text:
Q: Do exec() calls fork for each command if passed a shell script? For each command in a shell script passed to exec(), is it forked and ran in a child process?
Say I have a shell script called test.sh with the following contents;
#!/bin/bash

echo Hello
echo There

What I want to know is how the series of commands is treated if I were to call execvp() on test.sh in a C program.
For each command within the script, is there a fork followed by another exec call on that command, before a return to the parent and a repeat for the next command?
So far I have used strace on this exact example. My findings are that if I put two echos into the script, there are no calls to clone() (which I believe equates to forking?), but if I put two separate cats as such:
#!/bin/bash

cat file1
cat file2

Then I find two calls to clone in the strace. At the same time, stracing a singular cat call on its own, without running it from an execvp call on a shell script, does not yield any clones in the strace.
I would really appreciate a clarification on the way which exec calls handle shell scripts.

A: The bash shell has a number of built-in commands that are executed in the same process as the shell.  The echo command is one of those built in commands.
cat on the other hand is at external program, so the shell must fork and exec to create a process and run the program.

A: Some commands are built into the shell, so they don't need to fork. All the commands that implement control flow (e.g. if, while, case) have to be built in. So do the commands that change the shell process's state, such as cd and ulimit.
In addition, a number of simple commands are implemented as shell built-ins; these include echo and printf. So you won't see any forks in the first script with two echo commands.
The type command (itself a built-in) can be used to show which commands are built-ins. For example, type echo reports echo is a shell builtin, but type cat reports cat is /bin/cat.
Finally, the exit status of a script is the same as the exit status of the last command. So as an optimization, it doesn't fork for the last command, it simply execs it. That's why you see forks when the script has two cat commands, but not when there's only one.


text:
Q: Execute different kernel for different parts of input array Let's say I have a simple kernel that applies two different mathematical operations to each element of the input array. The operation to apply is selected based on the modulo with the element's position in the array:
__global__ void kernel(float* A, int N)
{
    int i = threadIdx.x;

    if (i < N) {
        float x = A[i];

        if (i % 2 == 0)       x = cosf(sqrtf(x));
        else if (i % 2 == 1)  x = sqrtf(logf(x));

        A[i] = x;
    }
}

int main()
{
    // some code...

    // Kernel invocation with N threads
    kernel<<<1, N>>>(A, N);

    // ...some more code
}

To improve execution time, is there perhaps a way to by-pass the element-wise modulo computation by instead launching two kernels, one that processes even indices with x = cosf(sqrtf(x)) and one that processes odd indices with x = sqrtf(logf(x))?

A:
is there perhaps a way to by-pass the element-wise modulo computation by instead launching two kernels, one that processes even indices with x = cosf(sqrtf(x)) and one that processes odd indices with x = sqrtf(logf(x))?

Yes.

To improve execution time,

I doubt that it would.
If you want an alternating (even/odd index) selection, a very low-cost operation is just:
if (index & 1)
   //perform odd function
else
   //perform even function

I think it is very unlikely that if you used that kind of low-cost selection, that breaking the operation into two kernels would help.
However if you wanted to do so, it would be fairly simple:
__global__ void even_kernel(float* A, int N)
{
    int i = threadIdx.x*2;

    if (i < N) {
        float x = A[i];
        x = cosf(sqrtf(x));
        A[i] = x;
    }
}

__global__ void odd_kernel(float* A, int N)
{
    int i = threadIdx.x*2+1;

    if (i < N) {
        float x = A[i];
        x = sqrtf(logf(x));
        A[i] = x;
    }
}

Based on the code you have provided, you could invoke these like so:
int main()
{
    // some code...
    cudaStream_t s1, s2;
    cudaStreamCreate(&s1);
    cudaStreamCreate(&s2);
    // Kernel invocation with N threads
    odd_kernel<<<1, N/2, 0, s1>>>(A, N);
    even_kernel<<<1, N/2, 0, s2>>>(A, N);

    // ...some more code
}

The stream handling isn't really necessary, but for such tiny  grids (one block each, N is at most 1024), there might be some small improvement in performance by running them "concurrently".
As suggested in the comments, we can probably address two of the performance criticisms that might be levelled against your original code by having each thread process two elements. If we use a vectorized load for this, then we can:

*

*provide for coalesced loads/stores

*avoid conditional behavior amongst threads

That kernel could look something like this:
__global__ void kernel(float* A, int N)
{
    int i = threadIdx.x;
    float2* A2 = reinterpret_cast<float2 *>(A);

    if (i < N/2) {
        float2 x = A2[i];

        x.x = cosf(sqrtf(x.x));
        x.y = sqrtf(logf(x.y));

        A2[i] = x;
    }
}

int main()
{
    // some code...

    // Kernel invocation with N threads
    kernel<<<1, N/2>>>(A, N);

    // ...some more code
}

This has a few assumptions implicit:

*

*The A pointer is properly aligned for float2 access.  This would be satisfied, for example, if A is returned (directly) by cudaMalloc.

*The total number of elements to process (N) is an even number (and 2048 or less, in this simplistic case.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redhat: Enabling proxy for specific IP addresses only I have a server that ordinarily does not require a proxy to connect (e.g.) to any URL on the internet. However some specific systems (IP addresses) I need to connect to via a specific proxy.
My question is how I can specify the proxy per IP-Address / subnet without disrupting the normal configuration where no proxy is required.
I am aware of the following variables that can be set, however this operates on an exclusion basis to access the proxy rather than an inclusion basis:
export http_proxy=http://my-proxy.tld:8080
export https_proxy=https://my-proxy.tld:8080
export no_proxy=127.0.0.1,localhost,192.168.1.123, ...

The server in question is a RedHat V7.1 box.
Any ideas will be much appreciated.
Thanks in advance
Alex

A: You can use Squid. If you want a smaller footprint installation and smaller configuration files, you could also try Tinyproxy.


text:
Q: Is there a name for the number system that's like $\mathbb{Q}$ but without the cancellation law $ax/bx = a/b$? Suppose we want to find $42/12$ as a quotient followed by a remainder. One approach is to write $42/12$ as a mixed number via the usual method:
$$\frac{42}{12} = \frac{36+6}{12} = \frac{36}{12}+\frac{6}{12} = 3 + \frac{6}{12}$$
So the answer is $3$ with remainder $6$. However, there's something a bit dissatisfying about this. Note that to write the RHS as a normal-form mixed number, we should simplify our fraction, obtaining $$3+ \frac{1}{2}.$$ Arguably this is slightly disconcerting: to get the correct final answer of remainder $6$ and avoid the incorrect final answer of remainder $1$, we have to avoid simplifying. That's perhaps a bit strange. More fundamentally, my issue here is that we can't actually extract the remainder from the rational number we started with. In particular, if someone tells you that $x \in \mathbb{Q}$ is the rational number $42/12$ and asks you to find the remainder, there's no sensible answer to their question - the remainder could be $1$, or any non-zero multiple of $1$.
For this reason, I'm interested in the number system that's like $\mathbb{Q},$ but without the cancellation law $ax/bx = a/b$. Lets call it $\tilde{\mathbb{Q}}$. The idea behind $\tilde{\mathbb{Q}}$ is that it's a quotient of the set of all formal $\mathbb{Z}$-linear combinations of elements of the form $$\frac{1}{1}, \frac{1}{2}, \frac{1}{3}, \frac{1}{4}, \ldots$$ So an example element would be $$\frac{5}{3} + \frac{17}{5},$$ by which we really mean the linear combination $$5\frac{1}{3} + 17\frac{1}{5}.$$ I'm pretty sure the above set can be identified with the Dirichlet series with finitely many terms. We then take a quotient of this ring by assuming that if $a$ and $b$ are integers satisfying $a \mid b$, then letting $c$ denote the integer $b/a$, we have $\frac{b}{a} = c\frac{1}{1}.$ I'm not sure how to translate this into Dirichlet language. Anyhoo, in the resulting set $\tilde{\mathbb{Q}}$ we've just constructed, which should be a commutative ring if I'm not mistaken, we have $$\frac{42}{12} = 3 + \frac{6}{12} \neq 3 + \frac{1}{2},$$ and so we can extract the remainder of $6$ from the quotient $42/12$, as desired.
I'd be curious to learn more, so:

Question. Does this number system have a name and/or where can I learn more about it?


text:
Q: Only one child element may have a given value I'm trying to accomplish the following, here is my XML document :
<TEST>
  X
  X
  <C>Y</C>
</TEST>

All the three element A, B and C must exist and only one of them must have Y value, the others must have X then.
I used the following code but apparently it's not working :
<xsd:complexType name="TEST">
    <xsd:choice>
        <xsd:sequence>
            <xsd:element name="A" type="xsd:string" fixed="Y"/>
            <xsd:element name="B" type="xsd:string" fixed="X"/>
            <xsd:element name="C" type="xsd:string" fixed="X"/>
        </xsd:sequence>
        <xsd:sequence>
            <xsd:element name="A" type="xsd:string" fixed="X"/>
            <xsd:element name="B" type="xsd:string" fixed="Y"/>
            <xsd:element name="C" type="xsd:string" fixed="X"/>
        </xsd:sequence>
        <xsd:sequence>
            <xsd:element name="A" type="xsd:string" fixed="X"/>
            <xsd:element name="B" type="xsd:string" fixed="X"/>
            <xsd:element name="C" type="xsd:string" fixed="Y"/>
        </xsd:sequence>
    </xsd:choice>
</xsd:complexType>

I've been stuck with this for a while, tried almost everything from asserts, alternatives to restrictions but nothing worked so desperately I tried the choice statement.
Hopefully someone gets what I'm trying to do and explain how to accomplish it.

A: You cannot represent such a constraint within XSD 1.0.  Your attempt using xs:choice violates Unique Particle Attribution.  If you're limited to XSD 1.0, you'll have to enforce that constraint outside of XSD.
XSD 1.1 Solution
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified"
  elementFormDefault="qualified"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  vc:minVersion="1.1">

  <xs:element name="TEST">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="A" type="yorn"/>
        <xs:element name="B" type="yorn"/>
        <xs:element name="C" type="yorn"/>
      </xs:sequence>
      <xs:assert test="count(* = 'Y') = 1"/>
    </xs:complexType>
  </xs:element>

  <xs:simpleType name="yorn">
    <xs:restriction base="xs:token">
      <xs:enumeration value="Y"/>
      <xs:enumeration value="N"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>


text:
Q: php mysqli looping too many results I'm having a little issue with looping through my database retrieving results, I understand why I am getting the issue but not too sure on how to implement the solution  as my PHP is not the greatest.
I have looked through the forums but couldn't find anything to address my problem.
From below my output would give me 12 results when only I want 6 results 2 items each: for each loop is counting 12 items in array which makes sense so it will out put 12 times giving me duplicates of each. how am I best to handle this issue.
    MyTable1:                          myTable2:
    |   ID   |  Name  |           | NameID   |       Details     |
    |--------|--------|           |----------|-------------------|
    |   0    | bob    |           |   0      | lives in the city |
    |   1    | david  |           |   1      | lives in a caravan|
    -------------------           --------------------------------

My MSQLI query:
     $qryRandom   =  "SELECT  MyTable1.ID,  MyTable2.Details
                      FROM  MyTable1
                      INNER JOIN  MyTable2
                      ON MyTable1.ID=MyTable2.NameID
                      ORDER BY RAND()
                      LIMIT 6;";

My PHP( generall example).
    $resultR= $con->query($qryRandom) or die($mysqli->error.__LINE__);
    while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
    {
    foreach ( $row as $key=>$value ){ // loops 12 times here as there is 6 items x 2 values
    echo $key.": ".$value."
";

    }

 }

result outputs:
    bob lives in city
    bob lives in city
    David lives in caravan
    David lives in caravan
    john lives in the car
    john lives in the car  // doubles of each entry is my issue
   // hope I was thorough and provided enough info for my scenario.

A: The solution I came up with works how ever I am still not happy with it;
   while($row = mysqli_fetch_array($resultR, MYSQL_ASSOC))
   {
    for ($i = 0; $i<1;$i++){
    echo $row['name'].$row['details']."
";
    }
    }

Im more then sure there is a better approach to this issue.


text:
Q: ARGV in perl not working Below is the snippet that works,
open(C, "Inputfile.txt")  || die "Cannot open the file\n";
use List::MoreUtils qw(uniq);
use Math::Round
while(<C>)

I wish to pass the file name in command line. I tried to use ARGV but it is not working. I modified it to:
use List::MoreUtils qw(uniq);
my $filename = $ARGV[1];
while($filename)

When I execute it with
perl file.pl inputfile.txt

I do not get any output. Can anyone say, why it is not working ?
Thanks,
AP

A: Issues

*

*In your test case $ARGV[1] is not defined since Perl arrays are zero-indexed

*You need to open a filehandle to $filename

*You need to do readline on the filehandle, e.g. while ( <$fh> ) { ... }
That said, just use the diamond operator <> or <ARGV>:
while (<>) {
    ...
}

A: It should be $ARGV[0], not [1].  Per Perl Maven, @ARGV does not include the program name — that's separate variable $0.


text:
Q: Google Maps API v3: Labelling a circle I'm using the following code to generate a circle on a map using the Google Maps v3 API:
var postcode_a = new google.maps.Circle({
 center: postcode_a_location,
 map: map,
 radius: 70,
 fillColor: "#3da5e1",
 fillOpacity: 0.5,
 strokeColor: "#2b546b",
 strokeWeight: 1
});

What I would like to do is place a text label in the centre of my circle.
I have poured over the documentation and can see no easy way to do this. The only solution I can propose to myself is to overlay a marker on top of the circle and set the icon to a transparent PNG containing the text label I want to display.  However, this is a pretty inelegant solution since I cannot accurately offset the position of the icon so that it displays in the centre of the circle at any zoom level (and for the other obvious reasons).
Can anyone suggest a solution to this? I am not above manipulating the API with a third party library.  I have seen some written for v2 of the API, but most of these seem to be geared toward adding a label or tooltip to a marker rather than a circle, in any case.

A: How about you put an image overlay as it is described in the overlays section of the javascript sports documentation?
Also take a look at this


text:
Q: foreach loop syntax error C# Visual Studio 2013 ultimate Okay so yes I am doing homework and I am SO close on this one I know it, but ive been messing with it for over an hour and now I'm going insane, if i take the loop out my program will read the file and say weather you passed but it wont write the wrong answers in the listbox, if i put in my foreach code it gives me a syntax error.
this is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace DriversLicenseExam
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] answerArray ={"B","D","A","A","C",
                                  "A", "B","A","C","D",
                                  "B", "C","D","A","D",
                                  "C", "C","B","D","A"};
            string[] studentansArray = new string[20];

            List<string> incorrectList = new List<string>();

            int count = 0, index = 0, qnumber = 0;
            try
            {
                string filename = "../../" + filenametxt.Text;
                StreamReader inputFile = File.OpenText(filename);
                while(!inputFile.EndOfStream)
                {
                    studentansArray[index] = inputFile.ReadLine();
                    if (studentansArray[index] == answerArray[index])
                        count++;
                    else
                    {
                        qnumber = index + 1;
                            incorrectList.Add(qnumber.ToString());
                    }
                    index++;
                }
                inputFile.Close();
                if (count >= 15)
                {
                    resultoutput.Text = "You Passed The Test!";
                }
                else
                    resultoutput.Text = "You Failed The Test... You're a Failure!";
            }
            foreach (string str in incorrectList)  // <<-- error is here
            {
                lbox.Items.Add(str);
            }                                      // <<-- error is here
            catch (Exception)
            {
                MessageBox.Show("File Not Found");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            filenametxt.Text = "";
            resultoutput.Text = "";
            lbox.Items.Clear();
        }

        private void exitbutton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

