text:
Q: How to convert signal from Time domain to Frequency domain with Java I have one signal y. The signal gets values from 0 to 1. The signal is actually derived from the red channel (from RGB) from a smartphone's camera, normalized by mapping all values from the space [0,1,... 255] to the space [0 - 1] by dividing by 255.
I have another array x for storing the camera frames 0,1,2,3,...
What I want to do is to convert the signal y from time domain to the frequency domain using Java. I have tried to use the class provided here.
My code is
fftsize = powtwo(y.size()); //keep samples of a size of power of 2
Float[] rp = new Float[fftsize]; //rp is real part of signal (= y)
for(int i=0; i<fftsize; i++){
    rp[i]=y.get(i);
}

Float[] ip = new Float[fftsize]; //ip is the imaginary part of signal = 0
for(int i=0; i<fftsize;i++){
    ip[i]=0.0f;
}
fft(rp,ip);

where
public int powtwo(int size){  //this function estimates the next power of 2 (below the given int value).
while(!(Math.sqrt((double)size)-(int)Math.sqrt((double)size) == 0)){
    size--;
}
return size;
}

I'm not sure if I'm doing it right and I don't know the next steps for turning FFT to frequency domain signal.

A: You seem to have started off OK, apart from the fact that powtwo is horribly inefficient. (See this question for various alternatives which are much more efficient.)
The FFT you are using is "in-place", so the frequency domain real/imaginary parts are returned in the input arrays. What you do with this data depends on your specific requirements, e.g. if you want to generate a power spectrum (one of the most common uses of an FFT) you would do something like this:
// ...

fft(rp,ip);

Float[] spectrum = new Float[fftsize / 2];

for (int i = 0; i < fftsize / 2; i++)
{
    spectrum[i] = Math.sqrt(rp[i] * rp[i] + ip[i] * ip[i]);
}


text:
Q: How to get number of months, weeks, days and hours from now to a future time? I need to find out the number of months, weeks, days and hours left from now to a future time using Java. I can not use any third party library like Joda. How can I do that using just JDK classes?
So far, this is what I have come up with. It sort of works, except for some situations:
public class DateUtil {

public static Integer[] components(Date from, Date to) {
    Integer[] result = new Integer[4];
    //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    //df.setTimeZone(TimeZone.getTimeZone("EST"));

    Calendar fromCal = new GregorianCalendar();
    Calendar toCal = new GregorianCalendar();

    fromCal.setTime(from);
    toCal.setTime(to);

    int months = 0;
    do {
        fromCal.add(Calendar.MONTH, 1);
        ++months;
        //System.out.println(df.format(fromCal.getTime()));
    } while (fromCal.before(toCal));

    fromCal.add(Calendar.MONTH, -1);
    --months;

    int days = 0;
    do {
        fromCal.add(Calendar.DAY_OF_YEAR, 1);
        ++days;
    } while (fromCal.before(toCal));

    fromCal.add(Calendar.DAY_OF_YEAR, -1);
    --days;

    int hours = 0;
    do {
        fromCal.add(Calendar.HOUR_OF_DAY, 1);
        ++hours;
    } while (fromCal.before(toCal));

    fromCal.add(Calendar.HOUR_OF_DAY, -1);
    --hours;

    int minutes = 0;
    do {
        fromCal.add(Calendar.MINUTE, 1);
        ++minutes;
    } while (fromCal.before(toCal));

    result[0] = months;
    result[1] = days;
    result[2] = hours;
    result[3] = minutes;

    return result;
}

public static void main(String[] args) {
    try {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        df.setTimeZone(TimeZone.getTimeZone("EST"));

        Date from = df.parse("2014-03-29 00:00");
        Date to = df.parse("2014-05-29 00:00");
        Integer result[] = components(from, to);

        System.out.printf("Months:%02d Days:%02d Hrs:%02d Mins:%02d\n",
                result[0], result[1], result[2], result[3]);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

It produces unacceptable results when you have February in the middle and start date is end of the month. For example:
From: Dec 31, 2013
To: Dec 31, 2014
The difference will produce: 12 months, 3 days.

A: Why not use the Java classes Date and Calendar
These classes already have built in functionality to help you calculate difference between two Dates. Most of the Date methods seem to be deprecated so instead I would recommend Calendar. Good luck!

A: One of my colleagues eventually came up with the right answer. The problem with incrementally adding a month to a Calendar is that you go from Jan 31 to Feb 28 to Mar 28, instead of Mar 31. This adds inaccuracy. The solution is to add 1 month, 2 months, 3 months and so on to the original start date. Then you go from Jan 31 to feb 28 to Mar 31. Anyway, here is his solution, slightly altered by me.
public class TimeSpan {
    public int months;
    public int days;
    public int hours;
    public int minutes;
}

class DateCalculator {
    public static TimeSpan difference(Date later, Date earlier) {
        TimeSpan v = new TimeSpan();

        /* Add months until we go past the target, then go back one. */
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.months++;
        }
        v.months--;

        /* Add days until we go past the target, then go back one. */
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.days++;
        }
        v.days--;

        /* Add hours until we go past the target, then go back one. */
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.hours++;
        }
        v.hours--;
        while (calculateOffset(earlier, v).compareTo(later) <= 0) {
            v.minutes++;
        }
        v.minutes--;

        return v;
    }

