text:
Q: Deriving Error for Trapezoid Rule. Question on book's answer (if it's correct or not). This is the question given in the book and is related to the error associated with the trapezoidal rule:
Consider the integral $I(h)=\int_{a}^{a+h} f(x) dx$. Establish an expression for the error term for each of the following rules:
a. $I(h) ~ hf(a+h)$
b. $I(h)$ ~ $hf(a+h)-1/2h^2f'(a)$
c. $I(h)$~$hf(a)$
d. $I(h)$~hf(a)+$1/2h^2f'(a)$.
For each, determine, the corresponding general rule and error terms for the integral:
$\int_{a}^{b} f(x) dx$, where the partition is uniform; that is, $x_i=a+ih$ and $h=(b-a)/n$ for $0\leq i \leq n$.
Here's the book answer for parts a and b:

Is the answer for part b incorrect?
Shouldn't it be $I(h)=\int_{a}^{a+h} f(x) dx$-($hf(a+h)-1/2h^2f'(a)$) =$(1/6-1/2)h^3f''(c_i) $=$-1/3h^3f''(c_i)$, not $-1/6h^3f''(c_i)$, which the book has?  Also isn't the answer for part c the same as the answer for part a? While the answer for part b should be the same answer as part b: $-1/3h^3f''(c_i)$?

A: If you assume that for an $n$-point formula, the error is $Ch^{n+1}f^{(n)}(\xi)$, which isn't always true then we can plug in an $n^{\text{th}}$ degree polynomial for which the quadrature formula predicts a value of $0$ and so get the error directly.
$$\int_a^{a+h}(x-a-h)dx=\left.\frac12(x-a-h)^2\right|_a^{a+h}=-\frac12h^2=hf(a+h)-\frac12h^2f^{\prime}(\xi)$$
$$\begin{align}\int_a^{a+h}\left[(x-a)^2-h^2\right]dx&=\left.\left[\frac13(x-a)^3-h^2x\right]\right|_a^{a+h}=\frac13h^3-h^3=-\frac23h^3\\
&=hf(a+h)-\frac12h^2f^{\prime}(a)-\frac13f^{\prime\prime}(\xi)\end{align}$$
$$\int_a^{a+h}(x-a)dx=\left.\frac12(x-a)^2\right|_a^{a+h}=\frac12h^2=hf(a)+\frac12h^2f^{\prime}(\xi)$$
$$\int_a^{a+h}(x-a)^2dx=\left.\frac13(x-a)^3\right|_a^{a+h}=\frac13h^3=hf(a)+\frac12h^2f^{\prime}(a)+\frac16f^{\prime\prime}(\xi)$$
So you weren't quite careful enough with parts $c)$ and $d)$, getting a sign and a factor of $2$ off. Actually we can show that the error formulas are correct here but it gets a little ugly, especially in part $b)$. We can start with
$$q(x)=\frac{\left[(x-a)^2-(y-a)^2\right]f(a+h)+\left[h^2-(x-a)^2\right]f(y)+(a+h-y)(y-x)(x-a-h)f^{\prime}(a)}{\left[h^2-(y-a)^2\right]}$$
For which $q(y)=f(y)$, $q(a+h)=f(a+h)$, and $q^{\prime}(a)=f^{\prime}(a)$, and assuming $a<y<a+h$ we can apply Rolle's theorem twice to find that there is some $a<u<a+h$ such that $f^{\prime\prime}(u)-q^{\prime\prime}(u)=f^{\prime\prime}(u)+\frac{-2f(a+h)+2f(y)+2(a-h-y)f^{\prime}(a)}{h^2-(y-a)^2}=0$, then solve for $f(y)$ and integrate from $a$ to $a+h$ and we get our error formula. It only works because the denominator in the last expression has the same same for $a<y<a+h$... but that's probably more in depth than required today.


text:
Q: Back-up restoration via iCloud for WhatsApp's stuck I have just re-downloaded Whatsapp and wanted to restore the chats that I have backed up. However, this occurs:

It has been stuck at 99% for the whole evening. I have tried following the guide WhatsApp published online but to no avail.
Is there anything that anyone knows which can help?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generic to assess if a parameter is "instanceof a generic class" if constructor is private I am trying to assert in a function if an object is instance of a class with type predicate.
function assertClass<CL extends new (...args: any[]) => any>(v: any, theClass: CL, message: string): v is CL
{
    let is = v instanceof theClass ;
    assert(is, message);
    return is;
}

(credit)
And it works except when the constructor of the class is private
class Cat{}
class Dog{
    private constructor(){
    }
    static async build(){
        let ret = new Dog();
        await somethingElse();
        return ret;
    }
}
let animal: Cat | Dog;
async function createAnimal(){ if (new Date().getTime() % 2) return new Cat(); else await Dog.build();}
animal= createAnimal();
assertClass(animal, Cat, 'should be a Cat');
assertClass(animal, Dog, 'should be a Cat');  // Cannot assign a 'private' constructor type to a 'public' constructor type

Is there a way to overcome this?


text:
Q: Literal syntax vs. mutableCopy and Objective-C compiler warnings I've more experience with Python than anything else, so to work with mutable vs. immutable arrays and dicts is a little weird.  I'm really enjoying the literal syntax that Xcode 4.5 has added, but in doing some simple messing about I come across a situation like this:
NSArray *myArray = [@[/*array objects here*/] mutableCopy];
[myArray addObject: @/*an object goes here*/];

and the compiler gives me a warning, stating "myArray may not respond to addObject".
The code compiles and addObject works just fine, I can NSLog the object and verify it exists in myArray - but I don't fully understand the nature of this warning.  Does mutableCopy not return an NSMutableArray in this situation?  Is it more appropriate to simply use NSMutableArray and not dink around with trying to (over)use literal syntax?
Also, since it's just a silly warning, can I ignore it and carry on?  That seems... lazy at worst, and maybe just opens the door to shenanigans in the future.

A: You need to declare your variable as NSMutableArray, not NSArray. addObject: is a method only available on NSMutableArray.
EDIT: You also seem to have an unnecessary @ in there. Your code should be:
NSMutableArray *mutable = [@[a, b, c] mutableCopy];
[mutable addObject:d];

A:
Does mutableCopy not return an NSMutableArray in this situation?

It does. That's why you have to assign the return value to an NSMutableArray, and not an NSArray.
NSMutableArray *myArray = [@[/*array objects here*/] mutableCopy];

should make the compiler shut up.


text:
Q: Is it possible in Red to test value? for a variable inside a context not in global context? In last example, probe value? 'a returns true as it detects 'a has value in global context. But I'd like to test 'a exclusively in local context, is there a syntax to do so ?
    context [
        probe value? 'a; false
    ]

    context [
        a: 1
        probe value? 'a; true
    ]

    ; would like false instead of true
    a: 1
    context [
        probe value? 'a; true
    ]

A: I think the simplest check would be
context [
    probe in self 'a ; none
]

It returns none instead of false, but that is the only other falsy value anyway, so it's totally appropriate to check against. If you need it to be false, you can put to-logic in front.

A:
Is it possible in Red to test value? for a variable inside a context not in global context?

By definition, no.  Because there is no such thing as "the global context".
Remember that "Rebol (Red) actually does not have scope at all" ... "Rebol (Red) fakes it."
(See: Is there a overall explanation about definitional scoping in Rebol and Red)
Rebol has BIND? for asking an arbitrary ANY-WORD! where it's bound to (if anywhere).  Red calls this CONTEXT?.  So what you can do is ask if the binding of a word is to a context you care about.
ctx1: context [a: 10]
ctx2: context [a: 20]

word: bind 'a ctx1

print ctx1 = context? word ; true
print ctx2 = context? word ; false

So if what you mean by "global context" is actually the so-called SYSTEM/WORDS object, then that can be your test:
context [
    probe value? 'a ; false
]

context [
    a: 1
    probe system/words <> context? 'a ; true
]

a: 1
context [
    probe system/words <> context? 'a ; false
]

As to whether this is appropriate for your purposes, I don't know.  Just remember there's no scope in Rebol/Red, unless you rig up some fake approximation that works well enough for what you're doing.