A: I'm not 100% sure about this, but your foreach is between your try and catch block, maybe try with that:
try
{
    string filename = "../../" + filenametxt.Text;
    StreamReader inputFile = File.OpenText(filename);
    while(!inputFile.EndOfStream)
    {
        studentansArray[index] = inputFile.ReadLine();
        if (studentansArray[index] == answerArray[index])
            count++;
        else
        {
            qnumber = index + 1;
            incorrectList.Add(qnumber.ToString());
        }
        index++;
    }
    inputFile.Close();
    if (count >= 15)
    {
        resultoutput.Text = "You Passed The Test!";
    }
    else
        resultoutput.Text = "You Failed The Test... You're a Failure!";
    foreach (string str in incorrectList)
    {
        lbox.Items.Add(str);
    }
}
catch (Exception)
{
    MessageBox.Show("File Not Found");
}


text:
Q: css style text with no tag inside class I am on a wordpress website of a client where I have to remove text they added by mistake under their logo . They use Outreach Pro wordpress theme and I cannot find in the theme where to remove the text in the header so I am going with custom css .
The format however with the text for the element is

TEXT I WANT
TEXT TO REMOVE

where TEXT TO REMOVE is outside of the h1 tag , so how can I make its display none without including the h1 tag ?
Thank you in advance

A: Set the font-size to zero, and re-set if for the children:

.title-area { font-size: 0; }

.title-area h1 { font-size: 32px; }

TEXT I WANT
TEXT TO REMOVE

A: Like an option, you can make your container flex with row layout and move text content you want to remove to the right; And text outside block will be cropped.
Also you can move text to hide war away from view port by text-indent: 1000%;, see Code Snippet with comments:

.title-area {
  display: flex;
  flex-wrap: nowrap;
  overflow: hidden;
  white-space: nowrap; /* make text in one line */
  text-indent: 1000%; /* move text to remove far away */
}

.title-area .site-title {
  flex-grow: 1;
  flex-shrink: 0;
  width: 100%;
  text-indent: 0; /* move site title to the beginning */
}

TEXT I WANT
TEXT TO REMOVE

A: Rules get overridden in css

.title-area
{
    visibility:hidden;
}
.site-title
{
    visibility:visible;
};

TEXT I WANT
TEXT TO REMOVE

A: You can do it by using js or css. I will show only the js solution for it.
JS Version

const el = document.querySelector(".title-area > *");
document.querySelector(".title-area").innerHTML = el.outerHTML;

TEXT I WANT

  TEXT TO REMOVE


text:
Q: Validate a form using a provider ReactJS I'm making an auth system, and I have an issue on validate the input...
I have a provider that have login,register and sigout functions that talk to firebase..
Here the login function inside the provider.js
    login(email,password){
        try{
            app.auth().signInWithEmailAndPassword(email,password) //effettuo il login, se va tutto bene... then =>
            .then(() =>{
                var user = app.auth().currentUser; //prendo l'utente corrente
                user.getIdToken().then((idToken) => { //prendo l'id_token dell'utente corrente
                    this.setState({ //aggiorno lo stato
                        isAuth : true,
                        currentUser: user,
                        currentUserToken: idToken,
                        userPassword: password
                    })
                    console.log("Login: id_token corrente: ",this.state.currentUserToken)
                    localStorage.setItem('password', password)
                })

                localStorage.setItem('userLogged', JSON.stringify(user)) //aggiorno il localstorage con l'utente corrente
            })
            .catch(error => {
                if(error.code === 'auth/wrong-password' || error.code === 'auth/invalid-email') {
                    console.error("Errore nell'authenticazione: ", error.code)

                 }
            })

        }catch(e){
            alert(e)
        }
}

Then I have a component called LoginModal, that access to login function using CONTEXT API
<AuthConsumer>
{({login}) => (
    <Modal open={this.state.open} toggle={this.toggle}>
    <ModalHeader>Accedi</ModalHeader>
    <ModalBody>
    <Form>
        <FormGroup>
            Email
            <FormInput placeholder = "mariorossi@splitlabs.it" id="email" value = {this.state.LogEmail} onChange = {(e) => this.setState({logEmail: e.target.value})}/>
        </FormGroup>
        <FormGroup>
            Password
            <FormInput placeholder = "******" type = "password" id="password" value = {this.state.LogPassword} onChange = {(e) => this.setState({logPassword: e.target.value})}/>
        </FormGroup>
    </Form>
    <Button onClick ={() => {
        login(this.state.logEmail, this.state.logPassword)

    }} outline>Accedi</Button>
    </ModalBody>
 )}
</AuthConsumer>

My question is, How do I get the error occurred in the login provider and display the error on the login modal???