    private static Date calculateOffset(Date start, TimeSpan offset) {
        Calendar c = new GregorianCalendar();

        c.setTime(start);

        c.add(Calendar.MONTH, offset.months);
        c.add(Calendar.DAY_OF_YEAR, offset.days);
        c.add(Calendar.HOUR, offset.hours);
        c.add(Calendar.MINUTE, offset.minutes);

        return c.getTime();
    }
     public static void main(String[] args) {
            try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    df.setTimeZone(TimeZone.getTimeZone("EST"));

                    Date from = df.parse("2013-01-31 00:00");
                    Date to = df.parse("2014-01-31 10:20");
                    TimeSpan ts = difference(to, from);

                    System.out.printf("Months:%02d Days:%02d Hrs:%02d Mins:%02d\n",
                                    ts.months, ts.days, ts.hours, ts.minutes);
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stubbing pino logger as class instance I have a custom log service, using a child instance of pinoLogger to log some things. Here is the code :
class LogService {
    ihmLogger = loggerPino.child({});

    async log(
        req: Request,
        level: number,
        message: string,
        additional?: string
    ): Promise<void> {
        //Context initialisation
        const logObj = this.initLogObj(
            req,
            ngxLoggerLevelToPinoLevel[level],
            message,
            additional
        );

        // Mapping log level with pino logger
        switch (ngxLoggerLevelToPinoLevel[level]) {
            case CONSTANTS.DEFAULT.LOG_NGX_LEVEL.ERROR:
                this.ihmLogger.error(logObj);
                break;
            case CONSTANTS.DEFAULT.LOG_NGX_LEVEL.WARM:
                this.ihmLogger.warn(logObj);
                break;
            case CONSTANTS.DEFAULT.LOG_NGX_LEVEL.INFO:
                this.ihmLogger.info(logObj);
                break;
            case CONSTANTS.DEFAULT.LOG_NGX_LEVEL.DEBUG:
                this.ihmLogger.debug(logObj);
                break;
        }
    }

    private initLogObj(
        req: Request,
        level: number,
        message: string,
        additional?: string
    ): ILog {
        const additionalObj = JSON.parse(additional || '{}');
        return {...};
    }
}

export default new LogService();

I'm trying to write unit-tests for this service. I'm using node-request-http to mock the Request object, successfully.
My problem concerns this child element. I'm simply trying to see if the correct function is called depending on the level, but I can't access it correctly. Here are the few syntaxes I tried :
[...]
import logService from './log.service';
import { loggerPino } from '../utils/logger';
[...]

it("test 1", async () => {
    sinon.stub(loggerPino,'child').returns({
        error: sinon.spy()
    });
    await logService.log(request, 5, 'msg', JSON.stringify({}));

    console.log('A',logService.ihmLogger.error);
});
// >> A [Function: noop]

it("test 2", async () => {
    const logger = sinon.stub(logService, 'ihmLogger').value({
        error: sinon.spy()
    });
    await logService.log(request, 5, 'msg', JSON.stringify({}));

    console.log('B',logger.error);
});
// >> B undefined

it("test 3", async () => {
    const logger = sinon.stub(logService, 'ihmLogger').value({
        error: sinon.spy()
    });
    await logService.log(request, 5, 'msg', JSON.stringify({}));

    console.log('C',logService.ihmLogger.error);
});
// >> C [Function (anonymous)]

I never could access the "callCount" valut, let alone checking the given parameter with a getCall(0).args[0]
How should I write the stub to be able to correctly access the value i'm trying to test?

A: The solution here was to completely replace the ihmLogger property of the service, as done in the "B" try up there, but putting it in a variable and checking the variable, not the sinon.stub object returned :
it("Log error called", async () => {
    const customLogger = {
        trace: sinon.spy(),
        debug: sinon.spy(),
        info: sinon.spy(),
        warn: sinon.spy(),
        error: sinon.spy(),
        fatal: sinon.spy()
    };
    sinon.stub(logService, 'ihmLogger').value(customLogger);
    await logService.log(request, 5, 'msg', JSON.stringify({}));

    expect(customLogger.error.callCount).to.eq(1);
    expect(customLogger.fatal.callCount).to.eq(0); //double check to avoid false positive
});

I'm not unit-testing the pinoLogger object (I have to trust if to work as intended), I'm unit-testing the correct branch & call.
Doing this, I'm also able to inspect the logObj transmitted :
const builtObj = customLogger.error.getCall(0).args[0]


text:
Q: SharePoint Online CustomAction redirect error I have a problem with the redirect in the <CustomAction> element where the button subscribes to
<CommandUIHandler Command = "Redirect.Command" CommandAction = "http://www.bing.com" />
On the redirect page I get an error like in the screenshot

There is no additional information and I have no idea what is wrong. Maybe some of you have encountered such a problem?


text:
Q: Change TextInput type="date" format in react-materialize I need to change the TextInput type="date" display/input format from mm/dd/yyyy to dd/mm/yyyy, I don't care if it is stored as YYYY-MM-DD, but I care about how it displays the input itself.
<TextInput
 label="Date Label"
 type="date"
 value={myDate}
 onChange={e => setMyDate(e.target.value)}
/>

I'm not using the full datepicker, I'm only setting the TextInput to type date.

A: A TextInput of type date is going to render a input with type date. Inputs of type date show the date in a format based on the locale of the user's browser.  This allows dates to be displayed in the format expected by the user and you should not alter this behavior.


text:
Q: Kubectl configuration changes are not saved via Rancher CLI I was trying to change some of my kubernetes cluster configuration via Rancher - kubectl CLI.
Eg: Modifications in namespaces, contexts etc.
https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/
But none of these changes persist if I close that active session. Kubeconfig defaults to previous config when I close the CLI.
Wanted to check if this is a Rancher issue, as I have no idea.
Eg: Executed the following commands to add/modify cluster and contexts.
kubectl config --kubeconfig=config-demo set-cluster development --server=https://1.2.3.4 --certificate-authority=fake-ca-file

kubectl config --kubeconfig=config-demo set-context dev-frontend --cluster=development --namespace=frontend --user=developer

Then saved the new kube config to environment variable $KUBECONFIG
export KUBECONFIG=$KUBECONFIG:config-demo

which resulted in new kube config, which was cross-verified using
kubectl config view

But when closed the cli session and opened a new session, and typed 'kubectl config view' , it showed the default config instead of new one.


text:
Q: Calling public function in another Controller? There are some similiar questions here on SO, but none of them has been answered.
How should i do this, the best way?
I can create a new instance of the other Controller class each time i want to use it's functions, but that seems to be bad in the long run, am i wrong?
Should i make the function (e.g. UserController.GetAllUsers()) shared?

A: I wouldn't suggest making the method accessible on the other controller.  In ASP.NET MVC, controllers can be created a number of different ways (injection, factories, etc) and you can't guarantee that you will emulate whatever mechanism is being used.
Rather, you should factor out your GetAllUsers method into a separate class/method which takes the parameters it needs to return its values.  Then, you would pass the appropriate values to that new class from both controllers.
The class should have no knowledge of ASP.NET MVC; you would pass those in from the controller instances themselves.


text:
Q: Collapse list of phrases by removing subsets in Python I have a series of phrases that occur in a larger text.  I would like to emphasize the phrases, but I want to first compact the phrases.  I am using Python 3.5 and NLTK for most of the processing.
For instance, if I have the sentence:

The quick brown fox jumped over the lazy dog

and the phrases

brown fox
quick brown fox

I want the resulting HTML to look like
The quick brown fox jumped over the lazy dog

not
The quick brown fox jumped over the lazy dog

It seems like I should be able to craft some sort of list comprehension that removes items that are a subset of of other items in the list, but I can't quite seem to wrap my head around it.  Any ideas about how I collapse my phrases to remove subsets of other entries?

A: If the terms are listed in a list:
terms = ['brown fox', 'quick brown', 'quick brown fox']

I would create a list of subsets by checking the term list against itself, and collecting all terms that are subsets of other terms in the list:
subsets = []
for x in terms:
    for y in terms:
        if x in y and x != y:
            subsets.append(x)

or using list comprehension:
subsets = [x for x in terms for y in terms if x in y and x != y]

then remove all the known subsets from the list of terms:
phrases = [x for x in terms if x not in subsets]

or in a one-liner (maybe not recommended since it's quite unreadable):
phrases = [z for z in terms if z not in [x for x in terms for y in terms if x in y and x != y]]

should give you:
>>> print(phrases)
['quick brown fox']

A: I think the best way will be to write your own parser for the same. This way rather than removing the additional  tags we wont insert them at all. You can one by one scan for the characters in the sentence and match them with characters in your phrases. If there is a match we insert the  tags at proper location.
Also I have arranged phrases in descending order of their length. So nested tags are automatically avoided. As soon as there is a match further phrases will not be checked.
Here is my parser:
#sentence is a string
#phrases are considered as list
def highlightphrases(sentence, phrases):
    phrases.sort(key=len, reverse=True)
    sentenceCharIndex = 0
    while sentenceCharIndex < len(sentence):
        for phrase in phrases:
            phraseCharIndex = 0
            while phraseCharIndex < len(phrase) and \
                  sentenceCharIndex + phraseCharIndex < len(sentence) and \
                  phrase[phraseCharIndex] == sentence[sentenceCharIndex + phraseCharIndex]:
                phraseCharIndex += 1
            if(phraseCharIndex == len(phrase)):
                sentence = sentence[:sentenceCharIndex+phraseCharIndex] +\
                           "" + sentence[sentenceCharIndex+phraseCharIndex:]
                sentence = sentence[:sentenceCharIndex] +\
                           "" + sentence[sentenceCharIndex:]
                sentenceCharIndex += phraseCharIndex + 6
                break;
        sentenceCharIndex+=1
    return sentence

Note : I am not basically a python programmer so please don't mind if code is shabby, let me know if the syntax for the answer can be improved in anyway. Do suggest edits. I am new to python and still learning the ways, suggestions are always welcome :)


text:
Q: Proving that homotopy equivalent spaces are n-connected for the same n I'm trying to prove that if $X$, $Y$ are homotopy equivalent then they are $n$-connected for the same $n$, without knowing about homotopy groups.
I am working with the second definition from
https://ncatlab.org/nlab/show/n-connected+space that does not use homotopy groups.
I tried to show that if $X$ is precisely $k-1$ - connected, then so is $Y$:
Let $X, Y$ be homotopic. So we have $f:X\to Y$, $g:Y \to X$ with $g\circ f \approx id_X$ and $f \circ g \approx id_Y$
By assumption there is some $t: S^{k-1}\to X$ that is not extendable to some $\widetilde{t}:B^k \to X$.
Define $q:S^{k-1} \to Y$ by $q = f \circ t$. Assume towards contradiction that $q$ is extendable to some $\widetilde{q}: B^k \to Y$.
Then we can take $\widetilde{t}: B^{k} \to X$ by $\widetilde{t}= g \circ \widetilde{q}$.
By definition $\widetilde{t}(S^{k-1}) =g \circ \widetilde{q}(S^{k-1})$. But $\widetilde{q}$ is an extension of $q$, hence $\widetilde{q}(S^{k-1})= q(S^{k-1})$. This gives:
$$
\widetilde{t}(S^{k-1}) = g (\widetilde{q}(S^{k-1}))= g(q(S^{k-1})) = g(f(t(S^{k-1})))
$$
But $t(S^{k-1}) \subset X$ hence $g(f(t(S^{k-1}))) \approx t(S^{k-1})$, meaning that $\widetilde{t}(S^{k-1}) \approx t(S^{k-1})$.
(Equivalently we showed $\widetilde{t}\mid S^{k-1} \approx t$).
If instead of the homotopy equivalence at the end, i'll show equality, it will be a contradiction (An extension that was assumed to not exists).
I'm not sure how to show that equality (or is this attempt correct at all?).

A: I would say that you have made life more difficult by choosing a somewhat contorted proof strategy.
How about just proving this statement:

Assuming that $X$ is homotopy equivalent to $Y$, the following is holds for every $k \ge 1$: if every map $S^{k-1} \to X$ extends over $X$ then every map $S^{k-1} \to Y$ extends over $Y$.

This statement implies, all by itself, that $X$ is $n$-connected if and only if $Y$ is $n$-connected, because you can apply the statement with the roles of $X$ and $Y$ swapped.
I'll stop here, because I suspect you can prove this statement, but I'm happy to continue if you want more help.


text:
Q: Debug app in different devices I use MUPDF to view pdf files in an Android app. The app works fine with Samsung s6 and Nexus 5 (Android 5.x). However when using Samsung S3 (Android 4.3), it just breaks without saying anything in the debugger "the app just disappears without saying any". Is that regarding MUPDF lib? I know this lib has compiled native code. As it is a legacy code and I have to deal with it, what could be the approach to solve such issue?
Thanks.

A: Check the Android logcat output when the app dies, that should reveal what is happening. You may need to run the app outside the debugger to get the full logcat output. If you can get this, please edit your question to add the output.
Depending on which debugger you're using, you may need to explicitly enable native debugging if you haven't already.

A: MuPDF isn't legacy code, its continuously being developed. I'd suggest you open a bug report, that way you stand some chance of informed people being able to help you.


text:
Q: How can I make the Excel cell menu update when the keyboard's context menu key is pressed At the moment, I have code that runs in the Application's SheetBeforeRightClick event, but I've found that this code doesn't run when I press the keyboard's Context Menu key instead of using the right mouse button, which means that I get the wrong menu.
I could use the SheetSelectionChange event instead, but I'd imagine this would be quite error prone. Is there a more elegant way of doing it?

A: There is a BeforeContextMenu event you can use.
http://msdn.microsoft.com/en-us/library/aa193082(office.11).aspx
It should catch both the right click and the keyboard key.


text:
Q: Meaning of WinMain function call parameters?  int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdshow)

In this line, are these statements about the call parameters correct?
HINSTANCE is a class and hInstance and hPrevInstance are objects, PSTR is a class and pScmdline is an object and int is a class and iCmdshow is an object ?

A: Firstly, an object is a location in memory having a value and possibly referenced by an identifier. An object can be a variable, a data structure, or a function.
A class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions, methods).
 int WINAPI WinMain:

- it's the function used as EntryPoint of Win32 projects.
 HINSTANCE = Handle INSTANCE:

- it's a void pointer(void, int, bool... are types), not a class, is the base address of the module in memory.
 hInstance and hPrevInstance:

- are parameters of the WinMain function, hInstance is the handle to the current instance of the application, and the hPrevInstance is a handle to the previous instance of the application, hPrevInstance is always NULL. yes, this is an object because it's in some location in the memory.
PSTR:

- it's a pointer of a 8bit string
pScmdline:

- The command line for the application. it's also an object.
int:

- Is a type not a class.
iCmdshow:

- it controls how the window is to be shown (minimized, maximized, hidden...), it's an object of a type.
see this question about the difference between types and class:  What is the difference between Type and Class?

A: HINSTANCE is void * which is not a class, neither is int a class. They are types.
Please see this link for a definition of these types.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx


text:
Q: How are OWL defined datatypes intended to be used? Section 9.4 Datatype Definitions of the OWL 2 Web Ontology Language Structural Specification shows how custom datatypes can be defined, giving the following example:
a:SSN rdf:type rdfs:Datatype .

a:SSN owl:equivalentClass [
  rdf:type rdfs:Datatype ;
  owl:onDatatype xsd:string ;
  owl:withRestrictions (
    [ xsd:pattern "[0-9]{3}-[0-9]{2}-[0-9]{4}" ]
  )
] .

a:hasSSN rdfs:range a:SSN .

So here we're defining a new datatype a:SSN by restricting the xsd:string datatype via the xsd:pattern facet. So far so good.
But then the specification says something I don't understand:

The datatypes defined by datatype definition axioms … have empty lexical spaces and therefore they must not occur in literals.

Why would a:SSN have an empty lexical space here? It was defined by constraining the value space of xsd:string via xsd:pattern facet. Section 4.3.4 pattern of XSD 1.1 Part 2: Datatypes says that

… pattern is a constraint on the ·value space· of a datatype which is achieved by constraining the ·lexical space· to ·literals· which match each member of a set of ·regular expressions·.

So we're constraining the value space of xsd:string, but we're doing that by constraining the lexical space of xsd:string (the set of finite-length sequences of zero or more characters … that ·match· the Char production from XML) to literals that match the regular expression. So why does the OWL spec say that the lexical space of a:SSN is empty, rather than the the set of finite-length sequences of zero or more characters (as defined in XML) that match the regular expression [0-9]{3}-[0-9]{2}-[0-9]{4}?
More pragmatically, the OWL spec says

… there can be no literals of datatype a:SSN.

So does that mean that a:SSN cannot be used as follows?
a:Jane a:hasSSN "123-45-6789"^^a:SSN .

If so, how is one supposed to use the a:SSN datatype? Is the idea that one should write
a:Jane a:hasSSN "123-45-6789"^^xsd:string .

and infer from the declared range of a:hasSSN what the actual datatype is and thus whether value is valid?

A:
Why would a:SSN have an empty lexical space here?

Datatypes and literal values are notoriously difficult to handle in symbolic reasoning. When you have a symbolic logic, such as first order logic or description logics, symbols denote things that are arbitrary elements in arbitrary sets. You don't need to know what the symbols denote in order to perform correct and complete reasoning (for instance, http://dbpedia.org/resource/France may denote anything, as far as a reasoner is concerned, and it is impossible to constrain this IRI to denote a specific thing in FOL or DL).
For literals, it is a completely different story because they are quantified. They denote specific values in specific sets. For instance "10"^^xsd:integer denotes the number "ten" and nothing else. This matters for the reasoner, because it has to understand that this is different from what "10"^^xsd:string denotes, but the same as what "10.0"^^xsd:decimal denotes. This means that however you implement your reasoner, there must a part of the code specifically dedicated to processing the literals with datatype IRI xsd:integer. Thanks to this dedicated code, an OWL reasoner is able to infer:
<s> <o> "10"^^xsd:int .

from:
<s> <o> "10.0"^^xsd:decimal .

If an ontology can introduce new datatype IRIs that can be used on literals, then you don't have the specifically dedicated code for literals with these types. Now, consider the following:
ex:one  a  rdfs:Datatype;
  owl:equivalentClass  [
    a  rdfs:Datatype ;
    owl:onDatatype  xsd:positiveInteger ;
    owl:withRestrictions ( [ xsd:maxInclusive 1 ] )
  ] .

Then, should the following be a well formed literal, given this datatype definition?
"1.0"^^ex:one

You see, "1.0" is in the lexical space of xsd:decimal and maps to the numeric value "one" in this datatype. The value "one" is also part of the value space of xsd:positiveInteger, but "1.0" is not a valid lexical form for an xsd:positiveInteger. You could argue that ex:one must only use the lexical forms of xsd:positiveInteger because it is defined as a restriction of it. But the problem is that you then have a semantic description (a piece of ontology) that defines a syntactic constraint (the way you are allowed to write a literal with a specific datatype IRI). Logicians know that logics that allow one to constrain the syntax with their semantics are devilish.
Because of the OWL 2 specification where the lexical space of ex:one is empty, it is then possible to say that ex:one is the same datatype as ex:oneD defined as follows:
ex:oneD  a  rdfs:Datatype;
  owl:equivalentClass  [
    a  rdfs:Datatype ;
    owl:onDatatype  xsd:decimal ;
    owl:withRestrictions ( [ xsd:minInclusive 1 ] [ xsd:maxInclusive 1 ] )
  ] .

One more remark, though: what I'm saying here is only valid when you consider the OWL 2 Direct Semantics. If you consider the OWL 2 RDF-based semantics, then there are other things to consider. Especially, in the RDF-based semantics, it is not necessarily the case that ex:one is the same as ex:oneD. They may be distinct datatypes that happen to have the same value space.
Regarding your other questions:

So why does the OWL spec say that the lexical space of a:SSN is empty, rather than the the set of finite-length sequences of zero or more characters (as defined in XML) that match the regular expression [0-9]{3}-[0-9]{2}-[0-9]{4}?

Here, you are considering the xsd:string datatype, where the value space and the lexical space are the same. The lexical-to-value mapping is identity. So it looks like there would be a trivial way to allow the datatype IRI to be used on literals. But consider the broader problem as I showed you before.

So does that mean that a:SSN cannot be used as follows?

Exactly.

If so, how is one supposed to use the a:SSN datatype?

You can use datatypes defined in this way as the range of a property, for instance, or in allValuesFrom or someValuesFrom restrictions. However, when it comes to concrete values attached to instances, you have to use the datatypes that are natively supported by OWL 2 reasoners, as you suggest in your last code snippet.

A: It seems to me that a:SSN has an empty lexical space in the example because it isn't itself "the set of finite-length sequences of zero or more characters that match the regular expression [0-9]{3}-[0-9]{2}-[0-9]{4}." Rather, that is the definition of a:SSN. The definition itself was made by constraining a datatype (xsd:string) that does not have an empty lexical space, which is why the section on patterns that you cited applies. That is, the example uses a pattern to constrain a datatype with a non-empty lexical space to define a datatype with an empty lexical space. Accordingly, since "there can be no literals of datatype a:SSN," you would have to either infer that "123-45-6789"^^xsd:string is an SSN by the usage of a:hasSSN or by asserting that "123-45-6789"^^xsd:string is an instance of a:SSN.

A:
However, when it comes to concrete values attached to instances, you have to use the datatypes that are natively supported by OWL 2 reasoners, as you suggest in your last code snippet.

Else augment the capabilities of the reasoner, for your application. But don't expect these capabilities to be available when data is processed by a 'generic' OWL reasoner.


text:
Q: Como alterar a exibição do nome de usuário no terminal Ubuntu
Como posso alterar a exibição do meu nome de usuário no terminal ?
Com esse texto muito grande, acaba atrapalhando.

A: O que está longo nesse caso é o nome do sistema operacional. Edite o arquivo:
/etc/hostname
e altere com o nome que deseja. A alteração será efetuada no próximo logon.


text:
Q: using AND condition MYsql What I need is: when I give training_id 172 AND training_id 174 it have to return user 150 only

I tried this but it doen't work
SELECT user_id FROM Training_users WHERE training_id = 172 AND training_id = 174

Most of the times training_id might be more than 2

A: What about this query:
SELECT user_id, COUNT(*) as nbTrainings FROM Training_users
WHERE training_id = 172 OR training_id = 174
GROUP BY user_id
HAVING nbTrainings = 2

It will filter the users having the training 172 or 174. Then it will count how many trainings each user returned has and only keep the one(s) with two trainings.
This supposed that a user cannot have multiple trainings 172 and/or 174
The advantage of this against the multiple self-joins is that you don't have to join multiple times for each training id if you want to filter with more than 2 training id.
More info on GROUP BY and HAVING here
EDIT : After testing in sqlfiddle this seems to work and does not return wrong values if some users have multiple training_id and one being 172 or 174
Working sqlfiddle

A: This should work:
SELECT a.user_id FROM Training_users a, Training_users b WHERE a.training_id = 172 and a.user_id = b.user_id AND b.training_id = 174;

A: This should do it:
SELECT
  a.user_id
FROM
  Training_users a
RIGHT JOIN
  Training_users b ON a.user_id = b.user_id AND b.training_id = 174
WHERE
  a.training_id = 172

A: select user_id from work where training_id in (172,174) group by user_id  having count(*)  > 1;

Check SQLFiddle Demo

A: Do something like this
SELECT user_id FROM Training_users WHERE (training_id = 172) AND (training_id = 174)


text:
Q: Where should DTO be defined for a interface? I am trying to understand using interfaces to help layer a solution. I have a project within the solution that defines the interface. Then I have a second project that defines a new class that uses the interface defined in the first project.
The interface:
public interface IDocumentStore
{
    Case GetCaseByAccount(int accountId);
}

Using the above example where should I define the return class "Case"? Should it be defined in the interface project as a class? Or should it be defined as an interface too?
Most examples I've seen only return simple types, i.e. string, int, bool, so it is unclear to me where this class should be defined.
The interface will be used in the future for creating other Document Store providers.


text:
Q: how to solve this css issue? I am having some css issues...
When you hover over a product from here, you can see 'show now'..
But when you hover over the product from here, you can see 'Addto Cart' and you also see some black background for 'Add To Cart' which I am not understanding..
May I know what still I have to add in CSS..?
here is my code that displays products:

  [product.each]

              [product.name]

              <?php if ($product->saleprice > 0 &&  $product->saleprice < $product->price) { ?>

                   [product.currency mode='sign'][product.price]&nbsp&nbsp
                   [product.currency mode='sign'][product.saleprice]

                    <?php } else { ?>

                  [product.currency mode='sign'][product.price]

                <?php } ?>

                SHOP NOW

      [/product.each]

so, please tell me what am I missing..? you can find CSS code in source code...

A: They have used a background image.
In your case you need to set a background to .buttons or the anchor in there.
BTW: please stop using inline-stylsheets; use a separate


text:
Q: Convertir metodo recursivo a no recursivo tengo una duda con una practica. Tengo un metodo recursivo realizado pero me gustaria hacerlo sin la recursion, ¿alguien sabria hacerlo?
El metodo es este:
public int length(PositionList<Vertex<V>> path) {
        return lengthRec(path, path.first(), 0);
    }

    private int lengthRec(PositionList<Vertex<V>> path, Position<Vertex<V>> vert, int suma){
        Position<Vertex<V>> next = path.next(vert);
        if(vert.equals(path.last())) return suma;
        Iterator<Edge<Integer>> it = graph.outgoingEdges(vert.element()).iterator();
        while (it.hasNext()) {
            Edge<Integer> edge = it.next();
            if(graph.endVertex(edge).equals(next.element())) {
                int result = edge.element() + lengthRec(path, path.next(vert), suma); ;
                if(result!=0) return result;
            }
        }
        return 0;
    }

Muchas gracias


text:
Q: ¿Cómo crear un excel (.xlsx) desde Genexus ? utilito .Net https://wiki.genexus.com/commwiki/servlet/wiki?2476,ExcelDocument+data+type
Según en la documentación hay que descargar unos .DLL pero no logro comprender como y donde dejar dichos dll tambien dice que si es para java o Net son dll diferentes en este caso uso .net.
También hay un ejemplo pero claro al pegarlo y cambiarles  los datos no logra generar un excel solo columnas vacias si lo ejecutas desde un webpanel desde los eventos.

A: La eppplus.dll se distribuye con Genexus, deberia estar en el bin de Net (Ejemplo: C:\Program Files (x86)\GeneXus\GeneXus17U8\gxnet\bin)
Por lo que dices la planilla se genera pero vacia, si logra crearse el problema no es por la DLL, de pronto es por los datos que accedes.
De pronto es bueno que incluyas el código que programaste en este post o incluso poner valores "harcoded" del tipo:
&ExcelDocument.Cells(1, 1).Number = 50

Con eso deberia queda en la fila 1, columna 1 el valor 50.


text:
Q: Multi org deploy in hyperledger fabric I am following this tutorial to setup multi org deployment. After creating a card in step 8, I am unable to import the card. I get the following error:
Failed to load connector module "composer-connector-undefined" for connection type "undefined".
I've cross checked the connection profiles but could not find the reason.
Could you please help.

A: The version of the tutorial you are referring to is for "latest" which is Composer v0.19.  This tutorial directs you to create connection.json files in the v0.19 format.
If you are using Composer v0.16 you need to use a different version of the tutorial to create connection.json and cards of the right format.
https://hyperledger.github.io/composer/v0.16/tutorials/deploy-to-fabric-multi-org


text:
Q: php and html output and display UTF-16 characters I am having some difficulty understanding how to output a UTF-16 string with PHP and having it properly displayed in the web page..
The string is from a game (it is a name) and can contain any of the characters.
I would like to output the given string "ムName" as ムName which would be interpreted by the browser as the original string ("ムName"). Thanks.

A: <?php
$val="ムName";
echo mb_convert_encoding($val, 'HTML-ENTITIES','auto');
?>

demo: http://codepad.viper-7.com/YFnx4a (view frame source to see the encoding)


text:
Q: sql-macro The SCALAR SQL Macro behaves similar as a  macro in a programing language and enables to encapsulate complexity in SQL statements and avoid the usage of PL/SQL functions.
The TABLE SQL Macro enables implement the parametrized views   or polymorphic table function


text:
Q: pg_dump: abortando debido a que no coincide la versión del servidor Desde hace un tiempo he estado utilizando un script para realizar los respaldos de postgres pero desde que se actualizó la versión del servidor me da el siguiente error:

pg_dump: versión del servidor: 9.4.18; versión de pg_dump: 8.4.20
pg_dump: abortando debido a que no coincide la versión del servidor

No entiendo cual pueda ser el problema, a continuación dejo el script del respaldo, agradezco cualquier ayuda.

#!/bin/bash

HOME=/
PG_USER=usuario
DATABASE=basededados
SERVER=SERVER
DIR="Directorio a respaldar"
DATE=$(date +"%m_%d_%y")
FILE="$DATABASE_$DATE"
# pass @ .pgpass

PG_BAK_NOW () {
  pg_dump -h $SERVER -U $PG_USER $DATABASE -f $FILE.sql
}

echo "Ready to dump to $FILE" >> "$HOME/pg_status"

cd $DIR
if [ -f "$FILE" ];
then
  rm $FILE
  PG_BAK_NOW
else
  PG_BAK_NOW
fi

A: Yo esto lo resolví de la siguiente manera:
Como en el path por defecto tenia el pg_dump de la versión "vieja", busque donde estan los binarios de postgres (asumo linux porque veo el script bash, y en mi caso uso debian):
$ locate pg_dump
...
/usr/lib/postgresql/11/bin/pg_dump
/usr/lib/postgresql/11/bin/pg_dumpall
/usr/lib/postgresql/9.3/bin/pg_dump
/usr/lib/postgresql/9.3/bin/pg_dumpall
/usr/lib/postgresql/9.4/bin/pg_dump
/usr/lib/postgresql/9.4/bin/pg_dumpall
/usr/lib/postgresql/9.6/bin/pg_dump
/usr/lib/postgresql/9.6/bin/pg_dumpall
...

Entonces para que coincidan las versiones del servidor, usé el path absoluto del binario que corresponda
En tu caso, la linea del script debería ser:
/usr/lib/postgresql/9.4/bin/pg_dump -h $SERVER -U $PG_USER $DATABASE -f $FILE.sql


text:
Q: Get property value instead of just Id I have this line i an Umbraco solution, which gets me the ids of the nodes selected, comma seperated.
But what i want to get, in a oneliner, is a value of the node(s) selected.
So currently it is just returning the node id like "1001, 1000, 1003" or just "1003" if only one is selected.
What i want it to return, is a value of the selected node. Lets say its a menu title on the property i want. So instead of the above output, i want "Frontpage, Contact, About Us" etc.
How would that look?
var mynode = Page.Cache.GetById(id);
mynode.GetPropertyString("pages")

A: The simplest way would be to install the Umbraco Core Property Value Converters nuget package.  This would then provide you with an extension method that you can use to retrieve  a list of nodes in one go.  Then you could use LINQ to select the menuTitle property of each page.
var menuTitles = mynode.GetPropertyValue<IEnumerable<IPublishedContent>>("pages")
    .Select(x => x.GetPropertyValue<string>("menuTitle"));

If you need to you can then use string.Join() to combine the menu titles to get a comma-separated list.
Here's a list of using statements that you might need to add:
using System.Collections.Generic;
using System.Linq;
using Our.Umbraco.PropertyConverters;
using Umbraco.Web;
using Umbraco.Core.Models;


text:
Q: How come Goldstone boson, PQWQ axion, be able to have mass at all? Quote:

Goldstone's theorem: For every spontaneously broken continuous symmetry, there is a massless particle created by the symmetry current.

However, under $U(1)_{PQ}$ symmetry, I read that PQWW axion can obtain mass from $G\tilde{G}$.
Both these sentence make sense, but, being a Goldstone boson, there seemed to be a contraction around PQWW axion.
I read that this might be connect with the approximation from t' Hooft's determinental interaction. Could you explain to me what the determinental  interaction was?
Does that mean Goldstone's theorem only works for the first order of t' Hooft determinental interaction?
Does PQWW boson has mass or not?
Could you explain to me why a Goldstone could every obtain a mass?

A: Like the pions, the axion is a pseudo-Golstone boson, so it has a mass. The $U(1)_{PQ}$, as a chiral symmetry, is broken by quantum corrections by the axion's coupling to gluons, and so is no longer an exact symmetry. Goldstone's theorem them does not apply. This is completely analagous to the so-called '$U(1)$ problem', where the $\eta '$ was seen to be too heavy to be a Goldstone boson. The resolution of this puzzle by 't Hooft made physical the CP-violating $G\tilde{G}$ term in the Lagrangian, which is what suggests a QCD axions in the first place.

A: Two conditions for pseudo goldstone boson:

*

*The broken symmetry is not gauged, otherwise the (pseudo)
goldstone boson will be eaten by the gauge field.

*Something else (chiral anomaly in this case) breaks the symmetry
even before the spontaneous symmetry breaking is taking place.

To visualize, think about a tilted Mexican hat potential. The lateral move in the tilted Mexican hat groove would be uphills (non-zero mass), as opposed to being flat (massless) for the usual Mexican hat potential. The non-zero mass of the pseudo goldstone boson would be very small if there is only a tiny bit tilting.


text:
Q: Unexpected commandButton behavior The problem:
While the cursor is in the inputText and I press the "Enter" the dialog will popup
This is happen in Chrome but not via IE:
  <h:form id="mainForm" prependId="false">
        <h:inputText id="globalFilter" onkeypress="if(event.keyCode == 13){}"/>
        <p:commandButton id="Button1"
                         oncomplete="widgetVar.show()"/>
        <p:dialog id="Dialog1"
                  widgetVar="widgetVar"
                  appendToBody="true"
                  dynamic="true"/>
    </h:form>

How can I prevent it ?
Thanks

A: You can just add return false to stop this event.
Like onkeypress="if(event.keyCode == 13){return false;}"


text:
Q: Node.js error (could not find) while creating Hybrid app in visual studio 2013 I have done fresh installation of Visual Studio 2013 - update 3 and have installed Visual studio 2013 MDA (Multi Device Application), and also have installed setup for Node js..
But when I create New Hybrid - Application project it shows me an error of "Node.js cannot be found"
Please help me..

A: You need to have NodeJS installed on your system.
Get the installer from this page: http://nodejs.org/download/
After installation you should also check if node command is usable the command line (cmd).
If it's not available you will need to manually add NodeJS to your path.


text:
Q: How to get the client IP address in a JAX-RS resource class without injecting the HttpServletRequest? We are using JAX-RS 1.0 and I want to get the client IP address in my resource class. Currently I inject the HttpServletRequest as a method parameter and then get the IP address.
I want to make my code cleaner. I am thinking if I can use a MessageBodyReader class and set the IP address. But if I use a MessageBodyReader I have to unmarshall the XML to a Java object which is additional logic as far as I believe.
Can anyone please let me know how to get the client IP address without having to inject the HttpServletRequest.

A: There's no magic. What you can do is wrap the HttpServletRequest into a CDI bean with request scope (@RequestScoped) and then inject this bean into your JAX-RS resource classes:
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

@RequestScoped
public class RequestDetails {