A: Here a solution without searching in the 'global' system/words, but in the 'local' self
>> a: 1
== 1
>> context [
[        probe all [
[            find words-of self 'a
[            value? pick find words-of self 'a 1
[        ]
[        probe value? 'a
[    ]
none
true
== make object! []
>>
>> context [
[        probe all [
[            find words-of self 'a
[            value? pick find words-of self 'a 1
[        ]
[        probe value? 'a
[        a: 2
[    ]
none
false
== make object! [
   a: 2
]
>>
>> context [
[        a: 2
[        probe all [
[            find words-of self 'a
[            value? pick find words-of self 'a 1
[        ]
[        probe value? 'a
[    ]
true
true
== make object! [
    a: 2
]


text:
Q: PHP Does Not Seem To Play Nicely With An XML String? I am creating an application where a users draws shapes on a canvas and then saves and retrieves them from a database. The saving part works fine, now though, im trying to load this XML content, Thats where the troubles are starting.
Firstly a user has a list of documents they have created, when clicked it loads that document into the applicaiton to do this, i use the following code, firstly a javascript function which takes the ID of the document, then sends it to a PHP script which retrieves that documents data from a database. The PHP script than loads that documents data into a $_SESSION['data'] variable. Once done, it goes back to the javascript function which redirects the user to application page.
function loadDocument(docID){
    $.ajax({
        url: "load_a_document.php",
        type: "POST",
        data: {
            documentID: docID,
        },
        success: function(data)
        {
            alert(data); //THIS DISPLAYS THE XML WITH NO PROBLEMS???
            window.location = "application.php";
        }
    });
};

The PHP queries the database and retreives the name and XML content of the document, it then does this:
$_SESSION['document_Name'] = $doc_NAME;
$_SESSION['document_XML'] = $doc_DATA;

echo($_SESSION['document_XML']); //this is 'data' on the ajax success call

Now when the PHP is finished it echoes the php context, this shows up in the alert box in the success:{} of AJAX with no problems. Now it takes the user to the actual application which begins like so:
<?php
session_start();

$document_Name = $_SESSION['document_Name'];
$document_Data = $_SESSION['document_XML'];
?>
<script>
    alert(" <?php echo $document_Name; ?> "); //WORKS FINE
    alert(" <?php echo $_SESSION['document_Name']; ?> ") //WORKS FINE

    //alert(" <?php echo $document_Data; ?> "); //STOPS THE PAGE LOADING
    //alert(" <?php echo $_SESSION['document_XML']; ?> ") //STOPS THE PAGE LOADING
</script>

Fetching the first two items, there are no problems, as soon as XML data is printer then their is a real problem. I dont understand why the loadDiagram() can alert
() the XML but my application page cannot. Has the data been corrupted somehow?
Thanks for any feedback.

A: You probably have quotes in the string that's causing the problem. Try
alert(<?php echo json_encode($document_Data) ?>);


text:
Q: Retrieve toplevel site's subsites using REST _api I'm currently working on an iOS app which uses _api-services to retrieve data stored in documents libraries of a SharePoint Online. Consuming _api/web/Lists/ works well so far. At the moment the REST service URL is fixed for each site i want to access.
What I need is a way to retrieve all available sites genericly, so that the users only have to enter their toplevel site and credentials and all available sites will be listed. So I need a service call which delievers me the [site]-information for triggering further calls on the related subsites.
http://toplevelsite.sharepoint.com/[site]/_api/web/Lists/...

Does the REST _api offer a possibility to get all sites and subsites or even the whole site structure?
Thanks for any advice solving my problem

A: How to retrieve sub webs under root web
The following REST endpoint
https://contoso.sharepoint.com/_api/site/rootWeb/webinfos

will return the  collection of sub webs (WebInfo objects) under root web

How to retrieve sub webs under relative web
Assume the following site structure:
-- Root
    |
    -- Community
       |
       -- Feedback

Then the following REST endpoint:
https://contoso.sharepoint.com/community/_api/web/webinfos

will return the Feedback sub web  under Community web

A: If the users have sufficient permissions you can use webinfos. But sometimes users do not have access to some of the subsites. Then SharePoint pops up the login prompt and the call does not work (401 error). In this case you have to use /_api/web/Webs and set effectivebasepermissions in the query string.
I have written a relevant post here
http://gbasagiannis.me/2016/01/27/find-first-level-subsites-sharepoint-2013-with-rest-api/


text:
Q: How do you get the SurveyMonkey SDK to upload images on iOS and Android? We are trying to integrate the SurveyMonkey SDK with our iOS app and Android app for user feedback. Everything seems to be working, except we are unable to upload images from photo library/camera on both platforms. Upon attempting to upload, the SDK becomes unresponsive, or it returns directly to the app without submitting the response. However, if you submit without trying to upload a photo from the library, the response will be accepted.
Any help would be great. Thanks!

A: Derek, I'm an engineer who works on the SDKs for SurveyMonkey. Unfortunately file upload is not yet supported by the iOS/Android SDKs. We're working on adding support in Android, but iOS will remain unsupported for the time being due to a known issue in iOS UIWebviews.
Wish I had a better answer for you, but stay tuned.


text:
Q: Where can I find documentation on what "\char" does? I've seen samples of TeX using
\char`\\

to produce a literal backslash. Where can I find documentation on what the \char command does? Is it a generic construct to safely produce reserved literals?

A: I cite the TeX By Topic book by Viktor Eijkhout.
Here is a an excerpt

\char is basically just for conversion of numbers to a character representation, using the underlying encoding.
'82 uses octal numbers, "82 means hexadecimal numbers.
The last sentence in this excerpt says all: typeset character number so-and-so


text:
Q: Spring request hangs when HttpServletResponse/HttpServletRequest are added as method parameters Following the example provided by spring.io for creating a simple REST service, I run into a strange issue.
If I make a request to localhost:8080/greeting the greeting route is called and I receive the expected response:
{"id":1, "content":"Hello, World!"}

If I add a route "/test" and then make an HTTP GET request to localhost:8080/test I get the expected response:
I'm a teapot

The problem arises when I do one of two things. Firstly, if I add HttpServletResponse or HttpServletRequest as a parameter to the test route and make an HTTP GET request to localhost:8080/test, the request hangs, the route is not called/executed, and maybe but not always the following is returned:
BODY: OK STATUS CODE: UNKNOWN 43

The second case is when I try to overcome this by using the @Autowire annotation. If I remove the HttpServletResponse/HttpServletRequest method parameters and instead autowire them in as class members, I get the same behavior.
If I make a request to any other invalid/undefined route e.g. HTTP GET localhost:8080/undefinedroute I receive the expected 404.
package hello;

import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    //@Autowired
    //HttpServletRequest request;

    //@Autowired
    //HttpServletResponse response;

    @RequestMapping("/test")
    public String index() {
       return HttpStatus.I_AM_A_TEAPOT.getReasonPhrase();
    }

    //@RequestMapping("/test")
    //public String index(HttpServletResponse response) {
       //response.setStatus(HttpStatus.I_AM_A_TEAPOT.ordinal());
       //return HttpStatus.I_AM_A_TEAPOT.getReasonPhrase();
    //}

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

A: You cannot autowire HttpServletRequest or HttpServletResponse, because these objects are created when the server receives and handles an HTTP request. They are not beans in the Spring application context.

The status code of your response is 43 (unknown) because of this line:
response.setStatus(HttpStatus.I_AM_A_TEAPOT.ordinal()); // status 43?

ordinal() gives you the position of enum declaration, not the value of the status code. I_AM_A_TEAPOT is the 43rd enum declared in HttpStatus. The request hangs because 43 is an invalid status code and your browser does not know how to deal with it. You should use:
response.setStatus(HttpStatus.I_AM_A_TEAPOT.value()); // status 418


text:
Q: How to swap Fragment dynamically? I am little confuse How to use Fragments in Android apps!  I am beginner in android and I am trying to build an apps for tablet 7 Landscape as you seen in the image below!
A, B, D How to swap fragment! By click event. When user click on A the content of A moved and shows in D and content of D shows in A and so on.
I want to be able to swap the content of A,B,and D dynamically!
What I should use? Fragment, Fragment Activity.
For example if D showing Video in VideoView, then when user click on A I want D to show TextView or any kind of data (but is not video View)
as well as showing the Video in A.
<pre>
<!-->
////////////////////////////////////////////
/ -------   -----------------------------  /
/ -  A  -   -                           -  /
/ -     -   -                           -  /
/ -------   -                           -  /
/ -  C  -   -            D              -  /
/ -     -   -                           -  /
/ -------   -                           -  /
/ -  B  -   -                           -  /
/ -     -   -                           -  /
/ -------   -----------------------------  /
////////////////////////////////////////////
<-->
</pre>

What I did is I made 4 fragment and put them inside the Main_Activity
fragment_A   I have problem with swap the content with D.
fragment_B   I have problem changing the content of D.
fragment_C   I connected with Fragment_C class that shows some static data.
fragment_D   I have problem with swap the content with A.
I am happy to for you suggestions!
Thanks!

A: You can try and go check FragmentTransaction
Check out replace / add / remove fragment methods. I'm sure you'll find what you are looking for.
ex :
FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(container, fragment);
        fragmentTransaction.commit();

and stuffs like :
FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(container, newFragment);
        fragmentTransaction.commit();

Where container is a simple View (RelativeLayout or other things).
EDIT :
Example :
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<LinearLayout
    android:id="@+id/fragment_snapshots"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/fragment_snap1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/fragment_snap2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

<fragment
    android:id="@+id/big_fragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />

</LinearLayout>

This layout specify, almost - except I only have 2 fragments on the left, what you are trying to do.
Then using onClickListeners and the function I gave you above, you might be able to do what you want.
Your containers will be the different IDs I put (big_fragment, fragment_snap1 & fragment_snap2.

A: you have to implement listeners .. go through following link :-
http://developer.android.com/training/basics/fragments/communicating.html


text:
Q: Check connection details to SQL Server 2000/2005 I want to migrate some DBs hosted on SQL 2000/2005 to SQL 2014, I don't have direct access to DBs and I want to know all applications connecting to it and connection details. Is there any best way to get this information? I tried using DB profiling but its not allowed as its taking up lot of space on hosted DB server which causing disruptions.
Any better way like an SQL statement or Remote connection monitoring will be helpful.
Thanks in advance for all your help.

A: To find out the names of processes that connect to the DB server in 2000/2005, you will need to run a job, probably every 30 seconds or even more often.  That job will have to store the results into a temp table and then add new process names and databases, and perhaps logins.  Here is a start:
Create a table to accumulate the information:
create table DBUsage_accumulate (
    [id] int identity(1,1) NOT NULL,
    [LoginName] SYSNAME NOT NULL,
    HostName SYSNAME NOT NULL,
    DBName SYSNAME NOT NULL,
    CONSTRAINT PK_DBUSAGE_ACCUMULATE PRIMARY KEY CLUSTERED (id asc));

Then you need to have an unique constraint on this table, use an index:
CREATE UNIQUE NONCLUSTERED INDEX
    IX_ACCUMULATE_LOGIN_DB_HOST
on DBUsage_Accumulate
(
    LoginName asc
    ,HostName asc
    ,DBName asc
);

and now you need to periodically run a check on sp_who2:
CREATE TABLE #temp_sp_who2
    (
      SPID INT,
      Status VARCHAR(1000) NULL,
      [LoginName] SYSNAME NULL,
      HostName SYSNAME NULL,
      BlkBy SYSNAME NULL,
      DBName SYSNAME NULL,
      Command VARCHAR(1000) NULL,
      CPUTime INT NULL,
      DiskIO INT NULL,
      LastBatch VARCHAR(1000) NULL,
      ProgramName VARCHAR(1000) NULL,
      SPID2 INT
      --,RequestID INT NULL --comment out for SQL 2000 databases
    )

INSERT  INTO #temp_sp_who2
EXEC sp_who2;

CREATE TABLE #temp_sp_who2
    (
      SPID INT,
      Status VARCHAR(1000) NULL,
      [LoginName] SYSNAME NULL,
      HostName SYSNAME NULL,
      BlkBy SYSNAME NULL,
      DBName SYSNAME NULL,
      Command VARCHAR(1000) NULL,
      CPUTime INT NULL,
      DiskIO INT NULL,
      LastBatch VARCHAR(1000) NULL,
      ProgramName VARCHAR(1000) NULL,
      SPID2 INT
      --,RequestID INT NULL --comment out for SQL 2000 databases
    )

INSERT  INTO #temp_sp_who2
EXEC sp_who2;

delete from #temp_sp_who2
where exists (
    select 1 from DBUsage_accumulate A
    where A.LoginName = #temp_sp_who2.Loginname
    and A.HostName = #temp_sp_who2.hostName
    and A.DBName = #temp_sp_who2.dbname);

insert into DBUsage_accumulate(LoginName,HostName,DBName)
select
distinct
    LoginName
    ,HostName
    ,dbname
from #temp_sp_who2
where [DBName] is not null
and [HostName] != '  .';

Placing the last chunk of SQL into a job that runs every 5-30 seconds will accumulate a list of all host names, DB names and logins.  You can use this to migrate the correct databases and logins as well as to amend connection strings in client machines.
Tested in 2000.


text:
Q: Using included mode that doesn't have a MIME in CodeMirror.overlayPerser() getMode works with modes that have MIME like text/plain or text/html. How can I make it work with jinja2? This doesn't work:
CodeMirror.defineMode("htmljinja", function(config, parserConfig) {
    return CodeMirror.overlayParser(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), CodeMirror.getMode(config, "jinja2"));
});

"text/jinja2" doesn't work either. How can I do this without coping the whole mode/jinja2.js in my file?


text:
Q: How to concat hour with date in python I have a pandas dataframe where date and hour is in two different columns as shown below -
I want to concat these two columns to have a new datatime column where I can apply pandas window/shift functions. Please share your views.
        date          hour
0       20190409       0
1       20190409       0
2       20190409       0
3       20190409       0
4       20190409       0

A: Use pandas.to_datetime and pd.to_timedelta and add them together:
df['datetime'] = pd.to_datetime(df['date'], format='%Y%m%d') + pd.to_timedelta(df['hour'], unit='H')


text:
Q: Is there way to formalize the idea that a category can be "cocomplete from the inside"? Let $\mathrm{KSet}$ denote the category of all countable sets, including the finite ones. Then $\mathrm{KSet}$ is finitely complete. Furthermore, $\mathrm{KSet}$ admits all countable colimits, or, less formally, it is "cocomplete from the inside." Is there way to formalize this idea (that a category can be "cocomplete from the inside") using structuralist language?

A: Let $\mathcal{S}$ be a category with pullbacks. An $\mathcal{S}$-indexed category $\mathbb{C}$ is a pseudofunctor $\mathcal{S}^\mathrm{op} \to \mathfrak{CAT}$, and $\mathbb{C}$ is said to be $\mathcal{S}$-cocomplete if the following conditions are satisfied:

*

*For each object $X$ in $\mathcal{S}$, the category $\mathcal{C}^X = \mathbb{C} (X)$ has finite colimits.

*For each morphism $f : X \to Y$ in $\mathcal{S}$, the functor $f^* : \mathcal{C}^Y \to \mathcal{C}^X$ preserves finite colimits.

*For each morphism $f : X \to Y$ in $\mathcal{S}$, the functor $f^* : \mathcal{C}^Y \to \mathcal{C}^X$ has a left adjoint, say $\Sigma_f : \mathcal{C}^X \to \mathcal{C}^Y$.

*The functors $\Sigma_f : \mathcal{C}^X \to \mathcal{C}^Y$ satisfy the Beck–Chevalley condition with respect to pullback squares in $\mathcal{S}$.

Observe that there is an obvious $\mathcal{S}$-indexed category $\mathbb{S}$ defined by $X \mapsto \mathcal{S}_{/ X}$. $\mathbb{S}$ automatically satisfies the last two conditions, and $\mathbb{S}$ is $\mathcal{S}$-cocomplete precisely when it is an extensive category with (pullbacks and) pullback-stable coequalisers. In particular, the category of countable sets is such a category.
We can dualise the above to obtain the notion of an $\mathcal{S}$-complete $\mathcal{S}$-indexed category. $\mathbb{S}$ is $\mathcal{S}$-complete if and only if $\mathcal{S}$ is a locally cartesian closed category; and if $\mathcal{S}$ also has finite colimits, then it is also $\mathcal{S}$-cocomplete.


text:
Q: AES encrypted string from objective C is not decrypted by Java decrypt function Hi i have encrypted a string using BBAES library in objective C . After which i passed it to server through webservices . But i keep on getting this error from server , error = "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"
I am able to decrypt that string locally with same library but Java decryption is throwing this error. (This code decrypts correctly when encrypted string sent from Android)
JAVA settings and function:
/** The Constant PASS_PHRASE. */
private static final String PASS_PHRASE = "PASS";

/** The Constant ITERATION_COUNT. */
private static final int ITERATION_COUNT = 1000;

/** The Constant KEY_SIZE. */
private static final int KEY_SIZE = 128;

/**
 * Instantiates a new aes util.
 */
public AesUtil() {
    this.keySize = KEY_SIZE;
    this.iterationCount = ITERATION_COUNT;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw fail(e);
    }
}

 /**
 * Decrypt.
 *
 * @param salt
 *            the salt
 * @param iv
 *            the iv
 * @param passphrase
 *            the passphrase
 * @param ciphertext
 *            the ciphertext
 * @return the string
 */
public String decrypt(String salt, String iv, String passphrase, String ciphertext) {
    try {
        SecretKey key = generateKey(salt, passphrase);
        byte[] decrypted = doFinal(Cipher.DECRYPT_MODE, key, iv, base64(ciphertext));
        return new String(decrypted, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw fail(e);
    }
}

 /**
 * Generate key.
 *
 * @param salt
 *            the salt
 * @param passphrase
 *            the passphrase
 * @return the secret key
 */
private SecretKey generateKey(String salt, String passphrase) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize);
        SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
        return key;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw fail(e);
    }
}

 /**
 * Random.
 *
 * @param length
 *            the length
 * @return the string
 */
public static String random(int length) {
    byte[] salt = new byte[length];
    new SecureRandom().nextBytes(salt);
    return hex(salt);
}

IOS code :
// BBAESSaltDefaultLength = 16 bytes
NSData* salt = [BBAES randomDataWithLength:BBAESSaltDefaultLength];
// BBAESPBKDF2DefaultIterationsCount = 1000 , keysize = 128
NSData *key = [BBAES keyBySaltingPassword:@"PASS" salt:salt keySize:BBAESKeySize128  numberOfIterations:BBAESPBKDF2DefaultIterationsCount];

NSString *secretMessage = [NSString stringWithFormat:@"{\"cli\":\"%@\",\"work\":\"%@\"}",[[NSUserDefaults standardUserDefaults] objectForKey:@"cli"],[[NSUserDefaults standardUserDefaults] objectForKey:@"work"]];
NSLog(@"Original message: %@", secretMessage);

NSData *BBIV = [BBAES randomIV];

NSData *encryptedBBData = [BBAES encryptedDataFromData:data IV:BBIV key:key options:BBAESEncryptionOptionsIncludeIV]; // This generates 64 byts

NSString *encryptedBBString =  [secretMessage bb_AESEncryptedStringForIV:BBIV key:key options:BBAESEncryptionOptionsIncludeIV];
NSLog(@"Encrypted message: %@", encryptedBBString);

NSString *decryptedMessage = [encryptedBBString bb_AESDecryptedStringForIV:nil key:key];
NSLog(@"Decrypted message: %@", decryptedMessage);

NSString *saltBBString = salt.hexadecimalString;
NSString *IVBBString = BBIV.hexadecimalString;

[request setHTTPBody:[[NSString stringWithFormat:@"{\"id\":\"%@\",\"mx_id\":\"%@\",\"payload\":\"%@\"}",IVBBString,saltBBString,encryptedBBString] dataUsingEncoding:NSUTF8StringEncoding]];

What might be wrong ? Can you please help me out ?
EDIT :
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"]; NSString *authString = [@"Bearer " stringByAppendingFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"jwtAuthToken"] ];
[request setValue:authString forHTTPHeaderField:@"Authorization"];
[request setValue:@"mobile" forHTTPHeaderField:@"source"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


text:
Q: how to handle the passwords in an emm android app? if i use the android managed configuration with all the app restrictions and so on... and the admin should set the credentials (example for a mail server) what is with security? All the values you define in the restrictions.xml file are set in plain text in the emm system. How can that be safe? and also if i understand everything right: the date also will send via google to the device... also in plaintext?
is there any different approach? or will all the restrictions send over the internet just always in plaintext?
thx

A: When sending data to and from Android devices, Android uses Transport Layer Security to provide communication security over the network. All data transferred to and from the server are encrypted. However, it's bad practice to store passwords in plaintext, so we would advise not including a field for passwords in your app restrictions. Gmail, for example, includes app restrictions for use with Exchange accounts; it allows the admin to specify a certificate alias for logging in, but it does not allow the admin to share the user's password via app restrictions (the user must login on the device).


text:
Q: Displaying Images in an Image Coordinate System I'm trying to programmatically do what's explained here. ('Focus on Image' to display an image in the Image Coordinate System.
I'm using a mosaic Layer to load an oblique dataset.
Currently I'm able to access a selected feature by getting the feature with:
ICompositeLayer compositeLayer = mosaicLayer as ICompositeLayer;
IFeatureLayer featureLayer = compositeLayer.Layer[1] as IFeatureLayer;

IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
ISelectionSet2 selectionSet = featureSelection.SelectionSet as ISelectionSet2;

ICursor cursor = null;
selectionSet.Search(null, true, out cursor);

IFeatureCursor featureCursor = cursor as IFeatureCursor;
IFeature feature = featureCursor.NextFeature();

and zooming to it with the answer from zoom to geometry
From here I would like to now view the selected feature's image in ICS.
This is currently only one aspect of what I'm trying to do with ArcObjects, which is make an add-in for Oblique display for Desktop.
Anything that would be helpful to first, display an image in ICS or to navigate an display Oblique Imagery using ArcObjects for ArcMap would be helpful
Using a selected footprint of a mosaicLayer How can I display the associated image in the Image Coordinate System?
Also, do I need to first load the raster from the selected footprint/FeatureLayer?

A: If you're using an Image service you can use IImageServer5's function "GetImageCoordinateSystem(int OID)"
https://desktop.arcgis.com/en/arcobjects/latest/net/IImageServer5_GetImageCoordinateSystem.htm
IMap map = ArcMap.Document.FocusMap;
IImageServer imageServer = GetImageServer(serviceUrl, serviceName);
IImageServer5 server5 = imageServer as IImageServer5;
map.SpatialReference = server5.GetImageCoordinateSystem(OID);
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;


text:
Q: Pretty URLs for File Uploads? Can files such as PDFs be uploaded to custom URLs? I would like to upload a PDF to www.example.com/whitepapers/pdf.pdf instead of www.example.com/wp-uploads/....
I found a plugin called WP Easy Uploader which seems OK, but I wanted to check if there are any other solutions.
One solution I was contemplating is to have the PDF treated as a page so I can assign a parent page to the PDF. This will handle any redirects in case the URL of the parent page is changed.
UPDATE - Not Considering WP Easy Uploader any more since I don't want to have any FTP access from within a Wordpress installation for security reasons.

A: Attachments in general (images, but also files like PDFs) have a special "attachment page" of the form example.com/main-post/attachment/file-title/. In most themes this is used to display a larger version of the image, still in the theme layout (so it returns a HTML file with the image in it, not the image directly).
You could exploit this by creating a template file that does serve the file directly, instead of just displaying it. Then if you create a page example.com/whitepapers/ with an attachment called file.php, the URL of the file will be example.com/whitepapers/attachment/file.
You would need to create a file in your theme directory called either attachment.php (if you want to do this for all attachments) or application.php (if you only want to do this for files with a mime type like application/*). In that file you get the attachment file location and then readfile() it to the browser. I guess there are already plugins out there that can do this for you.

A: UPDATE: Found Media Library Categories which sorts media by custom categories. All I need now is for a similar plugin to add that category to the URL so I can perform URL rewrites and get what I need!

Found a couple of plugins.
Relocate Upload allows you to upload to any folder and then have a drop down list when uploading media to place that new media in your custom locations. It looks ok but the files are placed in actual physical folders. It would be better if it could upload anything in one content folder and the 'folder' used in the link would be just a permalink. Also it did not work well on a quick localhost installation. It kept trying to access C:\wamp\www... instead of http://localhost/
Custom Upload Dir allows you to upload in custom directories but this did not meet my requirements.
About WP Easy Upload - I do not want to use it since I don't want to give FTP access to any plugin inside the installation for security reasons.

A: Solution #1 You can change your Media Path.  Go to Settings->Media
Change default "wp-content/uploads" to "whitepapers" of course if you upload other than whitepapers, this solution won't work so well.
Solution #2 Use Pretty Link to customize your path
I have been using Pretty Links since I've been using WordPress; a few years now.
Mostly to simplify paths to files.
You can map "abc.com/whitepaper/file.pdf" into "abc.com/wp-content/uploads/file.pdf"
http://blairwilliams.com/pretty-link/


text:
Q: linux df shows old mounts The df command shows old cifs mounts which aren´t existend anymore. The only active mount is
"//***/HR-Backup"

The system is debian wheezy. How can I get rid of the old entries, and why are they showing up?
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda1             29657164   2132588  26018068   8% /
tmpfs                   517208         0    517208   0% /lib/init/rw
udev                    512764        92    512672   1% /dev
tmpfs                   517208         0    517208   0% /dev/shm
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/Report-Calls-Redmine$/
                 292415096  67284924 225130172  24% /mnt/reporting
//***/he-backup$/
                 503313404 396248316 107065088  79% /mnt/backup
//***/HR-Backup
                 503313404 396248316 107065088  79% /mnt/backup

A: umount /mnt/backup

for all of them. I guess they're somehow still mounted when df displays them. What does
mount

display?


text:
Q: How not to match a token within quote like "hello w"orld in javacc I'm doing a redis-cli parser by using javacc. I have to handle the quote
for example set "a b" "cd", I hope key token is a b and value token is cd.
There is my solution:
RedisCommand.java
package com.demo.command;
public interface RedisCommand {
}

SetCommand .java
package com.demo.command;

public class SetCommand implements RedisCommand{

    private String key;

    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

RedisCommand.jj
options {
  STATIC = false;
  DEBUG_PARSER=true;
}

PARSER_BEGIN(RedisCommandParser)

package com.demo.parser;

import com.demo.command.*;
import java.util.*;

public class RedisCommandParser {

  public static void main(String args[]) throws ParseException {
    RedisCommandParser parser = new RedisCommandParser(System.in);
    parser.RedisCommand();
  }

}
PARSER_END(RedisCommandParser)

SKIP :
{
  <WHITESPACE: " " | "\t" | "\n" | "\r">
}

TOKEN :
{
  <K_SET: "set">
}

TOKEN :
{
   <SINGLE_QUOTE: "'">
   | <DOUBLE_QUOTE: "\"">
   | <SINGLE_STRING: <SINGLE_QUOTE> ((~["'"]) | "\\'" )+ <SINGLE_QUOTE>>
   | <DOUBLE_STRING: <DOUBLE_QUOTE> ((~["\""]) | "\\\"" )+ <DOUBLE_QUOTE>>
   | <RAW_STRING: (~[" "])+>
}

RedisCommand RedisCommand() :
{
  RedisCommand command = null;
}
{
  command=SetCommand() <EOF>
  {
    return command;
  }
}

SetCommand SetCommand() :
{
  SetCommand command = new SetCommand();
  String key = null;
  String value = null;
}
{
  <K_SET> key=StringParam() value=StringParam()
  {
    command.setKey(key);
    command.setValue(value);
    return command;
  }
}

String StringParam() :
{
  String s = null;
  Token token = null;
  String im = null;
}
{
  (token=<SINGLE_STRING> { im=token.image; s=im.substring(1, im.length()-1);}
  | token=<DOUBLE_STRING> { im=token.image; s=im.substring(1, im.length()-1);}
  | s=RawString()
  )
  {return s;}
}

String RawString() :
{}
{
  /* for reserved word
   * support like 'set set set'
   */
  (<K_SET>
  | <RAW_STRING>
  )
  {
    return token.image;
  }
}

SetCommandTest.java
package com.demo.command;

import com.demo.parser.ParseException;
import com.demo.parser.RedisCommandParser;
import org.junit.Test;

import java.io.StringReader;

public class SetCommandTest {

    @Test
    public void test() throws ParseException {
        //test1
        _test("set a b", "a", "b");

        //test2
        _test("set \"a b\" cd", "a b", "cd");

        //test3
        _test("set a\"b c\"d", "a\"b", "c\"d");

        //test4
        _test("set \"ab c\"d", "\"ab", "c\"d");
    }

    private void _test(String line, String expectKey, String expectValue) throws ParseException {
        RedisCommandParser parser = new RedisCommandParser(new StringReader(line));
        SetCommand command = (SetCommand) parser.RedisCommand();
        String key = command.getKey();
        assert key.equals(expectKey) : String.format("command[%s] key[%s] expect[%s]", line, key, expectKey);
        String value = command.getValue();
        assert value.equals(expectValue) :  String.format("command[%s] value[%s] expect[%s]", line, value, expectValue);
    }
}

test4 in SetCommandTest failed, error message is
Call:   RedisCommand
  Call:   SetCommand
    Consumed token: <"set" at line 1 column 1>
    Call:   StringParam
      Consumed token: <<DOUBLE_STRING>: ""ab c"" at line 1 column 5>
    Return: StringParam
    Call:   StringParam
      Call:   RawString
        Consumed token: <<RAW_STRING>: "d" at line 1 column 11>
      Return: RawString
    Return: StringParam
  Return: SetCommand
  Consumed token: <<EOF> at line 1 column 11>
Return: RedisCommand
java.lang.AssertionError: command[set "ab c"d] key[ab c] expect["ab]
    at com.demo.command.SetCommandTest._test(SetCommandTest.java:33)
    at com.demo.command.SetCommandTest.test(SetCommandTest.java:26)

It take "ab c" as <DOUBLE_STRING>, which is not what I want. I think the problem is <DOUBLE_STRING>, quote after space and quote before space should work fine. Not all quote string is <DOUBLE_STRING>. but I don't know how to do. Please help me


text:
Q: Share sheet icon on React-Native I've looked around everywhere I can think of and cannot for the life of me find out how to change the icon that appears in the Share sheet inside of react-native.
Is this even possible to customize?  I would love to put the app's icon in there.

A: When using a url only, it will automatically populate this icon with your link's favicon/web icon.
For a share sheet with a custom message it doesn't seem to be supported right now but, I would love to see this in the future.


text:
Q: Fluent NHibernate PersistenceSpecification I got the following error message:
System.IndexOutOfRangeException: Invalid index 9 for this SqlParameterCollection with Count=9..
And I absolutely wonder why oO?!
The database schema and the hbm.xml files were all correctly created with FluentNHibernate.
The error ocurrs in the CanCorrectlyMapBookmethod, the PersistenceSpecificationTest runs without an error.
[TestClass]
public class PersistenceSpecificationTests
{
    private static ISession _session;

    [TestInitialize]
    public void PersistenceSpecificationTest()
    {
        _session = Helper.CreateSessionFactory(false, false).OpenSession();
    }

    [TestMethod]
    public void CanCorrectlyMapBook()
    {
        new PersistenceSpecification<Book>(_session)
            .CheckProperty(p => p.IncludesCDDVD, true)
            .CheckProperty(p => p.Isbn, "1232324983sfdsdkfj")
            .CheckProperty(p => p.Name, "My Book")
            .VerifyTheMappings();
    }
}

The number 9 might come from the amount of columns the book has got. At first I thought I have to check all properties, but I tested this with another enity in another project and it worked correctly.
Anyone has an idea?
edit:
Here my domain object + mapping:
    public interface IEntity
    {
        int Id { get; set; }
    }

    public abstract class LoanedItem : IEntity
    {
        public virtual int Id { get; set; }

        public virtual DateTime DateOfIssue { get; set; }

        public virtual bool IsLoaned { get; set; }

        public virtual String Name { get; set; }

        public virtual Employee LoanedBy { get; set; }

        public virtual Release Release { get; set; }

        public virtual Publisher Publisher { get; set; }

        public virtual bool IncludesCDDVD { get; set; }

    }

    public  class Book : LoanedItem
    {
        public virtual string Isbn { get; set; }

        public virtual int Author { get; set; }

    }

 public class BookMap : ClassMap<Book>
    {
        public BookMap()
        {
            // identity mapping
            Id(p => p.Id).Column("BookID");

            // column mapping
            Map(p => p.Author);
            Map(p => p.Isbn);
            Map(p => p.IncludesCDDVD);
            Map(p => p.IsLoaned);
            Map(p => p.Name);

            // component mapping
            // Publisher
            Component(p => p.Publisher, m =>
            {
                m.Map(x => x.Name);
                m.Map(x => x.Homepage);
            });

            // Release
            Component(p => p.Release, m =>
            {
                m.Map(x => x.ReleaseDate);
                m.Map(x => x.ReleaseNumber);
            });

            // reference/association
            References(p => p.LoanedBy).Column("EmployeeID");
        }

EDIT:
Ok the problem above could be solved.
BUT how can I check a component? When I check a component with CheckProperty an error occurs ... "expected 'DomainModel.Model.Book' but get 'DomainModel.Model.Book' ... ugh :) well whats wrong there? it is exactly the same domain object. I created a new question

A: The problem probably are Name properties. You have 2 properties named "Name" - one in Book, and one in Publisher component. AFAIR FluentNHibernate will map BOTH of those properties to column "NAME" (check with generated hbms), which would result in an error you're getting.
Try to specify different column name for one of those properties (preferable in Publisher component - add a prefix or so) and see whether this helps.

A: I just tried your code in a new project, simplifying the POCOs and mappings to only what you're testing in your test class. This is what I have:
public abstract class LoanedItem
{
    public virtual int Id { get; set; }
    public virtual String Name { get; set; }
    public virtual bool IncludesCDDVD { get; set; }
}

public class Book : LoanedItem
{
    public virtual string Isbn { get; set; }
}

public class BookMap : ClassMap<Book>
{

public BookMap()
{
    // identity mapping
    Id(p => p.Id).Column("BookID");

    // column mapping
    Map(p => p.Isbn);
    Map(p => p.IncludesCDDVD);
    Map(p => p.Name);
}

And the test runner:
[TestClass]
public class PersistenceSpecificationTests
{
    private static ISession _session;

    [TestInitialize]
    public void PersistenceSpecificationTest()
    {
        var cfg = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.InMemory().UseReflectionOptimizer())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Book>())
            .BuildConfiguration();

        _session = cfg.BuildSessionFactory().OpenSession();
        new SchemaExport(cfg).Execute(false, true, false, _session.Connection, null);
    }

    [TestMethod]
    public void CanCorrectlyMapBook()
    {
        new PersistenceSpecification<Book>(_session)
            .CheckProperty(p => p.IncludesCDDVD, true)
            .CheckProperty(p => p.Isbn, "1232324983sfdsdkfj")
            .CheckProperty(p => p.Name, "My Book")
            .VerifyTheMappings();
    }
}

It's using an in-memory SQLite database. The test passes fine, so the problem must be elsewhere.


text:
Q: Regex to match numbers between dates I need some help to match some numbers that are between two dates, like this:
26/03/20213539-4 / 107512-826/03/2021R$
I tried (a lot), and in regexr.com my pattern works, but doesnt work when I try in PHP preg_match
My code:
$str = '26/03/20213539-4 / 107512-826/03/2021';
preg_match('/(?<=[0-9]{2}\/[0-9]{2}\/[0-9]{4})([^]*)(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})/', $str, $match);
echo $match;

Can someone tell me where is my mistake?

A: You're missing a quote of ^ in your POSIX character group. In your pattern, replace [^] with [\^]. Then it'll match.
Because you see, just [^] is not a valid group (it's not group with one character "^"). No, instead in your case: [^]*)(?=[0-9] it's na inverted group with ]*)(?=[0-9 characters (because syntax [^ ] inverts the group). So you must fix that somehow. Either by quoting \^, or introducing some other form of matching any character.
Did you want to match any character including newline? Because if that's the case then simply use . and add flag s (lowercase) - dot match all.
And instead of using preg_match(), you should use pattern($p)->test($string).


text:
Q: How to parse json array using php foreach? I want to get id,url,img and title of videos in the JSON data.My current code doesn't output anything
could any one tell me what i am doing wrong.Thanks
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2, true);
$i = 0;

foreach($data->videos as $values)
{
    echo $values->id . "\n";
    echo $values->url . "\n";
    echo $values->img . "\n";
    echo $values->title . "\n";
$i++;
}

data:
{
    "cat": {
        "id": "1234567",
        "source_id": null,
        "title_en": "first season",
        "description_en": "This is spring category ",
    },
    "videos": [{
        "id": "312412343",
        "url": "\/2015-07-17\/1abcd.mp4",
        "img": "image\/44\/\/2015-07-17\/1abcd.jpg",
        "title": "first",

    }, {
        "id": "2342343",
        "url": "\/2015-07-16\/2dcdeg.mp4",
        "img": "images\/44\/\/2015-07-16\/2dcdeg.jpg",
        "title": "second",

    }];

}

validated json data:
{
   "cat":{
      "id":"1234567",
      "source_id":null,
      "title_en":"first season",
      "description_en":"This is spring category "
   },
   "videos":[
      {
         "id":"312412343",
         "url":"\/2015-07-17\/1abcd.mp4",
         "img":"image\/44\/\/2015-07-17\/1abcd.jpg",
         "title":"first"
      },
      {
         "id":"2342343",
         "url":"\/2015-07-16\/2dcdeg.mp4",
         "img":"images\/44\/\/2015-07-16\/2dcdeg.jpg",
         "title":"second"
      }
   ]
}

A: Because you call
$data = json_decode($code2, true);

your $data is an array and not an object as you try to access it. So either access it as regular array, or change 2nd argument of json_decode() to false (or removeit as this is default), as this is what controls conversion behavior.
See docs: http://php.net/manual/en/function.json-decode.php
Your data is not a valid JSON (; at the end, redundant and missing comas - it's simply broken).
In case of such problems, var_dump() is pretty helpful to inspect what data you are really working with.


text:
Q: Issues with Text I'm pretty new to game development. I made a quick little 10-second Android project with Unity that just shows a few UI texts on-screen. It appears fine when I run it in Unity, but when I put the game onto my phone, the texts appear as pink blocks. Any ideas on what's going wrong?
Here's what happens:

A: The Case of broken connection of prefab.
This colour appears in Unity in case of missing resources. Either you've added a Font to it which is deleted or You've created a prefab of this text which is deleted (possible case).

A: Several hints:

*

*Maybe some material are missing (this magenta color appears when Material is missing).

*Maybe it is just some resolution issue (different resolution in game mode in the Unity editor than on your android device)

To fix the second point, you can set the Unity game mode's resolution to fit your Android device screen size by clicking the drop down menu under the "Game" tab (next to the scale slider). If you are using UI elements, you also have to set your Canvas Scaler to "Scale with screen size and giving him your Android device screen size.


text:
Q: How to send Parse query into another ViewController I'm trying to send over a query salesArray = [[NSMutableArray alloc]initWithArray:objects] into EditData, i can't for the life of me figure it out. i'm trying to fill a picker view..i get the query executed with [parseConnection parseProduct] but can't get the array over to EditData.m
ParseConnection.h
#import <Foundation/Foundation.h>
#import <Parse/Parse.h>
#import "Constants.h"
//#import "EditData.h"

@protocol ParseConnectionDelegate <NSObject>

@end

@interface ParseConnection : NSObject //<PFSubclassing>
{
  NSMutableArray *salesArray, *callbackArray, *contractorArray, *rateArray, *zipArray, *jobArray;
}

- (void)parseSalesman;

@property (strong, nonatomic) id<ParseConnectionDelegate> delegate; //added

@property (strong, nonatomic) UITextField *salesName;

ParseConnection.m
    #import "ParseConnection.h"

    @interface ParseConnection ()
    {
      //  NSMutableArray *salesArray, *callbackArray, *contractorArray, *rateArray, *zipArray, *jobArray;
    }
    @end

    @implementation ParseConnection

    #pragma mark - EditData PickerView
    - (void)parseSalesman {
        PFQuery *query = [PFQuery queryWithClassName:@"Salesman"];
        query.cachePolicy = kPFCACHEPOLICY;
        [query selectKeys:@[@"SalesNo"]];
        [query selectKeys:@[@"Salesman"]];
        [query orderByDescending:@"SalesNo"];
        [query whereKey:@"Active" containsString:@"Active"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            salesArray = [[NSMutableArray alloc]initWithArray:objects];
             // NSLog(@"adStr is %@",salesArray);
        }];
    }

EditData.m
#import "EditData.h"

@interface EditData ()
{
    NSMutableArray *salesArray, *callbackArray, *contractorArray, *rateArray;
}
@property (nonatomic, weak) UIStepper *defaultStepper;
@end

@implementation EditData
@synthesize custNo, leadNo, active, date, first, last, company, address, city, state, zip, phone, aptDate, email, amount, spouse, callback, saleNo, jobNo, adNo, photo, comment, rate, start, complete;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;  //fix
    self.listTableView.dataSource = self;
    self.listTableView.delegate = self;
    self.listTableView.rowHeight = UITableViewAutomaticDimension;
    self.listTableView.estimatedRowHeight = ROW_HEIGHT;
    self.listTableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
 // self.listTableView.tableHeaderView = view; //makes header move with tablecell

     ParseConnection *parseConnection = [[ParseConnection alloc]init];
    [parseConnection parseProduct];
      NSLog(@"adStr is %@",self.adName.text);

}

A: Instead of creating a salesArray inside ParseConnection, pass in the one you have inside EditData.  Then, in your completion block, add objects to it rather than initializing it.
Don't forget to init salesArray in EditData before passing it as a parameter to the parse... method.


text:
Q: How to remove the tiny invisible TikZ picture frame? Consider this example:
\documentclass{article}
\usepackage{tikz}
\usepackage[showframe]{geometry}
\usepackage{lipsum}
\begin{document}
\lipsum[1]

\noindent\begin{tikzpicture}
\draw (0,0)--(\linewidth,0);
\end{tikzpicture}
\end{document}

It gets a warning

Overfull \hbox (0.4pt too wide) in paragraph at lines 8--11

On my viewer, I can't even see the "too wide" part

Of course, it is very difficult to see it, because it is only 0.4pt! However, I don't like having such warnings pop-up, so how to make sure that the line perfectly fits the margin, i.e. set the "inner sep" of the "node" TikZ picture to exactly 0pt?
I know I can use \rule, etc. for this, but I have to draw something more in TikZ, so I use TikZ in the whole picture.
Thank you in advance!
Bonus question: You can see that I am using \noindent. Without modifications to \parindent, are there any better ways to do that?

A: This is more like a work-around, but the real cause for this issue is most probably related to the tikz environment internals.
\documentclass{article}
\usepackage{tikz}
\usepackage[showframe]{geometry}
\usepackage{lipsum}
\begin{document}
\lipsum[1]

\noindent\makebox[\linewidth]{%
\begin{tikzpicture}
\draw (0,0)--(\linewidth,0);
\end{tikzpicture}%
}

\end{document}

A: Lets fuzz it out using \hfuzz=0.4pt in your preamble.
\documentclass{article}
\usepackage{tikz}
\usepackage[showframe]{geometry}
\usepackage{lipsum}
\hfuzz=0.4pt
\begin{document}
\lipsum[1]
%https://tex.stackexchange.com/questions/50830/do-i-have-to-care-about-bad-boxes/50850#50850
\noindent\begin{tikzpicture}
\draw (0,0)--(\linewidth,0);
\end{tikzpicture}
\end{document}

For more information: Please visit the linked question for which @DavidCarlisle provided a great answer. Also, I think this answer only covers your bonus part :-).


text:
Q: semaphore like synchronization in ISR (Interrupt service routine) I have a queue where the put and pull functions of the queue are called when different interrupts happen. Is there a way to prevent race condition in this scenario?
While we can not wait on semaphores in interrupt service routines what is the best way to create a similar functionality.
We are using an ARM-Cortex A5 processor of a Zynq FPGA to develope the code.

A: Assuming that each interrupt causes the "Interrupt Disabled" state of the processor to be turned on, and assuming that the interrupts you are handling have the same priority (that is, one can't interrupt the execution of the other), then there already can be no race condition and your ISRs can just access the shared queue.
(When an interrupt occurs, the processor goes into interrupt disabled mode, pushes all registers onto the stack, jumps to the ISR entry point and continues execution there. Once the ISR is done, the "iret" instruction does the reverse of the entry. This simple description can be implemented differently in different processors and platforms.)


text:
Q: How to extract text from pdf (pdf available in public folder) in ReactJs...? Here I tried to extract and set the texts in one state, but I'm not able to console the text
const [text, setText] = useState('')

useEffect(() => {

    fetch('Docs/Introduction.pdf').then(res=>{
     let texts =  res.text()
    setText(texts)
    })

  }, [])

**console.log(text);**

But in console, I'm getting,

Here I need to get the all texts in texts state


text:
Q: Is it possible to develop IPhone applications with Java? I accidentally bumped into an ad like this: http://monotouch.net/DownloadTrial?ref=so1. Then I start to wonder if we have an equivalent thing in Java.
From my understanding, objective c is still the only language that people use to develop iPhone apps. Is this true?

A: There's this project. Which is interesting. It might be possible to do this, but the lastest version of the Developer Agreement will actually prohibit the use of tools like monotouch:
3.3.1 Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented API.

A: I'm not aware of any solution like that for Java, but in any case, learning Objective C and the recommended Apple way to do things is the best investment. Apple has a strong interest in preventing anyone from writing iPhone apps using anything but their tools, and they just enforced their position a little stronger today. Here's an article with more details.

A: No the iPhone does not support Java and Apple will not allow you to create an virtual machine for your app. There might be tools which help you convert Java code to Objective-C, C or C++ but then I would recommend teaching or using one of those rathen then taking a chance.


text:
Q: Как правильно организовать синхронизацию при помощи selection consistent примитивов Помогите разобраться что такое selection consistent примитивы, и как их правильно применять.
Я так понял что это когда объект монитора - примитив boolean потому что он всегда записывается за одну операцию. Но так и не понял что это дает и как конкретно это применить.
Объясните пожалуйста, на каком-нибудь элементарном примере, какую проблему это решает, и как именно этот принцип применять.


text:
Q: Как закрепить положение формы? Необходимо чтобы при старте программы окно появлялось в левом нижнем углу, и при это его нельзя было передвинуть. Заранее всем большое спасибо за помощь!

A: Ссылка из английской версии вопроса. И код перегрузки соответствующего метода с небольшим дополнением, чтобы окно появилось в левом нижнем углу:
protected override void WndProc(ref Message message)
{
    //Эта строка установит положение формы в левом нижнем углу
    this.SetDesktopLocation(Screen.PrimaryScreen.Bounds.Left, Screen.PrimaryScreen.Bounds.Bottom - this.Height);

    //этот код предотвратит возможность перемещения формы на экране
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MOVE = 0xF010;

    switch(message.Msg)
    {
        case WM_SYSCOMMAND:
           int command = message.WParam.ToInt32() & 0xfff0;
           if (command == SC_MOVE)
              return;
           break;
    }

    base.WndProc(ref message);
}

Этот код нужно добавить в код формы, которую хотите закрепить.
UPD:
В this.SetDesktopLocation(int x, int y) в принципе, можете передать любые координаты, которые можете рассчитать удобным для Вас способом с привязкой к размеру экрана и размеру формы.
Чтобы меню "Пуск" не перекрывало нижнюю часть формы, можете заменить
this.SetDesktopLocation(Screen.PrimaryScreen.Bounds.Left, Screen.PrimaryScreen.Bounds.Bottom - this.Height);

на
var wArea = Screen.GetWorkingArea(this);
this.Location = new Point(wArea.Left, wArea.Bottom - this.Size.Height);


text:
Q: Way to default the name of the generated XPS file? If a user prints a report, and they happen to be using the Microsoft XPS printer, i would like the default the filename to something meaningful.
i would have thought that the XPS printer would take the name of the print job, and use that as the default filename - but it doesn't.
Is there some other, programatic, way to default the name of the generated XPS file when i print to that printer? i was thinking there might be something like:

*

*a registry key

*global shared memory

*API call like SetDefaultXPSFilename()

*extended attributes about a print job

Example
Automate Excel to create a spreadsheet:
Excel xl = new ExcelApplication();
Workbook wb = xl.Workbooks.Add();
GenerateReport(wb);
wb.PrintOut();

Now if the user's default printer is the Microsoft XPS Document Writer, then the user will get:

i would like a way for that File name to be defaulted to something useful, such as:
20110729 - Chip Bank Settlement Sheet.xps

The user will accept the default filename, and files will organized automatically, rather than the user typing:
asdfadf.xps

References

*

*eggheadcafe: XPS Default File Name

*MSDN: XPS Name when Sent to Printer
Bump: 20110729 (12 months later)

A: Well,
here is a simple way (at least in my case):
(myPrintPage inherits from System.Drawing.Printing.PrintDocument)
    With myPrintPage
        With .PrinterSettings
            If .PrinterName = "Microsoft XPS Document Writer" Then
            .PrintToFile = True
            .PrintFileName = "c:\test.pdf"
            End If
        End With
        .Print()
    End With

I haven't found a way, yet, to determine whether or not the printer I have chosen is going to print into a file, hence the test on the printer's name.
In addition to above, here is a piece of code I found useful:
Let's say that my default printer is NOT the XPS Document Writer. My code needs to archive automatically some data, print a report in XPS, then offer the user to print the report on the default printer. In the second step, I need to change the PrinterSettings of myPrintPage.
Here is how:
  'save xps results
    'is the XPS printer installed?
    Dim myXPSfound As Boolean = False
    For Each s As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters
        If s.Contains("XPS") Then
            myXPSfound = True
            Exit For
        End If
    Next
    If myXPSfound Then
        'Manual settings of the XPS printerSettings
        Dim myXPSPrinterSettings As New Drawing.Printing.PrinterSettings
        myXPSPrinterSettings.Collate = False
        myXPSPrinterSettings.Copies = 1
        myXPSPrinterSettings.Duplex = Drawing.Printing.Duplex.Simplex
        myXPSPrinterSettings.FromPage = 0
        myXPSPrinterSettings.MaximumPage = 9999
        myXPSPrinterSettings.MinimumPage = 0
        myXPSPrinterSettings.PrinterName = "Microsoft XPS Document Writer"
        myXPSPrinterSettings.PrintRange = Drawing.Printing.PrintRange.AllPages
        myXPSPrinterSettings.PrintToFile = True
        myXPSPrinterSettings.ToPage = 1

        myPrintPage.PrinterSettings = myXPSPrinterSettings
        myPrintPage.PrinterSettings.PrintToFile = True
        myPrintPage.PrinterSettings.PrintFileName = mytargetFileName & ".xps"
        Try
            myPrintPage.Print()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Information, "Error Printing the XPS File")
        End Try
    Else
        MsgBox("The Microsoft XPS Writer was no found on this computer", MsgBoxStyle.Information, "Error Printing the XPS File")
    End If

It can be handy sometimes.

A: The Microsoft XPS Document Writer (MXDW) will generate an output file path without prompting the user if the application that prints sets lpszOutput in DOCINFO.
If you don't have access to the code of the application then another option is to build an XPS driver that generates a file path even when lpszOutput hasn't been set. The Windows Driver Kit (WDK) is the place to start.
For more details and links see this post.

A: Win2PDF 7 can save as XPS, and does default to the name of the print job.  If you don't want to use the print job as the name displayed in the File Save dialog, you can change the default file name by setting a registry value named "PDFTitle".
You can also set the output file without prompting either using the lpszOutput field of  DOCINFO, or by setting a registry setting named "PDFFileName" as described in the Win2PDF documentation.  The file will be created in the XPS format if the file name contains an .xps extension.


text: Q: How can I implement a live broadcast like Instagram live using Flutter? I'm working on a project and I intend to use the Flutter framework but is it possible to create a live video broadcast like that of Instagram or Facebook live?


text:
Q: How can I disable postfix on startup? I can't get cron to stop spamming me with completed job notifications. It's getting out of hand and starting to clog up my 'real' email server, so I'd like to just disable postfix while I figure out which job isn't going to /dev/null (any help on this is appreciated as well.)
I can stop the service, but everytime I reboot it kicks out all the emails it's been holding on to, and my mail server goes down ago.
How do I keep postfix from starting on boot, and how can I view its held messages?

A: Postfix is started in init.d, so you can use update-rc.d to disable it on startup:
sudo update-rc.d postfix disable

When you want to enable it again:
sudo update-rc.d postfix enable

Even if it's disabled you can still start it manually with sudo service postfix start.
If update-rc.d is not in your system, you'll have to install the package sysvinit-utils or sysv-rc, or similar (those are for 12.04, I don't remember if 10.04 use the same names).

As for the notifications, usually the email will give you a clue on which job sent it, but if you want to track all jobs run by cron, you can take a look at the crontab and /etc/cron.*. See the section NOTES in man cron for details.
crontab -l
sudo crontab -l
ls -lr /etc/cron.*

You could also check the syslog:
sudo grep -i cron /var/log/syslog

A: Stop the service as root: update-rc.d postfix disable
View the queue as root: showq
Also see the SEE ALSO section in the manual page on the Web.
Each cron job that does not need E-mail output redirects output to /dev/null: For example,
15 5 * * * command > /dev/null 2>&1


text:
Q: Hidden input type="file" submit on change I need a file upload button that does not look like the default "select file"-button.
Therefor I have a styled <button> and a hidden input[type="file"]
It appears however, that everytime I click on the <button> the parent <form> gets submitted and I do not understand why. There is no javascript triggering the form to submit. It submits while the filepicker-dialog is open so the POST request has no file sent at all.
I want it to submit the form but only after I selected a file (file-input has changed)
<form action="/upload.php" method="post" name="ta_file_upload" enctype="multipart/form-data">
    <input type="file" id="tableUpload1" name="files[]" style="visibility:hidden;" onchange="alert();" /> <!-- no alert is fired! -->
    <button class="btn btn-dark table-button table-button-upload" onclick="document.getElementById('tableUpload1').click()" title="Upload">UploadButton</button>
</form>

The alert(); is for testing purposes - it does not get triggered: no alert.
The error is not related to a specific browser (tested in chrome + firefox)


text:
Q: In R, exactly what causes an object of type name (or symbol) to be evaluated? After running:
x <- as.name("aa")
aa <- 2

in R, why doesn't
(x)

return 2?  And why doesn't
x <- as.name("aa")
aa <- 3
get(get(x))

return 3?
I know get() expects a string, but I don't understand why it doesn't evaluate x, find the string inside, and then get that. It seems to me like sometimes functions do such evaluation of their arguments, and sometimes they don't. For instance, in the second example, if you replace get(get(x)) with eval(x), eval() evaluates the x to find the name, and then evaluates the name to find 3.

A: I think @joran's answer is right but maybe I can try to explain a different way.
The ( "function" in R is essentially the identity function. It echoes back what you pass it. It's almost like it isn't there. There is no difference between what will be returned by these statements
x      #1
(x)    #2
((x))  #3

The parenthesis just passthrough the value inside. You can add as many parenthesis as you want and it will not change what's returned. The evaluator looks at ((x)), see the outer parenthesis, and knows to just return the value of the thing inside the parenthesis. So now it's parsing just (x), and again, it sees the outer parenthesis and will just return the value inside the parenthesis, which is x. The parenthesis just pass though the value from the inside; they do not evaluate it.
The bare value x is a name (or symbol). A name is not uniquely tied to a value. The mapping between names and values differs by environment. That's why names must be evaluated in a particular context to get a value. Consider these examples
aa <- 5
dd <- data.frame(aa=20)
x <- as.name("aa")
foo <- function(x) {aa<-10; eval(x)}

eval(x)
# [1] 5
foo(x)
# [1] 10
eval(x, dd)
# [1] 20

This behavior is actually highly desirable. It's what makes features that require non-standard evaluation work, like
subset(mtcars, hp<100)

When you are using the R console, it behaves as a REPL -- it reads your input, evaluates it, prints it, and then waits for the next input. Note that it only does one level of evaluation and the evaluation happens in the "current" environment. It does not recursively evaluate the returned value from an expression. So when you do
x <- as.name("aa")
x   # identical to (x)
# aa

when the REPL gets to the evaluation step, it evaluates the name x which points to the name aa. That's it. One level of evaluation. The name aa is not subsequently evaluated.
There is a note in the ?eval help page that says this:

eval evaluates its first argument in the current scope before passing it to the evaluator

There's not a "double" evaluation happening there. It is merely evaluating it's parameters just as any other function in R does. For examples
aa <- 5
bar <- function(x) print(x)
bar(aa+2)
# [1] 7

It prints "7", not "aa+2" because the function has evaluated it's parameter prior to printing. It also explains the differences between these two
dd <- data.frame(bb=20)
xx <- as.name("bb")
eval(bb, dd)
# Error in eval(bb, dd) : object 'bb' not found
eval(xx, dd)
# [1] 20

In the first eval() call, R is unable to evaluate bb in the current environment so you get the error. But note that
evalq(bb, dd)

does work because evalq does not try to evaluate the first expression parameter.

A: Because the value of x is not 2, it is the symbol (or name) aa. However, if you eval it:
> eval(x)
[1] 2

Similarly, get(x) doesn't work at all (i.e. produces an error) because as per the documentation for get, it's first argument must be an object name (given as a character string), where the parenthetical is meant to distinguish it from a symbol/name.
get only works with a character argument:
 > get("aa")
[1] 2

And a symbol (which I find less confusing than name) is not the same thing:
> identical("aa",as.name("aa"))
[1] FALSE

(as.name and as.symbol do the same thing.)
For an excellent explanation of the "evaluation of expressions" vs "evaluation of function arguments" distinction I mention below in a comment, see @MrFlick's answer.


text:
Q: Save context this I found some interesting problem. Task is to make wrapper to all child-functions, that will delay implementation.
function someFunc() {
  console.log(this.someProp);
}

var obj1 = {
  someProp: 1,
  method1: someFunc,
};

var obj2 = {
  someProp: 2,
  method2: someFunc,
};
Function.prototype.defer = function(ms) {
  let self = this;
  setTimeout(self, ms) //<<-- lose context(obj1, obj2)
};
obj1.method1(); // 1
obj2.method2(); // 2
obj1.method1.defer(1000); // 1 after 1 sec, now is undefined
obj2.method2.defer(1000); // 2 after 1 sec, now is undefined

A: Try preserving the execution context using the  bind. bind() allows set which specific object will be bound to this when a function or method is invoked.

function someFunc() {
  console.log(this.someProp);
}

var obj1 = {
  someProp: 1,
  method1: someFunc,
};

var obj2 = {
  someProp: 2,
  method2: someFunc,
};
Function.prototype.defer = function(ms) {
  setTimeout(this, ms) //<<-- lose context(obj1, obj2)
};
obj1.method1(); // 1
obj2.method2(); // 2
obj1.method1.bind(obj1).defer(1000); // 1 after 1 sec, now is undefined
obj2.method2.bind(obj2).defer(1000); // 2 after 1 sec, now is undefined

A: The direct calls to 'obj.method' work because when a function is called as a method of an object, this is set to the object the method is called on.
The defer function isn't called as a method of the object, it is called as a method of Function which is where it gets its this from
Least changes 'fix' to your code is:
function someFunc() {
  console.log(this.someProp);
}

var obj1 = {
  someProp: 1,
  method1: someFunc
};

var obj2 = {
  someProp: 2,
  method2: someFunc
};
Object.prototype.defer = function(func, ms) {
  typeof this[func] === 'function' && setTimeout(this[func].bind(this), ms) //<<-- lose context(obj1, obj2)
};
obj1.method1(); // 1
obj2.method2(); // 2
obj1.defer('method1', 1000); // 1 after 1 sec
obj2.defer('method2', 1000); // 2 after 1 sec

Depending on your real use case there are probably better ways to do this than adding methods to built in types. For example, making obj1, obj2 be instances of new classes that you declare that extend a base class in your code where you provide common methods like your defer() function.


text:
Q: How do I link Gradle to a native Android library and solve 'could not find method externalNativeBuild()'? I meet a problem when trying to build Telegram Source Code in Android Studio (https://github.com/DrKLO/Telegram).
I have installed NDK, CMake, LLDB.
But I got this error:
"Gradle sync failed: Could not find method externalNativeBuild()"
Here is my build.gradle:
    apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

configurations {
    compile.exclude module: 'support-v4'
}

dependencies {
    compile 'com.google.android.gms:play-services-gcm:9.6.1'
    compile 'com.google.android.gms:play-services-maps:9.6.1'
    compile 'com.google.android.gms:play-services-vision:9.6.1'
    compile 'com.android.support:support-core-ui:24.2.1'
    compile 'com.android.support:support-compat:24.2.1'
    compile 'com.android.support:support-core-utils:24.2.1'
    compile 'net.hockeyapp.android:HockeySDK:4.0.1'
    compile 'com.googlecode.mp4parser:isoparser:1.0.6'
}

android {
    compileSdkVersion 24
    buildToolsVersion '24.0.2'

    useLibrary 'org.apache.http.legacy'
    defaultConfig.applicationId = "org.telegram.messenger"

    sourceSets.main.jniLibs.srcDirs = ['./jni/']

    externalNativeBuild {
        ndkBuild {
            path "/jni/Android.mk"
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    signingConfigs {
        debug {
            storeFile file("config/release.keystore")
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD

        }

        release {
            storeFile file("config/release.keystore")
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD

        }
    }

    buildTypes {
        debug {
            debuggable true
            jniDebuggable true
            signingConfig signingConfigs.debug
            applicationIdSuffix ".beta"
        }

        release {
            debuggable false
            jniDebuggable false
            signingConfig signingConfigs.release
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        foss {
            debuggable false
            jniDebuggable false
            signingConfig signingConfigs.release
        }
    }

    defaultConfig.versionCode = 851

    sourceSets.debug {
        manifest.srcFile 'config/debug/AndroidManifest.xml'
    }

    sourceSets.release {
        manifest.srcFile 'config/release/AndroidManifest.xml'
    }

    sourceSets.foss {
        manifest.srcFile 'config/foss/AndroidManifest.xml'
    }

    productFlavors {
        x86 {
            ndk {
                abiFilter "x86"
            }
            versionCode = 2
        }
        armv7 {
            ndk {
                abiFilter "armeabi-v7a"
            }
            versionCode = 1
        }
        fat {
            versionCode = 3
        }
    }

    applicationVariants.all { variant ->
        def abiVersion = variant.productFlavors.get(0).versionCode
        variant.mergedFlavor.versionCode = defaultConfig.versionCode * 10 + abiVersion;
    }

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 24
        versionName "3.13.1"

        externalNativeBuild { ndkBuild {
                arguments "NDK_APPLICATION_MK:=jni/Application.mk", "APP_PLATFORM:=android-14"
                abiFilters "armeabi-v7a", "x86"
            }
        }
    }
}

apply plugin: 'com.google.gms.google-services'

It seems the Gradle has not linked to exist C++ library yet.
But, I didn't know how I manual link Gradle to exist Android.mk.
Any ideas?

A: A few guesses:

*

*Make sure you are using ndk-r12 or ndk-r13 (check your local.properties file). After you change ndk version, rm -fr TMessagesProj/.externalNativeBuild  [this is needed for current android studio]

*The only connection between gradle and native code is your top level Android.mk which is there already, just change its path to 'jni/Android.mk' [it needs to be relative path to your $project/build.gradle file.

*maybe jniLibs.srcDirs line in your build.gradle is not needed: the shared lib will be automatically packed into APK, unless you have other purposes. The built native libs are not saved there

I did have cmake installed, not sure that matters. https://developer.android.com/studio/projects/add-native-code.html. Your project could build with my fake json file, so your system should be pretty close.


text:
Q: Make error bar to a converted value Im trying to make errorbars to a already converted value. I have value in the dat file as uk gallons per minute and have now converted it into m^3/min.
My problem is that i cannot get my error bars when i also convert the value. Initially i just bracket the converting and then the accuracy on 0.0025(0.25%) but no error bars appear..
set yrange [34:37.5]
set xlabel "Time [min]"
set ylabel "Flow [m^3/min]"
plot '2015 08 30 0000 Pelletizer Feed (Wide).dat'  every ::2372::2459 using 4:($17*0.161) w l lc rgb 'green' title "Run 1", \
                        ''  every ::2372::2459 using 4:17:(($17*0.161)*0.0025) w errorbar lc rgb 'green' notitle, \
    '2015 08 30 0000 Pelletizer Feed (Wide).dat'  every ::2498::2565 using 4:($17*0.161) w l lc rgb 'blue' title "Run 2", \
                                ''  every ::2498::2565 using 4:17:(($17*0.161)*0.0025) w errorbar lc rgb 'blue' notitle, \
                        35.42 title "SP" with lines linestyle 2

A: When plotting with lines and with errorbars you are using different y-values. You have using 4:($17*0.161) for the lines, but using 4:17:(($17*0.161)*0.0025) for the errorbars, so that the errorbars are out of your yrange. Try:
set yrange [34:37.5]
set xlabel "Time (min)"
set ylabel "Flow (m^3/min)"
file = '2015 08 30 0000 Pelletizer Feed (Wide).dat'
set linetype 1 lc rgb 'green'
plot file every ::2372::2459 using 4:($17*0.161) w l lt 1 title "Run 1", \
  '' every ::2372::2459 using 4:($17*0.161):(($17*0.161)*0.0025) w errorbar lt 1 notitle


text:
Q: Filter pipe isn't working correctly angular 7 The problem I am having is when the page loads in and the API call is made the ngfor loop doesn't show all of the values, but when I type something in the search box to filter it works fine, what I want it to do is return all of the values when the search filter isn't applied when the page initially loads.

/*Filter Pipe*/
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(value: string, filterString: string, propName: string): any {
    if (value === null && value.length < 1 || filterString === '') {
      return value;
      /*This value isn't returning when fiter isn't applied on load*/
    }
    const resultArray = [];
    for (const item of value) {
      filterString = filterString.toLowerCase();
      if (item[propName].toLowerCase().indexOf(filterString) >= 0) {
          resultArray.push(item);

    }
  }
    return resultArray;
 }
}
/*Conponent*/
  ngOnInit() {
    this.api.getStopData().subscribe(
      data => {
        this.stations = data;
      }
    );
  }

<form class="form-inline md-form form-sm active-pink-2 mt-2">
  <input class="form-control form-control-sm mr-3 w-75" name="search" [(ngModel)]="search" type="text"
    placeholder="Search train stations" aria-label="Search">

</form>

<mdb-card class="m-1">

  <mdb-card-body>

    <mdb-card-title>

{{station.StationDesc}} Train Station

    </mdb-card-title>

  </mdb-card-body>
</mdb-card>

A: I'm assuming, you are not initializing search variable, as you have not mentioned above. If you are not initializing search variable in your component.ts, then on page load.
The value of search variable will be undefined not ''
Solution 1:
export class Component implements OnInit{
  search: string;

  constructor() {
   this.search = '';
  }

  ngOnInit() {
    this.api.getStopData().subscribe(
      data => {
        this.stations = data;
      }
    );
  }
}

Solution 2:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(value: string, filterString: string, propName: string): any {
    if (value === null && value.length < 1 || (filterString === '' || filterString === undefined)) {
      return value;
      /*This value isn't returning when fiter isn't applied on load*/
    }
    const resultArray = [];
    for (const item of value) {
      filterString = filterString.toLowerCase();
      if (item[propName].toLowerCase().indexOf(filterString) >= 0) {
          resultArray.push(item);

    }
  }
    return resultArray;
 }
}


text:
Q: Missing file or plugin on freshly installed Cloud9 ide? I'm currently trying to set up cloud9 on my debian server for node.js development. I followed some simple steps as described below, but there seems to be missing something and I would like to know how this can be resolved in the best way. Of course, I could start looking for the missing file on the web and put it there, but I think that's not the way to go.
What I did is this:

*

*ssh'ed into my Debian server into my home folder

*sudo git clone https://github.com/c9/core.git sdk (completed succesfully)

*cd sdk

*sudo ./scripts/install-sdk.sh
The installation finishes like this:
Success!
run 'node server.js -p 8080 -a :' to launch Cloud9

When I then start up the IDE with this command:
node server.js -p 1234 -l 0.0.0.0 -a rob:mypass -w /home/rob/myproject/

...everything looks good:
Starting standalone
Connect server listening at http://x.x.x.x:1234
Using basic authentication
CDN: version standalone initialized /home/rob/sdk/build
Started '/home/rob/sdk/configs/standalone' with config 'standalone'!
Cloud9 is up and running

and I can basically reach the IDE from my local browser. The problem is that it stops on the welcome screen with this loading indicator in the middle right under the cloud9 logo. The JS console shows a missing file (I've replaced my real URL):
http://myserver.de:1234/static/plugins/c9.ide.collab/notifications/bubble.js Failed to load resource: the server responded with a status of 404 (Not Found)

I then looked into the folder /home/rob/sdk/plugins/c9.ide.collab/, but it is empty.
What am I missing? Do I need to install something with npm or do I have to change the package.json file somehow? I'd really appreciate some help because I think wildly modifying and copying in files won't make things better.

A: edit: It turns out it was "bug in the script updating references [of some plugins]". Details: https://github.com/c9/core/pull/365
—Cheers!
Original answer:
I think think the c9.ide.collab plugin's refspec is wrong here: https://github.com/z3cka/core/commit/5f45ea38f422160a0030c5ef8d1efb19231bc78c#diff-b9cfc7f2cdf78a7f4b91a753d10865a2
I changed it back to #54aa1cbee0, ran the install-sdk.sh and it grabbed the latest version of the collab plugin. While prepping a PR, I just found 3 more plugins with bad refspecs

*

*c9.ide.language

*c9.ide.language.javascript.eslint

*c9.ide.run.debug
I'm currently working on a fix for the rest of these.


text:
Q: Is there a way to write a selector that will traverse the parentage of a tag until it finds a match? It doesn't look like there's a way to do this in jQuery, but I thought I'd ask you fine folks if there's a clever work around that will let me avoid parent().parent().parent() .
I'm basically looking to accomplish something like this: $('#myId').parent('li')

A: Try the .closest() selector
$('#myId').closest('li');

This will traverse up its ancestors in the DOM tree..
Check FIDDLE

A: You should use closest():
$(startElem).closest(selectorString);

Or, possibly parents():
$(startElem).parents(selectorString);

The main difference is that closest() will return zero or one matches (the first element it finds, or no elements if the selector doesn't match an ancestor), whereas parents() will return one, none or many elements (it continues up the DOM tree to the root element and returns all the found matches (if any).)
Incidentally, closest() will also search the starting-element, whereas parents() will only look at those ancestors starting from the starting-element's parent() node.
References:

*

*closest().

*parents().

A: You can use closest  or  parents.
The difference is that parents returns all parents li, closest returns the first.
References:

*

*http://api.jquery.com/closest/

*http://api.jquery.com/parents/

A: Use $('#myId').parents('li'). See: http://api.jquery.com/parents/


text:
Q: How to get No Records from SSRS to ASPX/ASCX I have a SSRS report and I just used it from my aspx and export it into excel directly without having ReportViewer. Now I want to check whether my DataSet having value or not. I can able to call the SP that I have used in SSRS to get the count. But I dont want to use that. Since I dont want to export to excel when there is no record or dataset is empty...!
Does anyone have any idea about how to return "No Records" from SSRS to ASPX/ASCX?

A: A simpler method would be to

*

*fetch the data from your stored procedure in your .net code

*check the no of records in the dataset

*If there are records, pass it to the report

*If not, show a "No Records" message

Here is how you can set the data source
reportViewer.LocalReport.DataSources.Add(
    new Microsoft.Reporting.WinForms.ReportDataSource(
    "MyData", dataset.Tables[0]));
reportViewer.RefreshReport();

You could now export this data to excel.


text:
Q: Clustered standard errors in 2-period Dif-in-Dif? in order to rectify invalid t-stats because of autocorrelation in Difference-in-Differences (DnD) models, Duflo et al (2004) propose (among other solutions) to collapse data so as to have a before-after DnD. My question: What if we already HAVE a before-after setting (e.g. pre-reform vs post-reform)? Would it be still ok to use clustered SE (provided the number of clusters would be high enough)? Or is it automatically wrong to use them EVEN IF we already have data that has 2 time periods only.
Would appreciate any comments. Thanks.

A: Bertrand et al. propose collapsing so that you don't have to cluster your standard errors. Just use a common t-statistic comparing two groups with unequal variances for your test:
$$\begin{equation*} \frac{\bar{y}_1 - \bar{y}_0}{\sqrt{\frac{\hat \sigma^2_0}{N_0} + \frac{\hat \sigma^2_1}{N_1}}} \end{equation*}$$
See that this assumes no correlation between observations within the pre- and post-periods and no correlation between pre- and post-periods. The first is a common cross-section assumption and Bertrand et al. show that the latter is reasonable in the panel context.
The above works when you have a balanced panel with all individuals experiencing the intervention at the same time. If this is not the case, perform the following regression. For each individual, get a pre-period average of the outcome $y$, $\bar{y}_{i0}$ and similarly a post-period average $\bar{y}_{i1}$. Now, for each individual, there are two observations: before and after. Turn this into a panel with $2N$ rows, where $N$ is the number of individuals. Run a regression on these data, including individual fixed effects and a treatment indicator.
Bertrand, Marianne, Esther Duflo, and Sendhil Mullainathan. 2004. "How Much Should We Trust Differences-In-Differences Estimates?" The Quarterly Journal of Economics 119 (1): 249–275.


text:
Q: Keyboard Driver for IOS : Background app intercepts bluetooth keyboard input I have rigged a custom bluetooth keyboard that needs drivers on the OS to interpret and output the desired characters.  This can be easily done on Windows.  However, I would like to have my keyboard work with IOS.
Do I need to get a background app to intercept the input and broadcast to foreground app?
Should I learn about Bluetooth driver?
What should I do?
Thanks in advance.
Peter

A: You can't implement iOS keyboard drivers without Apple's co-operation, so you're probably out of luck. There is no standard way on iOS to broadcast keystrokes to the foreground app either. You should probably try and get your custom bluetooth keyboard to implement the standard Bluetooth keyboard interface.


text:
Q: Page visibility API - check if browser is in background? According to http://www.w3.org/TR/page-visibility/,

On getting, the hidden attribute MUST return true if the Document contained by the top level browsing context (root window in the browser's viewport) [HTML5] is not visible at all. The attribute MUST return false if the Document contained by the top level browsing context is at least partially visible on at least one screen.

However, using the following script:
setInterval(function() {console.log(document.hidden);}, 1000)

it keeps printing false when the browser is running in the background, i.e. not visible at all. It does print true if I switch to a different tab, or minimize the browser, however.

A: PageVisibility API returns true only if the API is completely hidden. If your window is in the background, but even partially visible, it will return false.
Try putting it in the background, making it smaller than another window, then placing that window overtop. It now returns true.
You may want something like document.hasFocus instead (or some combination).


text:
Q: What the code for this symbol in latex? What is the latex code for the symbol?

A: Here https://detexify.kirelabs.org/classify.html, you can detexify any handwritten symbols.

A: It is \mathcal{G}
see also more letters here https://www.dafont.com/forum/read/9009/latex-mathcal


text:
Q: ValueError when try to convert a negative number from csv file to integer Hello i have the csv file below, imported with pandas data = pd.read_csv("1.csv"):
x1,x2,xb,y
−2,1,1,1

I need to convert the negative number (-2) to integer with int(), but i get ValueError:
print(data.iloc[1-1]['x1'])
> -2 # str

print(int(data.iloc[1-1]['x1']))
> ValueError: invalid literal for int() with base 10: '−2`

I haven't the error when try to convert positive number:
print(data.iloc[1-1]['x2'])
> 1 # str
print(int(data.iloc[1-1]['x2']))
> 1 # int

A: The "−" within "−2" is not a proper minus sign, looks like it but is not the same.
Your print would work like this:
print(int(data.iloc[1-1]['x1'].replace("−", "-")))

And if you don't want to replace the problematic minus signs with the correct ones one by one, you could do this operation on the whole column.
data['x1'] = data['x1'].str.replace("−", "-").astype("int")

A: The problem is that many unicode characters look like a minus sign...
The character that you are showing in your question is U+2212 MINUS SIGN. The character that is used for negative numbers is the ASCII U+002D HYPHEN-MINUS. While the print the same, they are different characters. You will have to clean up your data file...


text:
Q: Matplotlib plt.show() method does not pop out the window I have some problem with matplotlib's plt.show() method. When I run the following code, the plot is displayed inside IPython console. I am using Anaconda with Python 3.5
import matplotlib.pyplot as plt
import numpy as np
import csv

x = []
y = []

with open(r"F:\my_dir\example.txt", 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')
    for row in plots:
        x.append(int(row[0]))
        y.append(int(row[1]))

plt.plot(x,y, label = 'Loaded from file')

plt.xlabel("x")
plt.ylabel("y")
plt.title("This is my plot")
plt.legend()

plt.show()

example.txt is as follows.
1,3
2,6
3,1
4,8
5,9
6,2
7,9
8,5
9,4
10,17

I am also pasting the matplotlibrc file content here
The plt.get_backend() command on the console gives

'module://ipykernel.pylab.backend_inline'

I want the script to pop out the plot window. This used to happen earlier but now it has stopped. Please help

A: In Spyder, click Tools, Preferences, Ipython Console, Graphics. Under Graphics, change Backend to "automatic" instead of "inline".

A: Thanks pyan. This really helps.
But in addition, after following the above step, please restart your kernel to see the effect. Shortcut is "Ctrl+."