A: You'll want to set the error that you get from Firebase into the state, and then use that in your rendering.
So
try{
    app.auth().signInWithEmailAndPassword(email,password)
    ...
    .catch(error => {
        if(error.code === 'auth/wrong-password' || error.code === 'auth/invalid-email') {
            console.error("Errore nell'authenticazione: ", error.code)
        }
        this.setState({ signinError: error });
    })

And then:
<AuthConsumer>
{({login}) => (
    <Modal open={this.state.open} toggle={this.toggle}>
    <ModalHeader>Accedi</ModalHeader>
    <ModalBody>
    (this.state.signinError ?
{this.state.signinError}</div? : "")
    <Form>
        <FormGroup>

There might be some syntax errors in that last snippet, but I hope you get the idea.


text:
Q: Merge cloud yaml AWS cloud formation template I have multiple files that contains my cloud formation template.yaml file. For example
base.yaml
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Conditions:
  conFunctionInVPC: !And
    - !Not [!Equals [!Join ["", !Ref parFunctionSubnets], ""]]
    - !Not [!Equals [!Join ["", !Ref parFunctionSecurityGroups], ""]]
  conFunctionNotInVPC: !Not [!Condition conFunctionInVPC]
  conAwsXRaySdkLayer: !Not [!Equals [!Ref parAwsXRaySdkLayerArn, ""]]

application.yaml
Description: >
  test
  A short description of the function purpose

I want to produce the final yaml file. I tried a simple merging function
with open('base.yaml') as f:
    base = yaml.load(f)
with open('application.yaml') as f:
    application = yaml.load(fp)
template = merge(base, template) # my own function not important here
yaml.dump(template, open('template.yaml', 'w'))

However I get the error:

yaml.constructor.ConstructorError: could not determine a constructor for the tag '!And'

How can I tell yaml to just keep the node as simple it is? And be able to output it again when dumping it?
I tried with
yaml.add_multi_constructor('!', lambda loader, suffix, node: node)

but then when I dump the file, I get the SequenceNode object in my yaml for each !ref
for example:
conFunctionInVPC: !!python/object:yaml.nodes.SequenceNode
    end_mark: !!python/object:yaml.error.Mark
      buffer: null
      column: 2
      index: 721
      line: 24
      name: template/template.yaml
      pointer: null
    flow_style: false
    start_mark: !!python/object:yaml.error.Mark
      buffer: null
      column: 20
      index: 581
      line: 21
      name: template/template.yaml
      pointer: null
    tag: '!And'
    value:

A: Looking at YAML Error: could not determine a constructor for the tag
it seems it works using the RoundTrip and ruamel
template = load(f, Loader=RoundTripLoader)
yaml.dump(template, f, Dumper=RoundTripDumper)


text:
Q: Multiple Service definition in cloud formation template (YAML) I have an ECS Cluster by the name cluster-01 and under that cluster I have one service running which basically have few tasks associated to integrate microservices.
I want to add another service but want to use the same yaml template i.e single file for multiple service definition with assocated task definition defined with them.
I am pretty new to YAML and I created a single cluster with one service using AWS template available in their website.
If someone can help out to understand if it's possible to incorporate another service for same cluster by using single yaml template.
Thanks in advance.

A: You can have multiple AWS::ECS::Service resources defined in one template file:
ecsService1:
  Type: AWS::ECS::Service
  Properties:
    (...)

ecsService2:
  Type: AWS::ECS::Service
  Properties:
    (...)


text:
Q: All string are "???" while retrieving tables from Oracle of object type When I try to retrieve an object type from Oracle procedure I recieve correct numbers however all strings that this procedure passes to me are "???".
My example:
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;
import java.sql.Struct;
import java.sql.Types;

public class InitMethod {

    public static void init() throws Exception {
        Class.forName("oracle.jdbc.OracleDriver");
        Connection connection =
                DriverManager.getConnection("jdbc:oracle:thin:@10.0.0.20:1521:dw", "user", "password");

        final String typeName = "T_DEMO_OBJECT";
        final String typeTableName = "T_DEMO_OBJECTS";

        final StructDescriptor structDescriptor = StructDescriptor.createDescriptor(typeName.toUpperCase(), connection);
        final ResultSetMetaData metaData = structDescriptor.getMetaData();

        CallableStatement cs = connection.prepareCall("{call p_generate_demo_objects(?, ?)}");
        cs.setInt(1, 7);

        cs.registerOutParameter(2, Types.ARRAY, typeTableName);
        cs.execute();

        Object[] data = (Object[]) ((Array) cs.getObject(2)).getArray();
        for (Object tmp : data) {
            Struct row = (Struct) tmp;

            int idx = 1;
            for (Object attribute : row
                    .getAttributes()) {
                System.out.println(metaData.getColumnName(idx) + " = " + attribute);
                ++idx;
            }
            System.out.println("---");
        }
        cs.close();
}

I receive correct numbers however all strings are "???":

SOME_NUMBER = 1 SOME_STRING = ???
SOME_NUMBER = 2 SOME_STRING = ???

What might be an issue?
(I use ojdbc6.jar)

A: This happens when you don't include orai18n.jar in your classpath and when the database character set is not in this list: ASCII, UTF8 or ISOLATIN1. All the characters are replaced with the "replacement character" which is '?'. You can download orai18n.jar from OTN (search for "oracle jdbc download" in google).

A: In my company, we have columns of PII data in certain Oracle database schema that are redacted and replaced by a custom string. It seems likely that the '???' sequence to be a data redaction in the table. You might check with your DB Admin to see if this is the case.


text:
Q: PHP Function Name to File
Possible Duplicate:
How to find out where a function is defined?

I've searched google for a while and I can't figure it out.
I have a known function or class, lets say function/class f_x. This function is defined either in a seperate unkown .php -file.
Is there any way to retrieve the file name of that file? Like you would normally get with FILE? I can't edit those files as I'm writing a plugin for a php system.
I need this to implement a plugin for wordpress which does:
 - Enumerate all shortcode function
 - Detect if shortcode is present on page
 - if not, remove all hooks and filters related to the plugin using the shortcode.

A: Besides the fact, that I don't know, how someone can lose his classes, or functions:
$refFunction = new \ReflectionFunction('myFunction');
echo $refFunction->getFilename();

or
$refClass = new \ReflectionClass('ClassName');
echo $refClass->getFilename();

You can even ask, where it is defined in the file
echo $ref->getStartLine() . ':' . $ref->getEndLine();


text:
Q: mechanical relay output voltage doesn't change As a followup to my previous question, where a 2222 npn transistor wasn't beefy enough to handle the load I was putting on it to activate a solenoid valve, I decided to try a mechanical relay board kit instead (which I realize is overkill for what I need, but it wasn't too expensive, and I figure I can reuse it eventually).
Like my previous question, I'm driving the logic with an arduino. I see the LED on the relay toggle, and I can hear the relay click when it's turned on or off. However, the output voltage (NO to COM on the 'relay 2' outputs) doesn't change when I test it with a multimeter. The voltage between any pair of output pins stays zero (NC to COM as well, all the outputs on relay 1 as well).
Is it likely that I make a mistake when I soldered the board kit together? I could try to re-do the soldering, but visually it looks OK to me (although I'm new to this), and things are functioning enough that I can hear the relay click when it's toggled.
Could I have fried both of the relays? It's a 'Omron Relay G2RL-14-DC12, SPDT, 12A, 12VDC'. Is there a way I can diagnose what's wrong with the board? I've prodded various through-hole pins on the underside of the board, and I can see a voltage across the LED's pins, but not the output pins. Is there something else I should test? Since I can hear them click, I assumed they're working, but maybe something else on the board is busted.
The output voltage should be the same as the input voltage, right? The multimeter says the voltage across the input pins is 11.7 when the relay is on (open), 11.9 when the relay is off (closed), 12.01 when the arduino is off too (why would it be different? I thought it was an isolated circuit).
Thanks for fielding my newb question :)

A: The relay contacts are not connected to the board 12 volt power supply - they are just isolated switch contacts.
If you measure the resistance between the COM (common) and NC (normally closed) terminals, you should see near zero ohms when the relay is released, and an open circuit (inifinite resistance) when the relay is operated.
Measuringing resisttance between COM and NO will give the opposite result - near zero ohms when the relay is operated.


text:
Q: Powershell - Double dropdown menu selection I'm using a dropdown menu for one of my script and I call it twice to get two differents value on two different windows. I want to optimize my script and create one windows with two dropdown box in the same windows.
Look at my script:
    $DropDownArray = "Value1" , "Value2" , "Value3"

    # Form building

    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing

    $Form = New-Object System.Windows.Forms.Form
    $Form.width = 300
    $Form.height = 200
    $Form.Text = "User move Original Location Box"
    $Form.StartPosition = "CenterScreen"

    $DropDown = new-object System.Windows.Forms.ComboBox
    $DropDown.Location = new-object System.Drawing.Size(100,10)
    $DropDown.Size = new-object System.Drawing.Size(130,30)

    ForEach ($Item in $DropDownArray) {
    $DropDown.Items.Add($Item) | Out-Null
    }

    $Form.Controls.Add($DropDown)

    $DropDownLabel = new-object System.Windows.Forms.Label
    $DropDownLabel.Location = new-object System.Drawing.Size(10,10)
    $DropDownLabel.size = new-object System.Drawing.Size(100,200)
    $DropDownLabel.Text = "Select the user Original location ?"
    $Form.Controls.Add($DropDownLabel)

    $OKButton = new-object System.Windows.Forms.Button
    $OKButton.Location = new-object System.Drawing.Size(100,50)
    $OKButton.Size = new-object System.Drawing.Size(100,20)
    $OKButton.Text = "OK"
    $OKButton.Add_Click({
    $Form.DialogResult = "OK"
    $Form.close()
    })
    $form.Controls.Add($OKButton)

    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Size(100,75)
    $CancelButton.Size = New-Object System.Drawing.Size(100,20)
    $CancelButton.Text = "Cancel"
    $CancelButton.Add_Click({
    $Form.DialogResult = "Cancel"
    $Form.close()
    })
    $Form.Controls.Add($CancelButton)

    $Form.Add_Shown({$Form.Activate()})

    $result = $Form.ShowDialog()

    if($result -eq "OK")
    {
    $SrcServer = $DropDown.SelectedItem.ToString()
    }
    else
    {
    $SrcServer = $null
    }
foreach( $Site in $SiteAttribute.location.Site){
   $var1 = $Site.city
    If ($var1 -match $SrcServer){
            $SOURCE = $site.server
            $OldSiteGroup = $site.OldSiteGroup
            $OldDFSGroup = $site.OldDFSGroup
            $NewDFSRemote = $site.NewDFSRemote
       }

}

$source

# Form building

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$Form = New-Object System.Windows.Forms.Form
$Form.width = 300
$Form.height = 200
$Form.Text = "User move Destination Location"
$Form.StartPosition = "CenterScreen"

$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(100,10)
$DropDown.Size = new-object System.Drawing.Size(130,30)

ForEach ($Item in $DropDownArray) {
$DropDown.Items.Add($Item) | Out-Null
}

$Form.Controls.Add($DropDown)

$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(10,10)
$DropDownLabel.size = new-object System.Drawing.Size(100,200)
$DropDownLabel.Text = "Select the user Destination location ?"
$Form.Controls.Add($DropDownLabel)

$OKButton = new-object System.Windows.Forms.Button
$OKButton.Location = new-object System.Drawing.Size(100,50)
$OKButton.Size = new-object System.Drawing.Size(100,20)
$OKButton.Text = "OK"
$OKButton.Add_Click({
$Form.DialogResult = "OK"
$Form.close()
})
$form.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,75)
$CancelButton.Size = New-Object System.Drawing.Size(100,20)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({
$Form.DialogResult = "Cancel"
$Form.close()
})
$Form.Controls.Add($CancelButton)

$Form.Add_Shown({$Form.Activate()})

$result = $Form.ShowDialog()

if($result -eq "OK")
{
$DestServer = $DropDown.SelectedItem.ToString()
}
else
{
$DestServer = $null
}
#The Variable $Sharelocalpath is use in "Part 2 Creating a share on a remote computer" to help WMI
#to create the shared folder remotly using the Localserver Path to create the share if not the good value the U: drive will not map.

foreach( $Site in $SiteAttribute.location.Site){
   $var2 = $Site.city
    If ($var2 -match $DestServer -and $SrcServer -notmatch $DestServer ){
            $DESTINATION = $site.server
            $Street = $site.street
            $POBox = $site.POBox
            $city = $site.City
            $State = $site.state
            $Zip = $site.zip
            $Country = $site.country
            $OfficePhone = $site.OfficePhone
            $TargetOU = $site.TargetOU
            $Udrive = $site.Udrive + "$username$"
            $Sharelocalpath = $site.Sharelocalpath + $Username
            $NewSiteGroup = $site.NewSiteGroup
            $NewDFSGroup = $site.NewDFSGroup
            $DESTINATION
            Remove-ADGroupMember -server $DC -Identity $OldSiteGroup -Members $username -Confirm:$false
            Remove-ADGroupMember -server $DC -Identity $OldDFSGroup -Members $username -Confirm:$false
            Add-ADGroupMember -server $DC -Identity $NewDFSRemote -Members $username -Confirm:$false
            Add-ADGroupMember -server $DC -Identity $NewSiteGroup -Members $username -Confirm:$false
            Add-ADGroupMember -server $DC -Identity $NewDFSGroup -Members $username -Confirm:$false
            }
 }

My dropdownarray have the same value on both dropdown. But depending of my selection my var are going to change. thanks for helping.
John

A: Just a dirty example. Replace both your forms with this. You have to fill in the commands again since I just extracted one of your forms to modify it. It's pretty basic modifications if you just read the code. Or you could used the software(primalforms) that you used to design this with(since you don't understand the code) to make it.
$DropDownArray = @("Test1", "Test2", "Test3")

# Form building

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$Form = New-Object System.Windows.Forms.Form
$Form.width = 300
$Form.height = 200
$Form.Text = "User move Destination Location"
$Form.StartPosition = "CenterScreen"

$DropDownFrom = New-Object System.Windows.Forms.ComboBox
$DropDownFrom.Location = New-Object System.Drawing.Size(140,10)
$DropDownFrom.Size = New-Object System.Drawing.Size(130,30)

ForEach ($Item in $DropDownArray) {
    $DropDownFrom.Items.Add($Item) | Out-Null
}

$Form.Controls.Add($DropDownFrom)

$DropDownFromLabel = New-Object System.Windows.Forms.Label
$DropDownFromLabel.Location = New-Object System.Drawing.Size(10,10)
$DropDownFromLabel.Size = New-Object System.Drawing.Size(100,40)
$DropDownFromLabel.Text = "Select the user Original location ?"
$Form.Controls.Add($DropDownFromLabel)

$DropDownTo = New-Object System.Windows.Forms.ComboBox
$DropDownTo.Location = New-Object System.Drawing.Size(140,50)
$DropDownTo.Size = New-Object System.Drawing.Size(130,30)

ForEach ($Item in $DropDownArray) {
    $DropDownTo.Items.Add($Item) | Out-Null
}

$Form.Controls.Add($DropDownTo)

$DropDownToLabel = new-object System.Windows.Forms.Label
$DropDownToLabel.Location = new-object System.Drawing.Size(10,50)
$DropDownToLabel.size = new-object System.Drawing.Size(100,40)
$DropDownToLabel.Text = "Select the user Destination location ?"
$Form.Controls.Add($DropDownToLabel)

$OKButton = new-object System.Windows.Forms.Button
$OKButton.Location = new-object System.Drawing.Size(100,100)
$OKButton.Size = new-object System.Drawing.Size(100,20)
$OKButton.Text = "OK"
$OKButton.Add_Click({
$Form.DialogResult = "OK"
$Form.close()
})
$form.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,130)
$CancelButton.Size = New-Object System.Drawing.Size(100,20)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({
$Form.DialogResult = "Cancel"
$Form.close()
})
$Form.Controls.Add($CancelButton)

$Form.Add_Shown({$Form.Activate()})

$result = $Form.ShowDialog()


text:
Q: Stored procedures with joined data in entity framework We currently have a system with quite large database and stored procedures are used both for CUD and querying. DataSets are used to retrieve the results from the SP querys.
Now we are looking into developing another project against the same database using Entity Framework. When querying the database, the stored procedures often perform a lot of joins to gather some fields not in the target table, but data from the joined tables that is needed by the client in some way. When using DataSets, all the fields returned by the SP was included in the DataTable. So the DataTable doesn't actually match the target database table.
What is the correct way of handling this scenario in EF? When creating my model, the entities are mapped to each table which as mentioned above only sometimes matches the result of the SP. Can I add the "additional" fields of the SP query result to the entity class as properties and have them filled by the query but with these properties being excluded when it comes to CUD on the specific entity type? Seems like the EF-way, if queried through LINQ to Entities and not SPs, would be to have entity instances with relational properties to the joined entities so that using those "additional" properties would be done by navigating the relational properties?

A: You can define an arbitrary complex type (just a class that's generated for you, to match the columns and datatypes returned by the stored procedure) as the return type for your stored procedure in Entity Framework (as of version 4 and newer) - no problem here.
See Stored Procedures in the Entity Framework for a great explanation of all things related to using stored procedures in Entity Framework.


text:
Q: Why does my HTML category menu move the right when expanding the subcategories? I'm using the jQueryUI accordion widget to provide the functionality I need. I'm not that familiar with IE tweaks so the solution escapes me.
If you visit my test site, try to expand the categories using a modern browser such as Firefox, Opera or Chrome. It works as intended.
However when using IE8, the category tree moves to the left a bit, and there is even some bigger separation between the categories themselves.
What can I do to fix this bad behavior?
(Note: Forget about IE6,7 support, it just has to work, not look pretty. )

A: remove width from categories class, tried in ie8 and problem disappear

A: You have poorly formed HTML5 markup.  That might not be helping.  The number of list elements you have is real long so I'll just give a snippit.

MENÚ PRODUCTOS

CCTV
Circuito cerrado de televisión

Camaras

Camaras Infrarrojas

Profesional

On the 7th and 11th line above, you have UL tags but then proceed to use DIV tags.  UL tags can only have LI elements as a child per W3. http://www.w3.org/TR/2011/WD-html-markup-20110113/ul.html
I think your HTML could be closer to this:

MENÚ PRODUCTOS

CCTV Circuito cerrado de televisión

Camaras

Camaras Infrarrojas

Profesional

Though, there's probably better semantic use of tags possible than what I've got here.
You can then add a little padding to the left of your H3 > a tag and use the +/- gif as a background image that can be swapped with a CSS class.  That will make the swap real straight forward in jQuery to simply toggle the clicked anchor class.  That will help solve the previous bug I mentioned.
I hope that helps a little as Yucel seems to have a solution for the other issue, but there might be more going on with the HTML issues.
Cheers!


text:
Q: Save sql code used for creating database I am using windows terminal to create a simple database. I was wondering is the code used saved anywhere or do I have to save it? And how? I need to save the code I used for creating the database that's why I'm asking.

A: If you are talking about SQL Server, you can script out the database you created - just right click on the database in Management Studio, and script away!

A: Yes, you should save your work. Most tools don't save your indentation, they often format the sql in their own way - sometimees as
CREATE TABLE user@host.dbname.table AS ...

so it works to reconstruct your database, but isn't well readable. The worst thing I ever saw was what MsAccess did to my Input in the SQL-Window (but it was 15 years ago).

A: In MySQL you can use SHOW CREATE TABLE xxx to see the definition for your table(s).

A: Using mysqldump can help you create an sql file which you can later run to create a DB identical to yours.
It has many useful options you can read about here.
For your case it seems you need the schema only, without the data - see a how-to here. Basically all you need is the command:
mysqldump --no-data -u Username -pPassword mydatabase


text:
Q: Required disk space miscalculation preventing progress It seems that there is a mismatch between the disk space displayed in the GUI in MB and the actual space interpreted by the installer in KB.
The bug so far is being reproduced on RHEL 6.5 64b.

A: The installer requires a 10% safety margin that may be used by temporary files or for the actually larger amount of required disk space for small files.
That safety margin was not included in the displayed value on the "Installation location" screen. This will be fixed in install4j 6.0.2.


text:
Q: How can I use both resource.RetryError and diag.Diagnostics when developing a TF Provider Plugin SDK v2? Context: I'm developing a TF Provider Plugin SDK v2.
Recently I've found this doc that describes how to setup retries but it uses just error as a return type vs recommended diag.Diagnostics.
How can I use those 2 together? So far I'm thinking I could use:
func resourceFooCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {

    var diags diag.Diagnostics
    client := m.(*Client)

    // read params

    err := resource.RetryContext(ctx, ..., func() *resource.RetryError {
        resp, err := client.CreateFoo(params)
        if err != nil {
            switch err.(type) {
            case ServerError || 429Error:
                return resource.RetryableError(err)
            default:
                return resource.NonRetryableError(err)
            }
        }
        return nil
    })
    return diag.FromErr(err)
}

Did I get it right?


text:
Q: Threadpool not starting any new threads, but is below limit I have a app that uses async tasks to get Data from a MQTT server.
After I updated my System to Windows 11 I started noticing the Problem that the async tasks are not starting after the App runs for some Days.
This Worked fine before I upraded from Windows 10 to Windows 11.
Checking with a Debugger, I noticed that the Threadpool is set to minimum 16 tasks, but currently only has 1 task witch is waiting for another tasks that is not starting.
I also checked a Dump with Windbg and got this Result from !ThreadPool
CPU utilization: 9%
Worker Thread: Total: 1 Running: 0 Idle: 1 MaxLimit: 32767 MinLimit: 16
Work Request in Queue: 0
--------------------------------------
Number of Timers: 1
--------------------------------------
Completion Port Thread:Total: 1 Free: 1 MaxFree: 32 CurrentLimit: 1 MaxLimit: 1000 MinLimit: 16

My Code is basicly
Sub Test()
StartUpMQTT().Wait()
End Sub
Private Async Function StartUpMQTT() As Task
MQTTClient = Await Net.Mqtt.MqttClient.CreateAsync(strWebLink, Configuration) 'This is the Line where it waits for the unstarted task.
sessionState = Await MQTTClient.ConnectAsync(New MqttClientCredentials("TestAuslesung"))
End function

For now I changed my StartUpMQTT().Wait() to StartUpMQTT().Wait(5000), but I have to wait if this solves the issue of the whole app hanging.
Anything I can try to prevent this from happening/freezing the app, other than my change?


text:
Q: On time clicker JAVA code error Not understand WHY SCHEDULE underline always and not working (  I tried separated into classes, same thing, just can't get where the problem is.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;

    public class assertion extends JFrame {

     JTextField curTime, xT, yT;
     Timer timer;

     public static void main(String[] args){

      new assertion();

     }

     public assertion() {

      JFrame window = new JFrame("ВИ Кликер");
      window.setSize(400,400);

      JPanel mainframe=new JPanel();
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel x=new JLabel();
            x.setText("X-Coordinate");
            mainframe.add(x);

            xT=new JTextField(10);
            mainframe.add(xT);
            window.getContentPane().add(mainframe);
            window.pack();
            window.setVisible(true);

            JLabel y=new JLabel();
            y.setText("Y-Coordinate");
            mainframe.add(y);

            yT=new JTextField(10);
            mainframe.add(yT);
            window.getContentPane().add(mainframe);
            window.pack();
            window.setVisible(true);

            JLabel time=new JLabel();
            time.setText("Time");
            mainframe.add(o);

            curTime = new JTextField(10);
            mainframe.add(curTime);
            window.getContentPane().add(mainframe);
            window.pack();
            window.setVisible(true);

            JButton gO =new JButton();
            gO.setText("GO");
            mainframe.add(gO);

            gO.addActionListener(new ActionListener(){
             public  void actionPerformed(ActionEvent e){
         timer();
             }
          });

     }

     public void timer(){

      Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.HOUR_OF_DAY, 23);
      calendar.set(Calendar.MINUTE, 1);
      calendar.set(Calendar.SECOND, 0);
      Date time = calendar.getTime();

      timer = new Timer();
      timer.schedule(new assertion(), time);

     }

     public void mouse() throws AWTException {

      String xx = xT.getText(), yy = yT.getText();
      int xxx = Integer.parseInt(xx), yyy = Integer.parseInt(yy);

      Robot robot = new Robot();
      robot.mouseMove(xxx, yyy);
      robot.mousePress(InputEvent.BUTTON1_MASK);
      robot.mouseRelease(InputEvent.BUTTON1_MASK);
     }

    }

A: The class Timer is ambiguous between java.util.Timer and javax.swing.Timer so timer.schedule cannot be resolved.
Remove the package import
import java.util.*;

and only import the classes you need specifically, for example
import java.util.Calendar;

javax.swing.Timer is the correct Timer to use with Swing so you will need to refactor your code to account for this. There's no need to create a new instance of assertion - just ensure that all the methods are invoked the Swing Timer ActionListener.
Timer timer = new Timer(1000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        // perform timer actions
    }
});

Aside: Java Naming conventions show that classes start with an uppercase letter, e.g. Assertion

A: Assertion does not extend TimerTask which is needed.
Create an anonymous class like I showed you in the other question thread.


text:
Q: JavaScript - Drawing objects off the screen and other game optimizations In my game a large map exists, and I am wondering if not drawing shapes (average 250+ at a time) when the player cant see them would make any difference in the game's performance.
Also, every frame I am checking the distance of the player to about 500+ other position vectors (used for enemies, food, bullet interactions), which takes a lot of square rooting. If I make a raw estimate just using the X and Y components combined, would that significantly boost game performance?

A: The only way to answer these questions is to try it and see what happens. You have to weigh the cost of calculating whether something is on the screen against the cost of drawing it. Again, you're going to have to measure both and decide for yourself.
As for measuring distance, you could try using the distance squared to avoid the square root.
Or you could try storing your objects in a data structure like a quadtree, which allow you to you only check the distance of nearby objects. Or putting it simpler: do you really need all 500 vectors active all of the time? Why not store them and only activate them when you need them?
But again, the only way to answer your question is to try it. We can't tell you whether this will vastly improve performance in your game. Only you can answer that, by trying things out. Good luck.


text:
Q: Extra space character for "visited" link in profile When looking to "visited" field in profile page and cover it with mouse, I see underline like as if extra one space placed before "visited" word:

Related question in ruSO.meta (look at UPD section).


text:
Q: @PropertyName not working in Kotlin with Firestore I have troubles with Firestore as @PropertyName is totally ignored with data classes.
import com.google.firebase.database.PropertyName

data class Profile(
    @get:PropertyName("player_uuid")
    @set:PropertyName("player_uuid")
    @PropertyName("player_uuid")
    var playerUuid: String? = null,
   }

I've tried all combinations of annotations but none of them seem to work, because player Uuid will always be null when I get it from the server.
How I parse the object -
FirebaseFirestore.getInstance().document("profile/$id").get().await().toObject(Profile::class.java)

Same thing happens when I set the document
FirebaseFirestore.getInstance().document("profile/$id").set(profile).await()

On the firebase console, I will send playerUuid instead of player_uuid.

A: You're using the wrong import for Firestore.  The one you have now is for Realtime Database.  Use import com.google.firebase.firestore.PropertyName instead.

A: You have to add @Keep to your class. Or Proguard will rename the variables
Check in firestore datatabase if the field names are the variable names
@Keep
data class Profile(
@get:PropertyName("player_uuid")
@set:PropertyName("player_uuid")
var playerUuid: String? = null)


text:
Q: Call to a member function resize() on a non-object in I use a script to upload images.
in the script i want to create thumbnails.
First i make a copy, after the copy i want to resize the copy.
I have
$originalfile =//the file i just uploaded

$kopiefile = //the copy destination /same filename as original but with an extra dir added.

if (!copy($originalfile, $kopiefile)) {
    echo "failed to copy $originalfile...\n";
} else {
    $kopiefile = "http://mydomain.com/media/img/thumbs/".$file_name;
    echo $kopiefile;
    $kopiefile -> resize(300, 0, false);
}

the copy file works i can see the newly created file.
The echo $kopiefile gives me a link directly to the image wich works if i copy the link.
but now i get to the
$kopiefile -> resize(300, 0, false);

part and i get the error
Fatal error: Call to a member function resize() on a non-object in .... line 176
where line 176 is
$kopiefile -> resize(300, 0, false);

what is wrong with my code?
i also tryd to use:
$kopiefile = "/home/censored/domains/censored/public_html/ve/media/img/thumbs/".$file_name;
but it isnt working.
Can someone plz help me.

A: $kopiefile is just a string, and not an object, and therefore cannot have member functions like $someobject->resize().
You have to load the picture into an object which has some kind of resize method. What you're doing now is putting the url of the file in a string variable.
Try http://php.net/manual/en/function.imagecopyresized.php
Or this: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
Scroll to the bottom for the SimpleImage class code.
Use it like this:
<?php
   include('SimpleImage.php');
   $image = new SimpleImage();
   $image->load('picture.jpg');
   $image->resizeToWidth(250);
   $image->save('picture2.jpg');
?>

A: It looks you are using simpleimage php library. You have to load the image frist $image = SimpleImage('path.jpg'); then $image->resize() will works. First download simple image and then try it
download it here: simpleimage

A: $kopiefile is not object and has no method resize.
Try to use https://code.google.com/p/ag-php-classes/wiki/ImagesHelper class =)


text:
Q: How to make multiple LEFT JOINs with OR fully use a composite index? I am working on a timekeeping system and trying to determine that for each person, are they early or late for their scheduled shift.  The "TB_Scan" table originally had the person code and scan time which is a datetime field.  However, due to querying issues I was having, decided to add the scYear, scMonth and scDay fields thinking it might help.
It is a system that calculates how the users scan their fingerprints when they enter/leave the workplace. I don't know how it is called in English. I need to determine if the user is late in the morning, and if the user leaves work early.
This tb_scan table contains date and time a user scans a fingerprint.
CREATE TABLE `tb_scan` (
  `scpercode` varchar(6) DEFAULT NULL,
  `scyear` varchar(4) DEFAULT NULL,
  `scmonth` varchar(2) DEFAULT NULL,
  `scday` varchar(2) DEFAULT NULL,
  `scscantime` datetime,
  KEY `all` (`scyear`,`scmonth`,`scday`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

It has 100,000+ rows, something like this
scpercode scyear scmonth scday     scdateandtime
000001    2010      10     10      2016-01-10 08:02:00
000001    2010      10     10      2016-01-02 17:33:00
000001    2010      10     11      2016-01-11 07:48:00
000001    2010      10     11      2016-01-11 17:29:00
000002    2010      10     10      2016-01-10 17:31:00
000002    2010      10     10      2016-01-02 17:28:00
000002    2010      10     11      2016-01-11 05:35:00
000002    2010      10     11      2016-01-11 05:29:00

And this tb_workday table contains each date
CREATE TABLE `tb_workday` (
  `wdpercode` varchar(6) DEFAULT NULL,
  `wdshift` varchar(1) DEFAULT NULL,
  `wddate` date DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

It has rows with date sequence like this:
wdpercode  wdshift wddate
000001     1       2010-10-10
000001     1       2010-10-11
000001     1       2010-10-12
000001     1       2010-10-13
000002     2       2010-10-10
000002     2       2010-10-11
000002     2       2010-10-12
000002     2       2010-10-13

There is another tb_shift table containing shift time
CREATE TABLE `tb_shift` (
  `shiftcode` varchar(1) DEFAULT NULL,
  `shiftbegin2` varchar(4) DEFAULT NULL,
  `shiftbegin` varchar(4) DEFAULT NULL,
  `shiftmid` varchar(4) DEFAULT NULL,
  `shiftend` varchar(4) DEFAULT NULL,
  `shiftend2` varchar(4) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

shiftcode   shiftbegin2  shiftbegin  shiftmid  shiftend  shiftend2
        1     04:00:00     08:00:00  12:00:00  17:30:00  21:30:00
        2     12:00:00     17:30:00  21:00:00  05:30:00  09:30:00

I want to determine that in each day, is the employee comes to work late or leaves work early, and at what time.
SELECT wdpercode,wddate,shiftbegin,shiftend,time(tlate.scscantime) wdlate,time(tearly.scscantime) wdearly
FROM tb_workday
LEFT JOIN tb_shift
  ON wdshift=shiftcode
LEFT JOIN tb_scan tlate
  ON wdpercode=tlate.scpercode
  AND tlate.scyear=year(wddate)
  AND tlate.scmonth=month(wddate)
  AND (tlate.scday=day(wddate)
    OR tlate.scday=day(wddate)+1)
  AND tlate.scscantime>=ADDDATE(CONCAT(wddate,' ',shiftbegin),INTERVAL IF(shiftbegin2>shiftbegin,1,0) DAY)
  AND tlate.scscantime<=ADDDATE(CONCAT(wddate,' ',shiftmid),INTERVAL IF(shiftbegin2>shiftmid,1,0) DAY)
LEFT JOIN tb_scan tearly
  ON wdpercode=tearly.scpercode
  AND tearly.scyear=year(wddate)
  AND tearly.scmonth=month(wddate)
  AND (tearly.scday=day(wddate)
    OR tearly.scday=day(wddate)+1)
  AND tearly.scscantime>ADDDATE(CONCAT(wddate,' ',shiftmid),INTERVAL IF(shiftbegin2>shiftmid,1,0) DAY)
  AND tearly.scscantime<ADDDATE(CONCAT(wddate,' ',shiftend),INTERVAL IF(shiftbegin2>shiftend,1,0) DAY)

Here is the example of an output:
wdpercode wddate      shiftbegin  shiftend  wdlate    wdearly
000001    2016-01-10  08:00:00    17:30:00  08:02:00  (null)
000001    2016-01-11  08:00:00    17:30:00  (null)    17:29:00
000002    2016-01-11  17:30:00    05:30:00  17:31:00  (null)
000002    2016-01-11  17:30:00    05:30:00  (null)    05:29:00

this ADDDATE(CONCAT(wddate,' ',shiftbegin),INTERVAL IF(shiftbegin2>shiftbegin,1,0) DAY) is for employees who work on night shift, so it has to add 1 day into the shift time
The problem is if I create an index for scscantime, MySQL refuses to use it for comparison (>=,<=,>,<). Please see this thread Why does MySQL not use an index for a greater than comparison?
Because of this I created the scyear, scmonth, and scday fields and combine them in an index along with scpercode. And I have to make sure it calculates for workers working in night shift too so I have to add it with OR scday=day(wddate)+1 condition.
Before I added the OR condition, the EXPLAIN result was 52 rows. But when I added the OR scday=day(wddate)+1 condition, the EXPLAIN result became 364 rows, that means MySQL did not use scday part of the index. Is there any way to use the whole index, so the EXPLAIN result becomes 52 rows? I also tried removing the +1 part and the result is also 52.

A: From your query (readability formatted)
SELECT
      table1.*,
      tb21.year,
      tb21.month,
      tb21.day,
      tb22.year,
      tb22.month,
      tb22.day
   FROM
      table1
         LEFT JOIN table2 tb21
            ON table1.year = tb21.year
            AND table1.month = tb21.month
            AND (tb21.day = table1.day
              OR tb21.day = table1.day+1)
         LEFT JOIN table2 tb22
            ON table1.year = tb22.year
            AND table1.month = tb22.month
            AND (tb22.day = table1.day+2
              OR tb22.day = table1.day+3)

Aside from your restrictive content provided, lets look at you trying to compare the data from same day to day + 1, +2 and +3.  Lets also assume just for this example you have only 10 days in the table represented as all June 1 - June 10, 2016 in both your Table1 AND Table2 tables.
Again, this is an assumption that each table has all 10 dates in question just for simplistic purposes of why so many records.  So, for Table 1 date of June 1, 2016, it will qualify with table 2 (tb21 version) and return TWO records. One for June 1 and another for June 2.  So now you have TWO records in your result.  Now, you do that again left-join to table 2 (tb22 version).  This time you are looking for 2 and 3 days out, of which you have June 3 and 4 in the table.  So you are getting a Cartesian result.  So, for the June 1 record in table 1, you now have 4 records as follows.
T1Year  T1Month  T1Day  T21Day T22Day
2016    6        1      1      3
2016    6        1      1      4
2016    6        1      2      3
2016    6        1      2      4

Now, lets say your table 2 has 3 entries on June 2 and 3 entries on June 3 and your data is going to super bloat.  This is why you need to provide more clarification on what you are trying to do.
So, not having true context on what you are looking for, ignore the fact it is not perfectly utilizing your index.  You have an OR based on the date via the day comparisons.  It should still utilize for the query anyhow.


text:
Q: Get the type of redux's state I want to get a type for redux state, which will be used to mock said state.
So far I figured out I have this Reducer:
(alias) const reducer: {
    selectedElement: Reducer<StructureElement, AnyAction>;
    fetchedState: Reducer<FetchedState, AnyAction>;
    ... 10 more ...;
    mesApi: Reducer<...>;
}

So what I want to do, is somehow get the StructureElement, FetchedState and so on from inside of the Reducer</here/, AnyAction>; part.
How can I achieve that?
Or is there a better way to get combined state type? It has to be done automatically though. I don't want to change types in 2 places when it should be auto-generated.
If I try this:
type State = typeof reducer;

I get

Type '{ selectedElement: Reducer<StructureElement, AnyAction>; fetchedState: Reducer<FetchedState, AnyAction>; ... 10 more ...; mesApi: Reducer<...>; }' is not assignable to type '{ selectedElement?: { stateId: string; parentId: string; hasChild: boolean; pathList: string[]; name: string; color: string; isActive: boolean; level: number; children?: ...[]; key?: string; type: StateType; }; ... 11 more ...; mesApi?: { ...; }; }'.
Types of property 'selectedElement' are incompatible.

which makes sense.

A: I'd recommend to simply model it explicitly and then import those types where you need them:
export type UserState = {
    readonly isLoggedIn: boolean;
    // other user state here
};

// Type for entire global redux state
export type AppState = {
    users: UserState;
    // other sub-states here
};

A: I personally create a slice for each feature that I want in my state, then I have a file in which I'll first declare and export my RootState Type, and then I'll combine all of my reducers.
export interface RootState {
  pokemon: pokemonState;
  pokemonTrainer: pokemonTrainerState;
}

const reducer = combineReducers<RootState>({
  pokemon: pokemonSLice,
  pokemonTrainer: pokemonTrainerSlice,
});

Where pokemonState and pokemonTrainerState are the types of each feature.

And then I'll use RootState wherever I need.

A: Ok, I was being stupid. I had something like this back from the basic setup:
export type RootState = ReturnType<typeof store.getState>;

And it seems to do the trick.


text:
Q: Problem creating a timer in Objective C for the Iphone I've been having alot of problems creating a timer for a iphone application, currently I have a label displaying my timer, but it is just displaying the variable i (2700) in the label, and not decreasing by one every second. Its really driving my head in as this is really my 1st attempt coding in obj C, and for the life of me I cannot get it to decrease in the label.
I was hoping one of the programs on this site would be able to readover my code (MainViewController.m), with particular reference to the timer (countDown and viewDidLoad) and help me fix my problem.
Cheers in advance.
#import "MainViewController.h"
#include <unistd.h>
#include <stdio.h>

int i = 2700;

@implementation MainViewController
@synthesize window;
@synthesize InformationAboutRSI, mainView;

- (IBAction) InformationAboutRSI {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.rsi.org.au/what-is-rsi.html"]];
}

-(void)countDown {
    if (i > 0) {
        i--;
        countdownLabel.text = [NSString stringWithFormat:@"%i",i];
        sleep(100);
        }
    }

- (void)viewDidLoad {

   int countDown();
    [countdownLabel setFont:[UIFont fontWithName:@"DBLCDTempBlack" size:128.0]];
    countdownLabel.text = [NSString stringWithFormat:@"%i",i];
    [super viewDidLoad];

}

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller {

    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)showInfo:(id)sender {

    FlipsideViewController *controller = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
    controller.delegate = self;

    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];

    [controller release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [window release];
    [super dealloc];
}

-(void)updateLabel {
    countdownLabel.text = [NSString stringWithFormat:@"%i",i];

}

@end

A: When developing applications for most modern operating systems, you generally don't want to block the UI thread. This means that your code should do its work and get out of the way as quickly as possible, because while it blocks, the application can't do anything else (like respond to button presses). On a desktop application, blocking the UI thread for more than a couple of seconds will display an hourglass or pinwheel cursor.
With that in mind, you could design your countDown method to:

*

*Decrement the counter

*Update the label

Create an NSTimer (I would try scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:) in your initialization to ask the operating system to call countDown every X seconds.

A: You are calling your countdown method only once, i don't see a loop or timer that would repeat this action.
Have a look at the NSTimer reference.
or use a classic for loop
-(void)countDown
{
    for (int j = i, j > 0, j--)
        {
        countdownLabel.text = [NSString stringWithFormat:@"%i",j];
        sleep(100);
        }
}

you could call this method after loading your view and initializing the textfield with [self countDown];

A: You need to return from your countDown method without sleeping and without setting the label more than once.  The display will only update after you exit your code.
Then you need to find a way to call your countDown method again after a long enough delay and without sleeping anywhere else.  (Hint: use NSTimer)  Rinse and repeat.


text:
Q: The element type 'Color' can't be assigned to the map value type 'MaterialColor' How to set the colors I like with no problems, for example I set" PomodoroStatus.runningPomodoro: Colors.grey," and no problem, but when I want to customize the colors it throws 8 errors in each color property.
By the way, I'm using flutter with android studio.
This is my code
import 'package:flutter/material.dart';
import '../model/pomodoro_status.dart';
import 'package:flutter/cupertino.dart';
const pomodoroTotalTime = 240 * 60;
const shortBreakTime = 20 * 60;
const lonBreakTime = 60 * 60;
const pomodoroPerSet = 4;

const Map<PomodoroStatus, String> statusDescription = {
  PomodoroStatus.runningPomodoro: 'Pomodoro is running, try to be focused',
  PomodoroStatus.pausedPomodoro: 'Ready for a focused Pomodoro?',
  PomodoroStatus.runningShortBreak: 'Short break running, time to relax',
  PomodoroStatus.pausedShortBreak: "Let's have a short break",
  PomodoroStatus.runningLongBreak: 'Long break running, time to relax',
  PomodoroStatus.pausedLongBreak: "Let's have a long break",
  PomodoroStatus.setFinished: 'Congrats, you deserve a long break, ready to start?',
};

const Map<PomodoroStatus, MaterialColor> statusColor = {
  PomodoroStatus.runningPomodoro: const Color(0xFF5080D9),
  PomodoroStatus.pausedPomodoro: const Color(0xFFC2C2C2),
  PomodoroStatus.runningShortBreak:const Color(0xFF5950D9),
  PomodoroStatus.pausedShortBreak: const Color(0xFFC2C2C2),
  PomodoroStatus.runningLongBreak: const Color(0xFF5950D9),
  PomodoroStatus.pausedLongBreak: const Color(0xFFC2C2C2),
  PomodoroStatus.setFinished: const Color(0xFFC2C2C2),
};

A: Your statusColor map has MaterialColor as a value, so it will only accept colors within the Colors class.


text:
Q: FULL JOIN : Select the key I join on Here's the table I start with
CMS   |   defect_status
________________________
1     |   true
2     |   false
3     |   true
3     |   false

and here's what I want
   CMS    |      true_defects    |   false_defects
   1      |      1               |   0
   2      |      0               |   1
   3      |      1               |   1

So here's my code
SELECT DISTINCT
    false_table.CMS,
    true_table.true_defects,
    false_table.false_defects

FROM(
    SELECT DISTINCT
        CMS,
        COUNT(*) AS true_defects
    FROM data_table
    WHERE defect_status = 'true'
    GROUP BY CMS
) as true_table

FULL JOIN(
    SELECT DISTINCT
        CMS,
        COUNT(*) AS false_defects
    FROM data_table
    WHERE defect_status = 'false'
    GROUP BY CMS
) as false_table
ON true_table.CMS = false_table.CMS

I would like to select all CMS, those in "false_table" and "true_table".
If I select "false_table.CMS" (as in the code above), here's what I get :
CMS    |      true_defects    |   false_defects
2      |      0               |   1
3      |      1               |   1

CMS "1" has disappeared simply because it's not in the column false_table.CMS
Thank you

A: You can achieve it by simple case and group by  as below:
SELECT t1.CMS
    ,sum(CASE defect_status
            WHEN true
                THEN 1
            ELSE 0
            END) AS true_status
    ,sum(CASE defect_status
            WHEN false
                THEN 1
            ELSE 0
            END) AS false_status
FROM Table1 AS t1
GROUP BY CMS

Demo link: http://sqlfiddle.com/#!17/8478d/1


text:
Q: Bash returning my variable empty in text file I'm trying to make simple bash which will find my IP and then update it in .txt template. When I ran bash I my file is filled with blank spot instead of IP address.
alias wanip='curl -s http://whatismijnip.nl |cut -d " " -f 5'
wanip
sed -i -e "s/\${ip}/"$wanip"/" config.txt

A: Try this:
wanip="$(curl -s http://whatismijnip.nl |cut -d " " -f 5)"
sed -i -e "s/\${ip}/"$wanip"/" config.txt

I suppose $ip is no variable.


text:
Q: espacios a la derecha al pasar datos a input text en modal este es mi caso espero me puedan ayudar
tengo una tabla la cual lleno con datos desde mysql, cada fila tiene un boton que despliega una ventana modal la cual lleva los datos de la fila sobre la que se dio click en el boton. Todo funciona bien salvo que me deja un numero considerables de espacios en blanco a la izquierda del dato que lleva y no se como quitarlos, ya intente usando trim para quitarlos pero no lo consigo.
Esta es la forma en que lleno la tabla

                            Nombre
                            Rol
                            Correo
                            visualizar

                            <?php foreach($consulta as $info): ?>

                                <span id="alias<?php echo $info->getID();?>">
                                        <?php echo $info->getNombre(); ?>

                                    <?php echo $info->getRoles(); ?>

                                    <?php echo $info->getCorreo(); ?>

                                <button type="button" class="btn btn-danger btn-sm  Mostrar" value="<?php echo $info->getID(); ?>">Visualizar</button>

                            <?php
                        endforeach;
                        ?>

Esta viendo:

                <button class="close" data-dismiss="modal" aria-label="Cerrar">
                    ×
                </button>

                        <form action="" method="post" class="form-group ">
                            <input type="text" class="form-control crea_data" id="alias" name="alias">
                            <input type="submit" value="Confirmar" id="confirmar" name="confirmar" class="mt-4 btn btn-danger btn-sm btn-guardar">
                        </form>

Como podrán ver deja espacios a la izquierda del dato que debería mostrar
De antemano gracias por la ayuda

A: El error puede ser por que estas dejando espacio entre
<span id="alias<?php echo $info->getID();?>">

y
echo $info->getNombre(); ?>

Modificalo uno al lado del otro, sin dejar ningun tipo de espacio, salto de linea ni nada.


text:
Q: Cannot convert parameter 1 from derived pointer to base class pointer reference i have class that inherits from base class ,
then i have method that excepts as parameter pointer reference to base class .
when i try to pass the inherited object to the method im getting :
c++ cannot convert parameter 1 from 'ReelSymbol *' to ' Sprite *&'
Sprite  is frame work base class
class ReelSymbol :public Sprite
{
    public:
          ReelSymbol();
          ~ReelSymbol();

};

this is the method that i try to pass the ReelSymbol object pointer to
void UT::setSpriteReelsSymbolBoundingBoxSize(Sprite* &sprite)
{
    //DOTO to think if to use scale or bounding box size
    sprite->setScale(pSettings->ReelSymbolScaleFactor);
}

like this :
ReelSymbol* sprite = new ReelSymbol();
ut.setSpriteReelsSymbolBoundingBoxSize(sprite);

and getting this error:
c++ cannot convert parameter 1 from 'ReelSymbol *' to ' Sprite *&'

A: The problem with what you're trying to do is that if it would compile, then the function setSpriteReelsSymbolBoundingBoxSize could reset the variable you pass to something that is a Sprite*, but not a ReelSymbol*.
To clarify, consider the following (and pretend it would compile):
class NotAReelSymbol : public Sprite
{
};

void UT::setSpriteReelsSymbolBoundingBoxSize(Sprite* &sprite)
{
    sprite = new NotAReelSymbol;
}

ReelSymbol* sprite = new ReelSymbol();
ut.setSpriteReelsSymbolBoundingBoxSize(sprite);

Now, what's the original sprite variable of type ReelSymbol* supposed to look and behave like? This should demonstrate why the code you were trying to compile is just not valid and the compiler correctly rejects to compile it.
A possible workaround might be:
ReelSymbol* sprite = new ReelSymbol();
Sprite* sprite_base = sprite;
ut.setSpriteReelsSymbolBoundingBoxSize(sprite_base);

If you could guarantee that setSpriteReelsSymbolBoundingBoxSize will not reset the original variable to something that is not a ReelSymbol*, then afterwards you could do
sprite = dynamic_cast<ReelSymbol*>(sprite_base);

However, I find it far more likely, that you don't need to reset the original variable. Instead, by declaring the parameter as reference you were trying to express that the function is allowed to change the object to which spirit points. But since it's a pointer variable it's already clear, that the function can modify it. Thus, simply remove the &-symbol to make your code compile and work as expected:
void UT::setSpriteReelsSymbolBoundingBoxSize(Sprite* sprite);

A: The only problem here is your pointer reference
Sprite* &sprite

There is no need to make it a reference because you already have the pointer.
Like this:
Sprite* sprite

Your compiler would automatically down cast it to your base class "Sprite" as it was expected by you


text:
Q: Android: is it better to read a long string from file at runtime or to save it as an Android String Resource from the beginning? I am working on a project for Android (I'm currently using Android Studio, coding in Java) that requires a large amount of very long strings to be loaded dynamically in some TextViews. It's a sort of book, with each string being a page.
I was considering two options to achieve this:

*

*Use some .txt assets and read them at runtime (but I don't know how much this could affect performance)

*Save every page inside a string resource.
Could you tell me what do you think is best practice, and why?

A: Strings resources are best used to store string values pertaining UI related stuff, like EditText hints, Dialog messages and etc. Mainly because it helps to avoid hardcoding texts on views (often considered a bad practice). It also allows for optimal formatting and makes easier to translate your app to other languages.
Depending on the amount of data that you are going to put there, it's probably best (for the sake of your project's organization) to use a external source and load it from there.
For more info on string resources, please refer to this link:
https://developer.android.com/guide/topics/resources/string-resource.

A: In general, if you are doing IO intensive stuff, it should be done outside of the Android UI thread. This can be achieved using AsyncTask, RxJava or Kotlin Coroutines if you are using Kotlin.

Save every page inside a string resource.

Using Context::getString(int) doesn't seem like the best option for large amount of text. It is unclear to me from the Android specification whether it uses threading. It appears to me that all the string resources are preloaded into memory. If that is the case, large amount of text would mean inefficient use of memory. Although, this blocking call shouldn't take too long since it is implemented with several native jni methods.

Use some .txt assets and read them at runtime (but I don't know how much this could affect performance)

This is what I would do. Have the text in the assets folder, then use an AsyncTask to read the file without blocking the UI. Optionally show a loading spinner.


text:
Q: Justifying the fractional derivative power rule with the fractional derivative's formal definition (Riemann-Louiville) I have just seen that this is a duplicate but I don't follow how to arrive at the final power rule from where this question cuts off!
$$D_\alpha^nf(x)=\frac{1}{\Gamma(\lceil n\rceil-n)}\frac{d}{dx^{\lceil n\rceil}}\int_\alpha^xf(t)(x-t)^{\lceil n\rceil-n-1}\space dt$$
Where $\alpha$ is the base point for which $F(\alpha)=0$, $F'(x)=f(x)$ - I think, anyway; the video I saw that justified the repeated integration formula relied on this fact to make the formula work...
Anyway, aside from a small quibble about what $\alpha$ really is here, I think I understand this formula, but I do not understand where the following power rule comes from:
$$D_\alpha^n(x^k)=\frac{\Gamma(k+1)}{\Gamma(k+1-\alpha)}x^{k-\alpha}$$
I appreciate the arguments that take the ordinary power rule and just extend it to the reals with the use of $\Gamma$, but I would like to understand how to get to this formula through the integral definition.
I've tried integration by parts on the following expression but I can't make it work - also, since $x$ is a bound of the integral, does that affect how we differentiate the integral with respect to $x$ if we tried to move the derivative operator inside the integral?
$$\frac{1}{\Gamma(\lceil n\rceil-n)}\frac{d}{dx^{\lceil n\rceil}}\int_\alpha^xt^k(x-t)^{\lceil n\rceil-n-1}\space dt$$

A: After some learning at home, and realising how to continue the work of the proof I linked at the beginning of my question, I have the following proof (without tediously detailed working) for any who might be curious:
$$J_x^\kappa f(x)=\frac{1}{\Gamma(\kappa)}\int_\beta^x(x-\tau)^{\kappa-1}f(\tau)d\tau
$$
Letting $\kappa=\lceil\varphi\rceil$:
$$\begin{align*}&D_x^\varphi f(x)=\frac{d^\kappa}{dx^\kappa}D_x^{\varphi-\kappa}f(x)=\frac{d^\kappa}{dx^\kappa}J_x^{\kappa-\varphi}f(x)
\\
\\ &D_x^\varphi f(x)=\frac{1}{\Gamma(\kappa-\varphi)}\frac{d^\kappa}{dx^\kappa}\int_\beta^x(x-\tau)^{\kappa-\varphi-1}f(\tau)d\tau
\\
\\ &D_x^\varphi f(x)=\frac{1}{\Gamma(\kappa-\varphi)}\int_\beta^x\frac{\partial^\kappa}{\partial x^\kappa}(x-\tau)^{\kappa-\varphi-1}f(\tau)d\tau
\\
\\ &D_x^\varphi f(x)=\frac{1}{\Gamma(\kappa-\varphi)}\frac{\Gamma(\kappa-\varphi)}{\Gamma(-\varphi)}\int_\beta^x(x-\tau)^{-\varphi-1}f(\tau)d\tau
\\
\\ &D_x^\varphi f(x)=\frac{1}{\Gamma(-\varphi)}\int_\beta^x\left(1-\frac{\tau}{x}\right)^{-\varphi-1}x^{-\varphi-1}f(\tau)d\tau
\\ \end{align*}
$$
Letting $\nu=\frac{\tau}{x}$ and $\beta=0$:
$$
D_x^\varphi f(x)=\frac{1}{\Gamma(-\varphi)}\int_0^1(1-\nu)^{-\varphi-1}x^{-\varphi}f(x\nu)d\nu
$$
Suppose $f(x)=x^\omega$, and let $B$ denote the Beta function:
$$\begin{align*}&D_x^\varphi x^\omega=\frac{1}{\Gamma(-\varphi)}\int_0^1(1-\nu)^{-\varphi-1}x^{-\varphi}(x\nu)^\omega d\nu
\\
\\ &D_x^\varphi x^\omega=\frac{1}{\Gamma(-\varphi)}x^{\omega-\varphi}\int_0^1(1-\nu)^{-\varphi-1}\nu^\omega d\nu
\\
\\ &D_x^\varphi x^\omega=\frac{1}{\Gamma(-\varphi)}x^{\omega-\varphi}B(\omega+1,-\varphi)
\\
\\ &D_x^\varphi x^\omega=\frac{\Gamma(\omega+1)}{\Gamma(\omega-\varphi+1)}x^{\omega-\varphi}
\\ \end{align*}
$$
And as such, we have one valid fractional derivative power law for $x^\omega$ as required.


text:
Q: StreamReader Peek() method breaking without throwing exception I have a chrome native messaging host application that reads JSON messages from STDIN and writes data to STDOUT.
The problem I am facing right now is with the StreamReader.Peek() method.
On debugging on first iteration it runs successfully, but on second iteration it breaks at reader.Peek() point with out throwing any exception.
The control just goes away without any exception.
var length = 0;
var lengthBytes = new byte[4];
stdin.Read(lengthBytes, 0, 4);
length = BitConverter.ToInt32(lengthBytes, 0);

var messageBuffer = new char[length];
using (var reader = new StreamReader(stdin))
{
    while (reader.Peek() >= 0)
    {
        reader.Read(messageBuffer, 0, messageBuffer.Length);
    }
}

var message = new string(messageBuffer);
Log.Debug(message);
var jsonMessageObject = JsonConvert.DeserializeObject<JObject>(message);

if (jsonMessageObject == null)
{
    return null;
}

Can someone help how to know whats going wrong even though it had read all the data perfectly?
Why is Peek() breaking without any exception?


text:
Q: elasticsearch copy_to formatted date I have elasticsearch 6.4.2 with a mapping like this:
date_of_birth": {
    "type": "date"
},
"prefix_search": {
    "type": "text"
}

and by using copy_to feature I want to add date_of_birth into prefix_search (which later to use for some text based search). When queering ES I get e.g. 1430438920000 for date_of_birth but when adding it to prefix_search I want to have it formatted to e.g. 2018.05.24 (or some other format, doesn't matter exactly which one).
In order for the formatted date to be useful when searching prefix_search one would have to craft a custom analyzer - please consider this as another problem.
What should I do when using copy_to feature in order to append the formatted value of a date property to the target property?
Thank you!

A: copy_to index to the raw source of your field in another field with the target field analysis chain.
You can either
1/ use a script processor in a pipeline (but i think it will be a real pain in the a..)
2/ add the formatted data in the source you want to index in another field (like date_of_birth_formatted) and configure the copy_to on it
3/ use the same date_of_birth field, format the data before indexing and change the date format on the date_of_birth field


text:
Q: Restoring Windows XP programs after format I've recently had to format my laptop after Windows failed. Upon reboot I noticed all my program files were still on the hard drive but I cannot open them, is there a way (without reinstalling every one) to get them working again?
Cheers!

A: To get them working you need to restore the registry and possibly a few environment variables to the state they were in prior to your reinstallation of Windows.
While you might be able to search the internet and find these values the simplest solution is probably going to be to reinstall - I suppose it depends on how many applications you have (or should I say had) installed.
Have you tried just double clicking on the exe in the Program Files directory? It might not work for all applications, but some might run, and reset their registry settings - then all you need to do is add a shortcut to your desktop or the All Programs menu. Of course you won't be able to uninstall these applications easily.
Some installers might detect the presence of the folder (assuming you installed it into the default location) and offer a Repair option which should just update the registry in your case, so that might save a little time.
Once you've got everything reinstalled you should do something we all should do (but often don't) and back up your registry.


text:
Q: C double limitations in python I know python is capable of handling arbitrary big integers, so why doesn't it give me one when using scientific notation?  Why is 1e23 any different from 10**23?
Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> for x in range(30):
...   x1 = eval('long(1e{})'.format(x))
...   x2 = eval('long(1{})'.format('0' * x))
...   print x1, 'OK' if x1 == x2 else 'YUCK!'
...
1 OK
10 OK
100 OK
1000 OK
10000 OK
100000 OK
1000000 OK
10000000 OK
100000000 OK
1000000000 OK
10000000000 OK
100000000000 OK
1000000000000 OK
10000000000000 OK
100000000000000 OK
1000000000000000 OK
10000000000000000 OK
100000000000000000 OK
1000000000000000000 OK
10000000000000000000 OK
100000000000000000000 OK
1000000000000000000000 OK
10000000000000000000000 OK
99999999999999991611392 YUCK!
999999999999999983222784 YUCK!
10000000000000000905969664 YUCK!
100000000000000004764729344 YUCK!
1000000000000000013287555072 YUCK!
9999999999999999583119736832 YUCK!
99999999999999991433150857216 YUCK!

A: 1e23 is interpreted as a floating point number whereas 10**23 is an integer raised to an integer power (i.e. an integer)

A: Python floating point type use numbers native to the system architecture for computations - usually 64 bit floating points as defined here:  http://www.ee.unb.ca/tervo/ee6373/IEEE64.htm
I am not  certian if it can build using other floating point data types by default - but I know that if the architecture where Python is running has peculiarities in F>p> number handling, those will show up in Python - therefore you could have differences in Python program running in x86 hardware to those running in PPC, ARM or other CPUs.
However, if you want to use arbitrary precision decimal numbers in Python it is possible with the module Decimal. As of the recently released Python 3.3, the speed for Decimal numbers is comparable to that of native floating point numbers (inside a Python program - native code able to use F.P. speedups such as  SIMD instrucions would be much faster)


text:
Q: FastAPI doesn't include a JSON content type in the header, if a trailing slash is in the URL Depending on whether or not my URL has a trailing slash in it, FastAPI (with uvicorn server), will omit a content type: application/json header. I'm worried that clients might inadvertently put in a trailing slash in their URLs, and then not get back a JSON response, so I'd like to know
a) Is this correct behaviour?
b) How do I handle it server side?
Here is a very simple FastAPI application:
from fastapi import FastAPI
app = FastAPI()

app.get("/alist")
async def alist():
    somelist = [1, 2, 3, 4, 5]
    return somelist

Now here is what the headers look like for the "correct" request, namely one without a trailing slash:

Because WITH a trailing slash, the content-type: application/json is missing, and this can confuse the client.

So as per my question above, is this normal? And what do I do about it to prevent errors from clients expecting JSON response but which inadvertently added a trailing slash?

A: a) Is this correct behavior?

*

*This behavior appears because of redirection (HTTP status code 307).

*I think this should be handled automatically.

*So I think we should open a new issue in FastAPI repo.

b) How do I handle it server-side?
There are many different solutions :
1 - By converting the list to dict using one key trick (simple solution) :
from fastapi import FastAPI
app = FastAPI()

app.get("/alist")
async def alist():
    somelist = [1, 2, 3, 4, 5]
    return {"numbers": somelist}

2 - By adding "content-type" header manually :
using Response :
from fastapi import FastAPI, Response

app = FastAPI()

app.get("/alist")
async def alist(response: Response):
    # set content-type header to application/json
    response.headers["content-type"] = "application/json"
    somelist = [1, 2, 3, 4, 5]
    return somelist

using JSONResponse :
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

app.get("/alist")
async def alist():
    somelist = [1, 2, 3, 4, 5]
    # you can add additional headers
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    # json response will enforce "content-type" header to be "application/json"
    return JSONResponse(content=somelist, headers=headers)

You can read more about FastAPI responses and headers at https://fastapi.tiangolo.com/advanced/response-headers/


text:
Q: What's the lightest/fastest way to deliver data to mobile devices? I am looking for methods that let you deliver data to a user. This may be from XML to a flat-file DB to a relational DB.
This DB will be saved in a server and will serve handheld devices, smartphones and tablets on request. My main concern is the speed of displaying the requested info over millions of rows and how the data can be easily updated.
Before posting this, I made some Google searches pointing me to SQLite. What is your opinion about this ?

A: if you want the mobile devices to preform actions on the data(like offline processing) I think sql lite is the way to go.
if the processing gonna happen online anyway and the mobile device would be most for displaying and will be in an environment  where you are "always" online then Web services for requesting and processing the data and then a backend sql server would be the way to go
In tearms of preformance it is like this:
alot of data = alot of online traffic so if really alot of data like you said milions of rows then I think offline is the way to go otherwise the traffic would just kill the preformance

A: If you are dealing with millions of rows and you want to display small samples at a time (anything else is hardly possible) on mobile devices, you should definitely do the processing at the server side, best using an RDBMS. Those are made for handling millions of rows. Sqlite is fast and simple, but in the millions-of-rows-range you'd better reach for PostgreSQL or one of the commercial brands (Oracle, MS SQL server, ..).
You can use a web service or direct access to the database, that depends. You can do some processing locally, but the selection of rows has to happen at the server.

A: You would probably be better off setting up a SOAP/XML-RPC service and working the data on the server and sending it to the client pieces at a time, caching as you go. This is going to be potentially the "fastest" way, since you don't have to transmit a large file to a handheld. It may not work for you, but it's worth mentioning.
This is essentially just a file download bracketed by an output to a transport format and an input to the mobile device's datastore. I imagine you're describing something like a dictionary, something that is fairly static.
The approach you're going to want to achieve will need to:

*

*Take into account overall file size, ie, utilize as little meta description as you can get away with to communicate the data's meaningfulness.

*Utilize some type of compression (gzip, for instance) of the data between the server and device. Consider that aggressive compression may take longer on the device to uncompress and be counter-productive to a less aggressive approach that's significantly faster.

*Take into account how the data will get out of your server's storage (Is it in a database? Can you cache the data into the transport form?) into the device's data storage system (ie, SQLite). Going out of your way to compress the transfer speed significantly may in the end be counter-productive if the device has to work three times longer to insert the data than the time that was saved in downloading to the device.

*Test. Test. Test.

You could serve it as a CSV or JSON-formatted file, which are very minimalistic; they don't use a lot of data to describe the data. XML is not the fastest because it is generally very descriptive, but has other advantages. Another option may be send a text file with the SQL insert statements.
Another "option", of course, may be to use the update mechanism and push it out as an "update". My thought on this is that many people with mobile devices know updates are time consuming and are often very large downloads, so they connect to their computer when doing so. This is just a thought; I'm not sure if this would actually be any better, but thought I'd throw it out there.
SQLite is an RDBMS that runs on many mobile platforms. It has it's limitations, but it may be all you have to work with. It's a good option.


text:
Q: How to return text from GP service? So I've got a website that I want to extend by letting people look up postal/zip codes for an address they enter.  I've already got all the addresses (with their postal codes) for the city in an ArcSDE geodatabase.
What I'd like to happen is that the user will enter a civic number, select a street from a dropdown list and then upon clicking a button the postal code for the address will appear in it's text box.
I've created a script tool that takes two arguments: civicNumber and streetName and then uses a search cursor to get the postal code for the address.  If it finds the postal code the tool uses arcpy.AddMessage() to return the postal code.
This actually works, I've turned the tool into a GP Service and tested it from the web and the postal code is indeed being returned in a esriJobMessageTypeInformative JSON object.
My question is this: Is there any way for the Python script to return the Postal Code as a string without using the arcpy.AddMessage() function?

A: You could return it as a parameter.
outputAddress = #logic you already have to get this
arcpy.SetParameterAsText(2, outputAddress)
#2 being the index, since you have 2 inputs (0, 1), I say 2 being your 3rd parameter

After this bit of code, its just a matter of creating a new output parameter in the script tool properties. I'd make it a derived string.
Your web app would then get the output result (of type string) and display it some way.


text:
Q: Can I left or right justify my webpage that uses the 960 CSS framework? I just started playing around with the 960 CSS framework and found that it centers my page in the browser.  How can I change this so that the page is aligned to the left side of the browser window?
Thanks in advance for your help!

A: I would need to see your specific CSS stylesheet for the 960, but whatever your container div is called -- usually
<div id="container">

or something similar. In the CSS, you can accordingly remove this one-line setting:
#container { margin: 0 auto; }

That should align your 960 grid to the left and I see no reason why that would be a fundamental problem for the grid or for valid CSS.