    @Inject
    private HttpServletRequest request;

    public String getRemoteAddress() {
        return request.getRemoteAddr();
    }
}

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Stateless
@Path("client-address")
public class ClientAddressResource {

    @Inject
    private RequestDetails requestDetails;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response getClientRemoteAddress() {
        return Response.ok(requestDetails.getRemoteAddress()).build();
    }
}

I know this approach is not much different from injecting the HttpServletRequest. But there's no magic.


text:
Q: How to configure or enable Analytics in Self hosted Parse Server and Dashboard I am using self hosted Parse server with parse dashboard, My question is how to configure / Integrate or enable Parse Analytics.
Means how to enable or configure Analytics Adopters in Parse Server and enable Analytics widget in Parse Dashboard.
I do not want to use parse alternative analytics if its possible.
Any Help will be highly appreciated.

A: As of today (August 2018) it looks like Analytics with Parse Server is not supported.
https://docs.parseplatform.org/parse-server/guide/#analytics
It also seems that there are no plans to implement the Analytics feature in the open-source Parse Server.
https://github.com/parse-community/parse-server/issues/182
You could create your own "Class" and store whatever information you want in it, but you'd also need to build your own system for viewing that data.


text:
Q: Disabling ligatures in xelatex like rmligs Ligatures set by Latex are often wrong in German (i.e. between combined
words like "Auflaufform"). To set these words correct I often use rmligs
which is a great tool to disable ligatures when the use of them would be
wrong.
rmligs places a "| between the letters of a "wrong ligature".
Unfortunately the use of "| doesn't work for me if I use xelatex and
fontspec (it seems to require babel).
Is there a correct method to disable ligatures when I'm forced to use
xelatex and fontspec?
This is not a question about disabling only specific ligatures or disable ligatures generally.

A: I tried running rmligs on the following file
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{fontspec}

\begin{document}
Auflaufform
\end{document}

This resulted in writing out
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{fontspec}

\begin{document}
Auf"|lauf"|form
\end{document}

which I ran XeLaTeX on, getting

The same result is obtained if the original file is
\documentclass{article}
\usepackage[babelshorthands]{polyglossia}
\setmainlanguage[spelling=new]{german}
\usepackage{fontspec}

\begin{document}
Auflaufform
\end{document}

A: If using LuaLaTeX instead of XeLaTeX is an option for you, then running LuaLaTeX on
\documentclass[ngerman]{article}
\usepackage{fontspec,babel,selnolig}
\begin{document}
Auflaufform

auffällig

Stoffisolator
\end{document}

produces

without the need to run rmligs (or some other pre-preprocessor) on the input file.


text:
Q: This keyword is not pointing to the current object I have a react application where I am getting the property from the parent component, but when I try to set the state of the child using this.props, I am getting props is undefined error. I can understand that somehow this is not pointing to the current object. Can you please help me in resolving this issue. Thanks !!!
Error in the below line
count: this.props.value,

Full Code Below
import React, { Component } from "react";
import { throwStatement } from "@babel/types";

class Counter extends Component {
  constructor() {
    super();
    var self = this;

    this.incrementButtonClick = this.incrementButtonClick.bind(this);
    this.incrementDoubleClick = this.incrementDoubleClick.bind(this);
  }

  state = {
    count: this.props.value,
    tags: ["Markers", "Books", "Board"]
  };

  mySpanstyle = {
    fontSize: 10,
    color: "yellow"
  };

  render() {
    console.log("props ", this.props.value);
    return (
      <React.Fragment>
        {this.formatCount()}
        <button
          onDoubleClick={this.incrementDoubleClick}
          /* onClick={this.incrementButtonClick} */
          onClick={() => {
            this.incrementButtonClick("TEST");
          }}
          className="btn btn-primary"
        >
          Increment
        </button>

      </React.Fragment>
    );
  }

  incrementButtonClick(e) {
    console.log("Increment button clicked", e);
    console.log(this.state.count);
    this.setState({ count: this.state.count + 1 });
  }

  incrementDoubleClick() {
    console.log("Increment button Double clicked", this);
  }

  getSpanClass() {
    return this.state.count === 0
      ? "badge badge-warning m-2"
      : "badge badge-info m-2";
  }

  getMethod() {
    var value = () => {
      console.log("values ", this.props.value);
    };
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
  }
}
export default Counter;

A: Your constructor needs to accept props and your state should be initialized inside the constructor:
  constructor(props) {
    super(props);

    this.incrementButtonClick = this.incrementButtonClick.bind(this);
    this.incrementDoubleClick = this.incrementDoubleClick.bind(this);

    this.state = {
      count: this.props.value,
      tags: ["Markers", "Books", "Board"]
    };
  }

class Counter extends React.Component {
  constructor(props) {
    super(props);

    this.incrementButtonClick = this.incrementButtonClick.bind(this);
    this.incrementDoubleClick = this.incrementDoubleClick.bind(this);

    this.state = {
      count: this.props.value,
      tags: ["Markers", "Books", "Board"]
    };
  }

  mySpanstyle = {
    fontSize: 10,
    color: "yellow"
  };

  render() {
    console.log("props ", this.props.value);
    return ( <
      React.Fragment >
      <
      span className = {
        this.getSpanClass()
      } > {
        this.formatCount()
      }  <
      button onDoubleClick = {
        this.incrementDoubleClick
      }
      /* onClick={this.incrementButtonClick} */
      onClick = {
        () => {
          this.incrementButtonClick("TEST");
        }
      }
      className = "btn btn-primary" >
      Increment <
      /button> <
      br / >
      <
      /React.Fragment>
    );
  }

  incrementButtonClick(e) {
    console.log("Increment button clicked", e);
    console.log(this.state.count);
    this.setState({
      count: this.state.count + 1
    });
  }

  incrementDoubleClick() {
    console.log("Increment button Double clicked", this);
  }

  getSpanClass() {
    return this.state.count === 0 ?
      "badge badge-warning m-2" :
      "badge badge-info m-2";
  }

  getMethod() {
    var value = () => {
      console.log("values ", this.props.value);
    };
  }

  formatCount() {
    const {
      count
    } = this.state;
    return count === 0 ? "Zero" : count;
  }
}

function App() {
  return ( <
    Counter value = {
      1
    }
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render( < App / > , rootElement);


text:
Q: If I truncate a table, should I also add indexes I'm developing a rails application with MYSQL and I've created a migration for adding indexes to tables.
Also I have a rake task that truncates some of the tables and writes data.
ActiveRecord::Base.connection.execute("TRUNCATE #{Model.table_name}")

Do I need to add indexes again after truncate ?
Thank you in advance :)

A: No. The table is dropped and then re-created again (including any indexes and constraints)


text:
Q: Converting string to int from array I am trying to print out the exact location of an array element but am coming out short
string[] ocean = { "Beebo", "Jeff","Arthur", "Nemo", "Dory" };

foreach(string fish in ocean)
{
    if (fish == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!",int.Parse(fish));
        return;
    }
}

Console.WriteLine("He was not here");

I need the {0} token to be replaced with the array index of that element in this case with 3 but i am failing at the int.Parse(fish) which obviously isn't working

A: The easiest way to get this working is by switching to a for loop
for(int i = 0; i < ocean.Length; i++)
{
    if (ocean[i] == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!", i);
        return;
    }
}
Console.WriteLine("He was not here");

Alternatively you can keep track of the index in a foreach
int index = 0;
foreach(string fish in ocean)
{
    if (fish == "Nemo")
    {
        Console.WriteLine("We found Nemo on position {0}!", index);
        return;
    }

    index++;
}
Console.WriteLine("He was not here");

Or you can avoid the loop altogether and use Array.IndexOf.  It will return -1 if the value is not found.
int index = Array.IndexOf(ocean, "Nemo");
if(index >= 0)
    Console.WriteLine("We found Nemo on position {0}!", index);
else
    Console.WriteLine("He was not here");

And here's a Linq solution
var match = ocean.Select((x, i) => new { Value = x, Index = i })
    .FirstOrDefault(x => x.Value == "Nemo");
if(match != null)
    Console.WriteLine("We found Nemo on position {0}!", match.Index);
else
    Console.WriteLine("He was not here");

A: I am writing the probable solution in LINQ maybe and I hope it will be helpful. The error is due to the fact that indices in arrays start on zero it shows 3
   string[] ocean = { "Beebo", "Jeff","Arthur", "Nemo", "Dory" };

   ocean.Select((x, i) => new { Value = x, Index = i }).ForEach(element =>
   {
       if (element.Value == "Nemo")
       {
           Console.WriteLine("We found Nemo on position {0}!",element.Index);
       }
   });

How to use it in compiler


text:
Q: Is there an OGR is_line method? Following on from GDAL/OGR Geometry Type Python, what is the best way to determine if a vector geometry is any kind of line or point or whatever?
For example, I'm using this technique at the moment,
# check geom type is supported
vector_lyr = vector_ds.GetLayer()
ftr = vector_lyr.GetNextFeature()
geom = ftr.GetGeometryRef()
geom_type = geom.GetGeometryType()

if geom_type in (ogr.wkbLineString, ogr.wkbMultiLineString):
    do_line_stuff()
elif geom_type in (ogr.wkbPoint, ogr.wkbMultiPoint):
    do_point_stuff()
else:
    raise NotImplementedError(
        'Geometry Type {} is not supported'.format(geom.GetGeometryName()))

but it feels like it doesn't cover all geometry types. What if it's a curve, or a ring, or a geometry collection? Should I just list all the possible types in the if statements above, or is there a better way? There doesn't seem to be a catch-all is_line() method.

A: Looks like the answer is no - you have to write your own.


text:
Q: JSON and a .rss file I'm pretty new to android development and I was wondering if I could get some input on what to do in my case. I'm trying to make a list of events that are going on at my school using the calendar that's on its website. The problem is, the only way I found to get to the JSON format is through the .rss which looks like this link
I put it into myjson and got this error message and I have no idea what it means:
Parse error on line 1:

My goal is to be able to use JSON to create a list in a ListView on the app I'm making, but so far I'm completely lost as far as what to do. Any help is appreciated!

A: JSON is entirely different from RSS.
Look into this tutorial here or check out github, there's a ton of libraries that support RSS parsing such as this or this


text:
Q: Switching Between Cameras, Crash on Nexus S When switching between the rear-facing and front-facing camera, I am running into the following error on a Nexus S (Android 4.1.2):
E/CameraHardwareSec(90): ERR(virtual android::status_t android::CameraHardwareSec::setParameters(const android::CameraParameters&)): preview is running, cannot change size and format!

This is immediately followed by:
06-30 16:43:38.961: E/AndroidRuntime(10946): java.lang.RuntimeException: setParameters failed
06-30 16:43:38.961: E/AndroidRuntime(10946):    at android.hardware.Camera.native_setParameters(Native Method)
06-30 16:43:38.961: E/AndroidRuntime(10946):    at android.hardware.Camera.setParameters(Camera.java:1410)
06-30 16:43:38.961: E/AndroidRuntime(10946):    at com.commonsware.cwac.camera.CameraView.initPreview(CameraView.java:279)
06-30 16:43:38.961: E/AndroidRuntime(10946):    at com.commonsware.cwac.camera.TexturePreviewStrategy.onSurfaceTextureAvailable(TexturePreviewStrategy.java:45)
06-30 16:43:38.961: E/AndroidRuntime(10946):    at android.view.TextureView.getHardwareLayer(TextureView.java:368)
...

This is despite the fact that I call stopPreview() on my rear-facing camera preview before calling setParameters() with a new preview size (suitable for the FFC). The same code works on other devices (e.g., Galaxy Nexus, Nexus 4).
Does anyone have an idea of how to work around this problem, besides choosing a preview size available to both cameras? That solution could work, but I have no way of ensuring that there is a common preview size between the two cameras, plus it artificially limits the preview size.
Thanks!
UPDATE
Here is a longer dump from LogCat, showing my stopping of the preview, then starting it later and crashing. This one shows an artificial one-second delay added in via postDelayed(); that did not clear up the problem:
06-30 17:20:14.375: D/CameraView(12663): stopping preview
06-30 17:20:14.414: I/CameraHardwareSec(90): int android::CameraHardwareSec::previewThreadWrapper(): calling mSecCamera->stopPreview() and waiting
06-30 17:20:14.492: I/CameraHardwareSec(90): void android::CameraHardwareSec::stopPreviewInternal() : preview not running, doing nothing
06-30 17:20:14.492: I/CameraHardwareSec(90): int android::CameraHardwareSec::previewThreadWrapper(): return from wait
06-30 17:20:14.492: I/CameraHardwareSec(90): int android::CameraHardwareSec::previewThreadWrapper(): exiting
06-30 17:20:14.500: W/SecCamera(90): int android::SecCamera::stopPreview(): doing nothing because m_flag_camera_start is zero
06-30 17:20:14.507: W/SecCamera(90): int android::SecCamera::stopRecord(): doing nothing because m_flag_record_start is zero
06-30 17:20:14.507: I/SecCamera(90): DeinitCamera: m_cam_fd(39)
06-30 17:20:14.523: I/SecCamera(90): DeinitCamera: m_cam_fd2(40)
06-30 17:20:14.550: E/CameraHardwareSec(90): preview window is NULL!
06-30 17:20:14.550: I/CameraService(90): Destroying camera 0
06-30 17:20:14.550: I/CameraHardwareSec(90): int android::HAL_camera_device_close(hw_device_t*)
06-30 17:20:14.550: I/SecCamera(90): DeinitCamera : already deinitialized
06-30 17:20:14.554: W/AudioFlinger(90): session id 206 not found for pid 90
06-30 17:20:14.558: W/AudioFlinger(90): session id 207 not found for pid 90
06-30 17:20:15.480: E/DemoCameraHost(12663): facing: 0, useFFC: true
06-30 17:20:15.480: E/DemoCameraHost(12663): facing: 1, useFFC: true
06-30 17:20:15.480: I/CameraService(90): Opening camera 1
06-30 17:20:15.480: I/CameraHardwareSec(90): int android::HAL_camera_device_open(const hw_module_t*, char const*, hw_device_t**): open camera 1
06-30 17:20:15.484: E/SecCamera(90): initCamera: m_cam_fd(39), m_jpeg_fd(0)
06-30 17:20:15.484: I/SecCamera(90): Name of input channel[1] is S5KA3DFX
06-30 17:20:15.496: E/SecCamera(90): initCamera: m_cam_fd2(40)
06-30 17:20:15.496: I/SecCamera(90): Name of input channel[1] is S5KA3DFX
06-30 17:20:15.496: I/SecCamera(90): initCamera : initialized
06-30 17:20:15.496: I/SecCamera(90): Name of input channel[1] is S5KA3DFX
06-30 17:20:15.496: I/CameraHardwareSec(90): int android::HAL_camera_device_open(const hw_module_t*, char const*, hw_device_t**): opened camera 1 (0x412688a8)
06-30 17:20:15.496: I/AwesomePlayer(90): setDataSource_l('/system/media/audio/ui/camera_click.ogg')
06-30 17:20:15.504: I/CameraHardwareSec(90): int android::CameraHardwareSec::previewThreadWrapper(): starting
06-30 17:20:15.504: I/CameraHardwareSec(90): int android::CameraHardwareSec::previewThreadWrapper(): calling mSecCamera->stopPreview() and waiting
06-30 17:20:15.507: W/SecCamera(90): int android::SecCamera::stopPreview(): doing nothing because m_flag_camera_start is zero
06-30 17:20:15.515: D/dalvikvm(12663): GC_CONCURRENT freed 159K, 4% free 8249K/8519K, paused 53ms+7ms, total 98ms
06-30 17:20:15.519: I/AwesomePlayer(90): setDataSource_l('/system/media/audio/ui/VideoRecord.ogg')
06-30 17:20:15.535: I/CameraHardwareSec(90): void android::CameraHardwareSec::stopPreviewInternal() : preview not running, doing nothing
06-30 17:20:15.535: E/CameraHardwareSec(90): preview window is NULL!
06-30 17:20:15.539: I/CameraHardwareSec(90): virtual android::status_t android::CameraHardwareSec::startPreview() : deferring
06-30 17:20:15.640: D/CameraHardwareSec(90): mPreviewHeap(fd(39), size(460800), width(640), height(480))
06-30 17:20:15.640: I/CameraHardwareSec(90): int android::CameraHardwareSec::previewThreadWrapper(): return from wait
06-30 17:20:15.640: D/CameraView(12663): initPreview() called, setting up 320 x 240
06-30 17:20:15.644: E/CameraHardwareSec(90): ERR(virtual android::status_t android::CameraHardwareSec::setParameters(const android::CameraParameters&)): preview is running, cannot change size and format!
06-30 17:20:15.648: D/AndroidRuntime(12663): Shutting down VM
06-30 17:20:15.648: W/dalvikvm(12663): threadid=1: thread exiting with uncaught exception (group=0x40c33300)
06-30 17:20:15.679: E/AndroidRuntime(12663): FATAL EXCEPTION: main
06-30 17:20:15.679: E/AndroidRuntime(12663): java.lang.RuntimeException: setParameters failed
06-30 17:20:15.679: E/AndroidRuntime(12663):    at android.hardware.Camera.native_setParameters(Native Method)
06-30 17:20:15.679: E/AndroidRuntime(12663):    at android.hardware.Camera.setParameters(Camera.java:1410)
06-30 17:20:15.679: E/AndroidRuntime(12663):    at com.commonsware.cwac.camera.CameraView.initPreview(CameraView.java:280)
06-30 17:20:15.679: E/AndroidRuntime(12663):    at com.commonsware.cwac.camera.TexturePreviewStrategy.onSurfaceTextureAvailable(TexturePreviewStrategy.java:45)
06-30 17:20:15.679: E/AndroidRuntime(12663):    at android.view.TextureView.getHardwareLayer(TextureView.java:368)
...

A: I found my problem. I was turning on preview mode before I thought I was, which caused problems when I later set the preview size.
Moral of this story: when in doubt, set breakpoints on every one of your uses of Camera, and make sure the order of events is what you think it is.


text:
Q: How to add personal android projects to my CV to get into Android job market I am an experienced Java Programmer. 1 year back I started android programming and published 3 Apps into the market. But these all are my personal projects. Now I want get into the android job market. As my android experience is not corporate experience does the companies consider this? How to add these android projects to my CV to get into Android job market?
Thanks

A: Experience gained making those apps are more important.
It would be a waste of space to simply list the applications that you have worked on in the past and simply leave it at that.  It doesn't matter if these are personal applications or commercial applications.
What is important is the quality of the software that you have produced, and what you have learned in the process.
If you list these attributes first and then lastly present your applications as "proof", then it should be inconsequential if these were commercially created or paid for apps or personal projects.
IMO the most important aspects of writing any software for that matter are:

*

*Results - are you proud of your achievements of these personal apps, are they of a quality you are happy for an interviewer to evaluate your skill based on these applications.  If not then DO NOT list them.

*Methods used for Quality Assurance - Did you write JUnit Tests, perform end user testing with multiple emulators in various screen resolutions / orientations.  Does the software work without crashing, handle exceptions correctly etc.

*What you have learned creating your personal apps - What technology did you use, what have you learned that can be applied to your next commercial app.

If you can answer the above questions in your resume (very quickly in bullet form), and express that you went through the same process as you would have for a commercial app.
You will then be showing clearly that you have relevant experience.

A: *

*Come up with a company name (and make a web page for it)

*Call yourself the owner

*Add the products to your CV under that company

Because, after all, if you are writing software for the android market (especially if you are selling them), then you are your own company, and you do have 'commercial' experience.
Dont undersell your 'personal' projects just because they arent developed within a cubicle farm.  Being able to conceptualize, implement, and ultimately sell your own software is a big deal.

A: So the question do you want to target Android Market only or Android + Java?
If you are an experienced Java developer, I would say mention your experience as Java developer and then add your experience as an Android developer. Try to indicate that you are making a shift. This way you will have a professional experience as well as your own project to indicate you are trying to make switch. Three projects are good enough to get into Android Market. Even one is good enough. You just have to sell yourself. I probably would list them on the top since that is where I am focusing now.
I had a similar change of career from C++ development to web development. Initially I had listed only one of my PHP projects and my resume was a mixture of C++ and PHP. Gradually got a couple of more projects that I added and then I just totally focused it on Web Development. I still mentioned my C++ experience. I had better success with my web developer resume although the C++ market wasn't that bad at all.
Should you list your personal project?
Absolutely. As Justin answer says if you are proud of it, mention it! You must! Believe it or not I got sold by stuff that I did personally years ago when I was a student. I was proud of it so I mentioned it. One could have said, why bother mentioning such thing, and they wouldn't be that wrong.
I think it is important to highlight both your experiences Java + Android. And you are good to go.

A: Create a section at the bottom that lists what you did.  If anything is piblicly available, mention it there.  Also include all the buzzwords to get it by HR and the auto filters.

A: You can call it as your Pet-Projects and put it under your educational qualification before professional experience to highlight it in same order.


text:
Q: If $f(x)$ is positive and $f'(x)<0$, $f"(x)>0$ for all $x>0$, prove that $\frac{1}{2}f(1)+\int_1^nf(x)dx<\sum_{r=1}^nf(r)$
If $f(x)$ is positive and $f'(x)<0$, $f"(x)>0$ for all $x>0$, prove that $$\frac{1}{2}f(1)+\int_1^nf(x)dx<\sum_{r=1}^nf(r)<f(1)+\int_1^nf(x)dx$$

Since function is decreasing, then area of rectangles $$f(2)[2-1]+f(3)[3-2]+...<\int_1^nf(x)dx$$
Hence, $$\sum_{r=2}^nf(r)<\int_1^nf(x)dx$$
Adding $f(1)$ on both sides,
$$\sum_{r=1}^nf(r)<f(1)+\int_1^nf(x)dx$$
But how do I get the second inequality : $$\frac{1}{2}f(1)+\int_1^nf(x)dx<\sum_{r=1}^nf(r)$$

A: $f'' > 0$ means that $f$ is strictly convex, so the graph of $f$ restricted to each interval $[r, r+1]$ lies below the straight line connecting
$(r, f(r))$ and $(r+1, f(r+1))$:
$$
f(x) \le (r+1-x) \, f(r) + (x-r) \, f(r+1)
$$
with equality only at the endpoints of the interval.
The integral of a linear function over an interval is just
the value at the midpoint, multiplied by the length of the interval.
It follows that
$$
\int_r^{r+1}f(x)dx < \frac 12 \bigl( f(r) + f(r+1)\bigr )
$$
and therefore
$$
\int_1^nf(x)dx < \frac 12 f(1) + f(2) + \dots + f(n-1) + \frac 12 f(n)
$$
or
$$
\frac 12 f(1) + \int_1^nf(x)dx + \frac 12 f(n) < \sum_{r=1}^n f(r) \, .
$$
The conclusion now follows since $\frac 12 f(n) > 0$.


text:
Q: xcode ios App "The application could not be verified" I'm developing a app with the latest xcode. I configured xcode
to "don't sign" to install the app to my iphone without a developer account.
It was working fine, until i updated my iphone 6 to ios 8.3.
I removed the app from the phone, restarted it, did a "clean"(in Build-Menu),
but same error.
Also i havent changed the project settings in xcode.

A: There is a no solution for this with this xCode version,
because Apple restrictions.
I installed xcode 7.0 that allows installing apps without developer account to iphones/ipads, solved my problem.


text:
Q: How to identify unused libraries and peer dependencies in angular app? I've a angular application which depends on lot of angular libraries. Now the app code changed over the time and some of the libraries and their peer-dependencies are not referenced anymore.
I want to remove all non-referenced libs from package.json.
Is there a way to identify all the libs and peer-deps which are not required ?


text:
Q: Delete object from database when it has dependencies I was trying to implement the Delete Action in the MVC3, but I got to the point that the object that I want to delete has dependencies in other tables and that's why I am getting:

DELETE statement conflicted with the REFERENCE constraint

Here is my method in the controller:
[HttpPost]
public ActionResult Delete(int? id)
{
    repo.DeleteDirector(id);
    return View("index");
}

and this is how I am deleting it in my repository:
void DeleteDirector(int? id)
{
    Director d = dc.Directors.FirstOrDefault(dir => dir.Id == id);
    dc.Directors.Remove(d);
    dc.SaveChanges();
}

I was hoping that simple LINQ Remove method will do the job, but it won't.
So I am trying to think of a way to efficiently remove it with all the dependencies. I know that I can do it manually by going through all the tables where particular Director  might be referenced. But I was hoping if Framework provides own implementation for it.

A: There is one property in SQL CasCade delete which will enable dependencies to be deleted automatically when the parent record removed from the table.
By reviewing above code I am assuming you are using EF code first with repository pattern. If this is the case then you should provide Cascade delete in configuration. you can refer the below link
Entity Framework (EF) Code First Cascade Delete
I hope that will be helpful to you.


text:
Q: issue in executing commands in cmd using C# I am doing two commands in cmd from C# application.

*

*renaming a file
string commandToExecute;
commandToExecute = @"/c ren E:\filename filename.rar";
Process.Start("cmd.exe", commandToExecute);

*unrar-ing a file
commandToExecute = @"/c unrar e E:\filename.rar";
Process.Start("cmd.exe", commandToExecute);

The first part of the code works, but the second part doesn't, although it is working when I write the command in cmd manually. And I noticed that when executing in C# it runs the application itself again (like recursion). I don't know why.
Note: I am using 64-bit windows 7.

A: Remember that Process.Start launches another process. If the commands need to run serially, you need to obtain a Process object from Process.Start and call the WaitForExit method.


text:
Q: How to seamlessy color the background of a series of \items I need to change the background of a number of (full) \items in a numbered list. I saw the answers to How to highlight an entire paragraph? and (naively) tried to do the following:
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[framemethod=tikz]{mdframed}
\newcommand{\blob}{A text which is long, but not so long  as a
  \texttt{\textbackslash lipsum}  paragraph and show the
  problem about changing the background color}
\begin{document}
\begin{enumerate}
  \item \blob
  \begin{mdframed}[hidealllines=true,backgroundcolor=blue!20]
  \item \blob
  \item \blob
  \end{mdframed}
  \item \blob
  \item \begin{mdframed}[hidealllines=true,backgroundcolor=blue!20]
        \blob   \end{mdframed}
\end{enumerate}
\end{document}

Unfortunately, that does not work. The first mdframed simply stop the listng, and the second way of using it has a strange effect:

I would like to have just the background change, without changing the list spacing. The change of background will happen sometime across a page break.
I tried to use the method proposed in Box around a few items in an itemize environment, but that method has two shortcomings for my application:

*

*(minor) it can just highlight one section in the list --- if I need a couple of them it doesn't work;

*(major) does not work if the highlighted text cross a page boundary.

Next I tried to suspend and resume the list, but it gave me other problems:
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}
\usepackage{framed,xcolor}
\colorlet{shadecolor}{blue!20}
\newcommand{\blob}{A text which is long, but not so long  as a
  \texttt{\textbackslash lipsum}  paragraph and show the
  problem about starting and resuming lists multiple times}

\begin{document}
  \begin{enumerate}
    \item \blob
  \end{enumerate}
\begin{shaded}
  \begin{enumerate}[resume]
    \item \blob
    \item \blob
  \end{enumerate}
\end{shaded}
  \begin{enumerate}[resume]
    \item \blob
    \item last one
  \end{enumerate}
\end{document}

It seemed a good idea, but intermixing the shaded environment mangles the [resume] option (probably due to locality of definitions into the shaded environment):

A: There is room for improvement, but I am exhausted!
Using tcolorbox:
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[most]{tcolorbox}
\tcbuselibrary{breakable}
\newcommand{\blob}{A text which is long, but not so long  as a
  \texttt{\textbackslash lipsum}  paragraph and show the
  problem about changing the background color}
\usepackage{enumitem,lipsum}
\newcommand{\myitem}[1]{%
    \end{enumerate}
    \begin{tcolorbox}[enhanced,title=,
                    frame hidden,
                    colback=blue!20,
                    breakable,
                    left=0pt,
                    right=0pt,
                    top=0pt,
                    bottom=4pt,
                    boxsep=0mm,
                    arc=0mm,boxrule=0pt,
                    nobeforeafter,
                    ]
        \begin{enumerate}[resume*,itemsep=0pt,topsep=0pt,leftmargin=!]
            \item #1
        \end{enumerate}
    \end{tcolorbox}
    \begin{enumerate}[resume*]
}
\begin{document}
\begin{enumerate}
  \item \blob
  \item \blob
  \myitem \blob
  \item \blob
  \myitem \lipsum
  \item \blob              %% \myitem can't come at last :-(
\end{enumerate}
\end{document}

Using mdframed:
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[framemethod=tikz]{mdframed}
\newcommand{\blob}{A text which is long, but not so long  as a
  \texttt{\textbackslash lipsum}  paragraph and show the
  problem about changing the background color}
\usepackage{enumitem,lipsum}
\newcommand{\myitem}[1]{%
    \end{enumerate}
    \begin{mdframed}[hidealllines=true,
                    backgroundcolor=blue!20,
                    leftmargin=0,
                    rightmargin=0,
                    innerleftmargin=0,
                    innerrightmargin=0,
                    skipabove=-3\itemsep,
                    skipbelow=0]
        \begin{enumerate}[resume*,itemsep=0pt,topsep=0pt,]
            \item #1
        \end{enumerate}
    \end{mdframed}
    \begin{enumerate}[resume*]
}
\begin{document}
\noindent X\hrulefill X
\begin{enumerate}
  \item \blob
  \myitem \blob
  \item \blob
  \myitem \lipsum
  \item \blob
  \item \blob
\end{enumerate}
\end{document}

Caveats The code is crude and there is lot of room for improvements. Further, \myitem can not be the last item.

A: I have found a "workaround"--- I need to define a new environment. The follow snippet will highlight all the parts of the list hlenum  (admittely adding spaces --- I should mix it with the other solutions proposed here, but it's too late...) included between \starthl and \stophl. If you change the list to a enumerate normal one, the highlight will disappear.
\stophl could not be the last item in the list, but you can omit it if you want the highlight to reach the end of the list.
It is inspired by this answer adding a \global in setting the counter --- which means that it will work only for the outmost list.
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{framed,xcolor}
\colorlet{shadecolor}{blue!20}%color of the background
\newcommand{\blob}{A text which is long, but not so long  as a
  \texttt{\textbackslash lipsum}  paragraph and show the
  problem about changing the background color}
\newcounter{glistresume}
\newif\ifintoshade
\newcommand{\realstarthl}{%
        \global\setcounter{glistresume}{\theenumi}
        \end{enumerate}
        \begin{shaded}
        \intoshadetrue
        \begin{enumerate}
        \setcounter{enumi}{\theglistresume}
        }
\newcommand{\realstophl}{%
        \global\setcounter{glistresume}{\theenumi}
        \end{enumerate}
        \end{shaded}
        \intoshadefalse
        \begin{enumerate}
        \setcounter{enumi}{\theglistresume}
        }
\newcommand{\starthl}{\relax}
\newcommand{\stophl}{\relax}
\newenvironment{hlenum}{%
        \intoshadefalse
        \let\starthl\realstarthl
        \let\stophl\realstophl
        \begin{enumerate}}{%
        \end{enumerate}%
        \ifintoshade \end{shaded}\fi
        }
\begin{document}
\begin{hlenum}
  \item \blob
  \starthl
  \item \blob
  \item \blob
  \stophl
  \item \blob
  \starthl
  \item \blob
  \stophl          %% you can comment these two lines
  \item last one   %% to have an highlight till the end of the list
\end{hlenum}
\end{document}


text:
Q: How do I use Firebase Admin SDK Service Key JSON file in a remote Linux shell (Python Admin SDK)? I recently got started with Firebase, and I had a question about the private key JSON file. I can download it and securely store the file on a computer that has a GUI - and so my Firebase Admin SDK code works fine on computers with a GUI. However, I can't get the file to work on a remote Linux shell, as when I copy the certificate contents over to a .json file on the shell, it throws errors relating to the JSON formatting.
How would I use the use the Admin SDK for Python on a remote Linux server with no access to a GUI, as I can't download the private key file (as it requires a GUI to download)? Thanks in advance.
Edit: I forgot to add what's causing the problem. The code I'm trying to run is here (I'm trying to use the Admin SDK for Python):
import firebase_admin
from firebase_admin import db

firebase_admin.initialize_app({
     'databaseURL' : '<database URL here>'
})

ref = db.reference('/')
print(ref.get())

Below is the template for the service account private key generated by Firebase when clicking on the "Generate Private Key" button in the Firebase service account settings (I've removed the values for security reasons):
{
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}

I've set the GOOGLE_APPLICATION_CREDENTIALS variable to the file path of the private key file. This works with the Windows machine, but on my Linux backend, I get this error if I copy the contents of my private key to a .json file on the Linux backend:

ValueError: Illegal Firebase credential provided. App must be initialized with a valid credential instance.

How should I use the Admin SDK with a remote Linux server with no access to a GUI? Thanks.


text:
Q: New html,css,js page for each user/product I am relatively new to web development, I was just thinking whether Facebook/twitter or Amazon make a new html,css,js page for each user/product. If not, is it possible to replicate this action using the tech i am learning.
HTML, CSS, JavaScript + React, Node.js and MongoDB
Thank you for any help!!

A: The answer is: sort-of! I'll use Facebook as an example.
Facebook has roughly 2 billion users. Each user can go to their profile page. But Facebook does not have 2 billion "profile.html" pages stored on its server. There would be many problems with that:

*

*That would be a tremendous amount of data to store.

*Profile pages all have a lot in common: they have the same color/font theme, the same general layout, the same headers and footers... Storing 2 billion files that are very similar is not an efficient use of space.

*Let's say Facebook wanted to change the font on the profile page. They would need to update all 2 billion profile pages, which is not efficient.

Instead, Facebook stores one template of a profile page. Then, when User Alice goes to her profile, Facebook loads the template, loads Alice's data from a database, inserts her data into the template, and then sends Alice that filled-out template.
That way, Facebook gets these advantages:

*

*They store a much smaller amount of data

*If they want to change the font of the profile page, they only need to change the template

All of the other platforms aside from Facebook do this same thing.


text:
Q: Need help decoding part number for SOT23-5 chip I have a circuit board that has come out of a smart plug-in lamp dimmer/switch module. I would like to find the part number of a small SOT23-5 integrated circuit chip that is on this board. The SMT code appears to be FW7GE but I have been unsuccessful in a multitude of web searches and visiting manufacturer web sites to locate the actual part number that corresponds to the SMT top code.
Here is a picture of the chip zoomed in as far as I could and still maintain a decent focus. The chip seems to part of a switching power supply

Any help locating he part number would be much appreciated.


text:
Q: Why is element-wise matrix row-exchanging more efficient than array-wise row-exchanging in Fortran? I have some Fortran code that performs a matrix row exchange. In the legacy code, it is written as
do J = 1,N
   save_val  = B(IROW,J)
   B(IROW,J) = B(JCOL,J)
   B(JCOL,J) = save_val
end do

This exchanges row IROW with row JCOL (IROW and JCOL are integers). However, the function of that block of code is not intuitive. In my opinion, it would be more intuitive, or at least aid readability to write it as:
save_row  = B(IROW,:)
B(IROW,:) = B(JCOL,:)
B(JCOL,:) = save_row

(it is more clear that rows are being moved).
From the image attached, it is clear that the looping methods provide better performance relative to the array operations.
Why is this? Is it because this becomes a memory limited process when the number of elements in the array gets large? (i.e. the array would get "chunked") Or is it something else?
Compiling as gfortran -O3 test.f95. Adding the flag fstack-arrays did not make significant difference.

program test

  implicit none

  integer  :: N
  integer  :: M
  integer  :: loop_max = 1e7
  integer  :: i                    ! loop index
  real     :: t1, t2
  real     :: time_loop, time_array, time_sub_loop, time_sub_array

  real, dimension(:, :), allocatable   :: B
  real, dimension(:)   , allocatable   :: save_row

  real :: save_val
  integer :: IROW, J, JCOL

  character(*), parameter :: format_header = '(A5, 1X, 4(A12,1X))'
  character(*), parameter :: format_data = '(I5, 1X, 4(ES12.5, 1X))'

  open(1, file = 'TimingRowExchange.txt', status = 'unknown')
  write(1, format_header) 'N', 't_loop', 't_array', 't_sub_loop', 't_sub_array'

  do N = 1, 100
    M = N + 1
    allocate(B(N,N), save_row(M))
    call random_number(B)

    JCOL = 1
    IROW = 3

    call CPU_time(t1)
    do i = 1, loop_max
      do J = 1,N
        save_val  = B(IROW,J)
        B(IROW,J) = B(JCOL,J)
        B(JCOL,J) = save_val
      end do
    end do
    call CPU_time(t2)
    time_loop = t2 - t1
    ! write ( *, * ) 'Using Loop =', t2 - t1

    call CPU_time(t1)
    do i = 1, loop_max
        save_row(1:N) = B(IROW,:)
        B(IROW,:)     = B(JCOL,:)
        B(JCOL,:)     = save_row(1:N)
    end do
    call CPU_time(t2)
    time_array = t2 - t1
    ! write ( *, * ) 'Using Array =', t2 - t1

    call CPU_time(t1)
    do i = 1, loop_max
      call exchange_rows_loop(B, JCOL, IROW)
    end do
    call CPU_time(t2)
    time_sub_loop = t2 - t1
    ! write ( *, * ) 'Loop Subrout =', t2 - t1

    call CPU_time(t1)
    do i = 1, loop_max
      call exchange_rows_array(B, JCOL, IROW)
    end do
    call CPU_time(t2)
    time_sub_array = t2 - t1
    ! write ( *, * ) 'Array Subrout =', t2 - t1

    deallocate(B, save_row)
    write(1, format_data) N, time_loop, time_array, time_sub_loop, time_sub_array
  end do

contains

  subroutine print_mat(A)
    implicit none
    real, dimension(:,:), intent(in) :: A
    integer :: n

    n = size(A,1) ! # of rows

    do i = 1,n
      print*, A(i,:)
    end do
    print*,

  end subroutine print_mat

  subroutine exchange_rows_loop(A, row1, row2)
    implicit none
    real, dimension(:,:), intent(in out) :: A
    integer,              intent(in)     :: row1, row2

    integer :: J
    real :: save_val

    do J = 1, size(A,1)
      save_val  = A(row1,J)
      A(row1,J) = A(row2,J)
      A(row2,J) = save_val
    end do

  end subroutine exchange_rows_loop

  subroutine exchange_rows_array(A, row1, row2)
    implicit none
    real, dimension(:,:), intent(in out) :: A
    integer,              intent(in)     :: row1, row2

    real, dimension(size(A,1))           :: save_row

    save_row  = A(row1,:)
    A(row1,:) = A(row2,:)
    A(row2,:) = save_row

  end subroutine exchange_rows_array

end program test

A: My understanding of Fortran's philosophy (strength) is that the language should help the user focus on the science, while taking care of most computer-related stuff such as optimization-for-speed, garbage collection, etc.
Functional programming style via pure/elemental functions and subroutines is IMHO one of the greatest tools that has been introduced yet underutilized, because it makes code clear, simpler and more robust.
So I've added one more test with an elemental swapping routine:
  subroutine exchange_rows_elemental(A, row1, row2)
    implicit none
    real, dimension(:,:), intent(in out) :: A
    integer,              intent(in)     :: row1, row2
    call swap(A(row1,:),A(row2,:))
  end subroutine exchange_rows_elemental

  elemental subroutine swap(a,b)
     real, intent(inout) :: a,b
     real :: save_val
     save_val = a
     a = b
     b = save_val
  end subroutine swap

And in the main:
call CPU_time(t1)
do i = 1, loop_max
  call exchange_rows_elemental(B, JCOL, IROW)
end do
call CPU_time(t2)
time_elemental = t2 - t1
! write ( *, * ) 'Elemental =', t2 - t1

This is what I get with gfortran 9.2.0 on Windows:

The elemental version is almost as fast as the fastest loop versions, but it likely operates in a vectorized way. I'm sure in this case the compiler is probably inlining the swap routine (maybe it wouldn't be able to if it was in another file), but still, telling the compiler that the swap routine can be vectorized probably helps it achieve optimal performance. I like it as a good way to make best usage of compiler optimization without cluttering the source code with nested loops and loop variables.

A: Those two versions do not do the same, the ordering is different and the optimizations done by the compiler are different. The assembly is available at https://godbolt.org/z/hc8zcs
The loop:
    movss   xmm0, DWORD PTR [rax+12]
    movss   xmm1, DWORD PTR [rax+4]
    movss   DWORD PTR [rax+4], xmm0
    movss   DWORD PTR [rax+12], xmm1
    cmp     ebx, 1
    je      .L6
    movss   xmm0, DWORD PTR [rsi]
    movss   xmm1, DWORD PTR [rcx]
    movss   DWORD PTR [rsi], xmm1
    movss   DWORD PTR [rcx], xmm0
    cmp     ebx, 2
    je      .L6
    movss   xmm0, DWORD PTR [r8]
    movss   xmm1, DWORD PTR [rdi]
    movss   DWORD PTR [r8], xmm1
    movss   DWORD PTR [rdi], xmm0

It is somewhat unrolled, the vectorized instructions (SSE) are used.  Overall it is very straightforward.
The subarray version:
        mov     r10, QWORD PTR [rsp+216]
        mov     rsi, QWORD PTR [rsp+208]
        mov     r8d, 10000000
        mov     rdx, QWORD PTR [rsp+152]
        mov     rdi, QWORD PTR [rsp+144]
        mov     r11, r10
        lea     rbx, [r10+1]
        lea     r15, [r10+2]
        mov     r9, QWORD PTR [rsp+8]
        imul    r11, rsi
        lea     rax, [rdx+1]
        mov     rcx, QWORD PTR [rsp+224]
        imul    rbx, rsi
        lea     r12, [rdx+3]
        imul    r15, rsi
        sal     rsi, 2
        lea     rbp, [r12+r11]
        add     rdx, r11
        add     r11, rax
        lea     r14, [r12+rbx]
        lea     r13, [rdi+rdx*4]
        add     rbx, rax
        add     r12, r15
        add     r15, rax
        mov     QWORD PTR [rsp], r15
        mov     r15, QWORD PTR [rsp+80]
.L13:
        movss   xmm0, DWORD PTR [rdi+rbp*4]
        movss   DWORD PTR [r9], xmm0
        cmp     r15, 1
        je      .L10
        movss   xmm0, DWORD PTR [rdi+r14*4]
        movss   DWORD PTR [r9+4], xmm0
        cmp     r15, 2
        je      .L11
        movss   xmm0, DWORD PTR [rdi+r12*4]
        movss   DWORD PTR [r9+8], xmm0
.L11:
        cmp     r10, rcx
        jg      .L65
.L37:
        mov     rax, r13
        mov     rdx, r10
.L14:
        movss   xmm0, DWORD PTR [rax+4]
        add     rdx, 1
        movss   DWORD PTR [rax+12], xmm0
        add     rax, rsi
        cmp     rcx, rdx
        jge     .L14
        movss   xmm0, DWORD PTR [r9]
        movss   DWORD PTR [rdi+r11*4], xmm0
        cmp     r15, 1
        je      .L15
.L35:
        movss   xmm0, DWORD PTR [r9+4]
        movss   DWORD PTR [rdi+rbx*4], xmm0
        cmp     r15, 3
        jne     .L15
        movss   xmm0, DWORD PTR [r9+8]
        mov     rax, QWORD PTR [rsp]
        movss   DWORD PTR [rdi+rax*4], xmm0

There is a lot of pointer arithmetic, comparison and branching involved. I suspect that the compiler has to check for the aliasing of the subarrays or for zero array extents and it is harder perform efficient vectorization.


text:
Q: Would neutron average life expectancy be shorten by gaining (relativistic) mass? A free neutron can survive up to 887.7s +/-3 (count from the bottle) or 878.5s +/-1 (pump kinetic energy). Could the difference of 9s due to its total energy at that moment when observation is made?

A: I believe you're referring to the embarrassing problem that measurements of the neutron lifetime made with neutron beams have in recent decades given systematically longer lifetimes than measurements made with ultracold neutrons trapped in bottles:

[source]
Your idea is reasonable: since the beam neutrons are moving faster, perhaps time dilation plays a role.  But the math doesn't work out.  The modern beam measurements are made with thermal or cold neutron beams.  A thermal neutron is drawn from an an ensemble with temperature $T\approx 300\rm\,K$, and the equipartition theorem tells us that such neutrons will typically have $kT \approx \frac12 mv^2$ --- that corresponds to a speed of about $v\approx 2000\,\mathrm{m/s} \approx 10^{-5}c$.  But that gives a relativistic factor of
$$
\gamma = \frac1{\sqrt{1-{v^2}/{c^2}}}
\approx \left(
1-10^{-10}
\right)^{-1/2}
\approx
1+\frac12 10^{-10}
$$
The ratio of the lifetimes from the two types of measurements is
$$
\frac{887\rm\,s}{880\rm\,s} \approx 1.008
$$
which is different from one in the fourth significant figure, rather than the tenth significant figure.  The relativistic correction isn't large enough to explain the discrepancy.
(This argument is still sound if you're not sloppy with factors of two.)
You mention in a comment that you learned about this discrepancy from this Scientific American news story.  If you'd like more technical information you might read this feature article in the same magazine, or this academic review article which I think probably precipitated both of the Scientific American stories.

A: In the system where it has the relativistic mass (rest mass times gamma factor), which is the system in which it is not at rest but moving, the live expentancy is not shorter but longer (because of the relative time dilation it ages slower, so it lives longer by the same factor the relativistic mass is higher than the rest mass, which is again the gamma factor).
So if you observe the moving particle to have a lower life expectancy than the one at rest that must be for some other reasons than time dilation.

A: To expand on @СимонТыран's answer, the fact that muons reach Earth's surface at all was one of the early forms of evidence for special relativity. The mean life of the muon is about 2 microseconds. In that time, a muon could travel only about 600 meters, at the speed of light. Since muons are produced thousands of meters up, only a tiny fraction should be able to reach the ground. What we observe is not consistent with that, and can only happen if the mean life is a rest frame phenomenon and the high energy muons gets extended by time dilation. For more details, see Wikipedia's article and the Hyperphysics article.


text:
Q: How do I install a new BIOS driver on Ubuntu 9.10 Karmic Koala I just got off the phone with an ACER support technician and he says I should make sure I have the latest BIOS driver (the installation of which could solve my overheating problems...) He helped me find the driver and I have it downloaded as a .zip file.
My question is, how do I install it? And another question would be: How do I make sure it will work with Ubuntu 9.10 and not cause any troubles? The technician I spoke says that taking about anything other than Windows is out of his scope..
edit: Full computer name: Acer Aspire 5536-5519 Model number: MS2265

A: You can not install them under Linux. There IS a utility which lets you do it with a given type of BIOS, but I wouldn't trust it. The best way is to download a bootable disc ISO (usually you can get this from the ACER website). Burn it, boot it, that's it.
If you tell us/me the entire model number, name of your laptop, we/I can check if there is an ISO avaliable or not.

A: Using a WinPE cd will often work if you have the installer on USB or something. Boot in to BartPE, VistaPE, or a Windows Vista or 7 install dvd and access the CLI using Shift+F10 and run the update. This doesn't always work but it works most of the time.

A: How about a DOS live CD? Once I used FreeDOS in a situation similar to this. I booted the live CD and after that I used a CD on which I burned DOS version of BIOS utilities. This was on Acer Aspire 7720.
You should burn the contents of the zip file and in DOS run JV50.bat It should flash the BIOS.
EDIT Here are step by step instructions how to flash BIOS. I'll add CD-RW erasing and burning instructions later today when I have ubuntu 9.10 available.
FIRST READ THESE INSTRUCTIONS COMPLETELY SEVERAL TIMES BEFORE STARTING THE PROCEDURE!
Sorry for screaming, but otherwise bad stuff can happen.
This was made in a virtual machine, so don't pay attention to any strange menus on the top of the screen!
First download the big "fdfullcd.iso". Here's a link.
Next burn it to a CD. After that download the BIOS files. The ones used in example I got from here. Just use menus on the site to select your laptop and download BIOS version 1.11.
Unzip the file somewhere. Open the BIOS_ACER_1.11_Windows_AS5236  AS5536  AS5536G directory and copy its contents to another CD.
After that boot FreeDOS as instructed in images.

Press 1 then enter.
Select five and press enter.

Wait until you get A:> prompt. Then type X: after that eject the live CD and insert the BIOS cd.

X is the letter of your CD-ROM drive. So now that you have BIOS CD in, type DIR. It will display contents of CD. I accidentally made wrong ISO so I have one directory layer more than you will.
When typing commands, remember that Tab button can be used to automatically complete long file or directory names.
If there are several options, it will complete up to a point where the difference in names appears. After that press one letter to select one of the options and press Tab again. Repeat until you get whole file name.

Now this part is kind of important. Some filenames are incorrect, so flash utility will not automatically detect you BIOS image. Instead, you'll have to insert name by hand.
Type ph and press Tab then space then jv and pressTab then Shift + - and press Tab then w and press Tab. The last command in the picture is what you should get. After that press enter. It should flash your BIOS.

This is how the running program looks:

I know this may be boring, but here are some warnings: Make sure your battery is full before you start BIOS flash. Make sure that power supply is connected to your computer while you are flashing BIOS.
If computer loses power while phlash16 is running, you'll have problems restoring BIOS!
Fortunately, it's a bit safer with laptops because of the battery!
At the end your computer may shutdown or restart. That's normal. After that it may happen that any custom settings in BIOS are lost, so before flashing, make sure you write them down.