问:
docker image is running but webpage error - Docker
I have a basic django project and I am trying to get it running locally through docker. I have the docker file. I build the docker image. I ran the docker image. It is running, but my webpage shows an error on the screen like it is not connecting to the docker server... Here is what I have:

docker file:

```<code>FROM python:3
WORKDIR general
COPY requirements.txt ./
EXPOSE 8000
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
</code>```

Here is how I am buiding and running this project:

```<code>omars-mbp:split omarjandali$ docker build -t splitbeta/testing2 .
Sending build context to Docker daemon  223.7kB
Step 1/7 : FROM python:3
 ---> 79e1dc9af1c1
Step 2/7 : WORKDIR general
 ---> 04a6f8a7f92a
Removing intermediate container b2ffb485e485
Step 3/7 : COPY requirements.txt ./
 ---> 649d77ec499e
Step 4/7 : EXPOSE 8000
 ---> Running in 7d8d6fe8de1d
 ---> c328d885a5f1
Removing intermediate container 7d8d6fe8de1d
Step 5/7 : RUN pip install -r requirements.txt
 ---> Running in 1c9aca43dc14
Collecting Django==1.11.5 (from -r requirements.txt (line 1))
  Downloading Django-1.11.5-py2.py3-none-any.whl (6.9MB)
Collecting gunicorn==19.6.0 (from -r requirements.txt (line 2))
  Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB)
Collecting pytz (from Django==1.11.5->-r requirements.txt (line 1))
  Downloading pytz-2017.3-py2.py3-none-any.whl (511kB)
Installing collected packages: pytz, Django, gunicorn
Successfully installed Django-1.11.5 gunicorn-19.6.0 pytz-2017.3
 ---> 602e88557c8b
Removing intermediate container 1c9aca43dc14
Step 6/7 : COPY . .
 ---> 55cff629cb51
Step 7/7 : CMD python manage.py runserver 0.0.0.0:8000
 ---> Running in efd75f8fb602
 ---> 2cef664a626d
Removing intermediate container efd75f8fb602
Successfully built 2cef664a626d
Successfully tagged splitbeta/testing2:latest
omars-mbp:split omarjandali$ docker run -d spltibeta/testing2
</code>```

Here is the project running:

```<code>omars-mbp:split omarjandali$ docker ps
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS               NAMES
fc14f03a18b0        splitbeta/testing2   "python manage.py ..."   3 seconds ago       Up 3 seconds        8000/tcp            loving_volhard
</code>```

THe webpage is giving the following error when it is supposed to display a template page....

```<code>This site can’t be reached

127.0.0.1 refused to connect.
</code>```

I got it running yesterday but it is not working any more... I dont know why. I didnt change anything

I am logged into my dockerhub account in my terminal

答:
It seems your Docker run command doesn't publish port 8000. By default, docker won't publish any container ports on the host system if you don't tell it to explicitly. Try using the -p or --publish option of docker run:

```<code>docker run -d -p 8000:8000 spltibeta/testing2
</code>```

Alternatively, you can use the -P or --publish-all option to publish all exposed ports of your container on your host system. This will assign a random port on the host.

```<code>docker run -d -P spltibeta/testing2
</code>```

Body:
I have a basic django project and I am trying to get it running locally through docker. I have the docker file. I build the docker image. I ran the docker image. It is running, but my webpage shows an error on the screen like it is not connecting to the docker server... Here is what I have:

docker file:

FROM python:3
WORKDIR general
COPY requirements.txt ./
EXPOSE 8000
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Here is how I am buiding and running this project:

omars-mbp:split omarjandali$ docker build -t splitbeta/testing2 .
Sending build context to Docker daemon  223.7kB
Step 1/7 : FROM python:3
 ---> 79e1dc9af1c1
Step 2/7 : WORKDIR general
 ---> 04a6f8a7f92a
Removing intermediate container b2ffb485e485
Step 3/7 : COPY requirements.txt ./
 ---> 649d77ec499e
Step 4/7 : EXPOSE 8000
 ---> Running in 7d8d6fe8de1d
 ---> c328d885a5f1
Removing intermediate container 7d8d6fe8de1d
Step 5/7 : RUN pip install -r requirements.txt
 ---> Running in 1c9aca43dc14
Collecting Django==1.11.5 (from -r requirements.txt (line 1))
  Downloading Django-1.11.5-py2.py3-none-any.whl (6.9MB)
Collecting gunicorn==19.6.0 (from -r requirements.txt (line 2))
  Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB)
Collecting pytz (from Django==1.11.5->-r requirements.txt (line 1))
  Downloading pytz-2017.3-py2.py3-none-any.whl (511kB)
Installing collected packages: pytz, Django, gunicorn
Successfully installed Django-1.11.5 gunicorn-19.6.0 pytz-2017.3
 ---> 602e88557c8b
Removing intermediate container 1c9aca43dc14
Step 6/7 : COPY . .
 ---> 55cff629cb51
Step 7/7 : CMD python manage.py runserver 0.0.0.0:8000
 ---> Running in efd75f8fb602
 ---> 2cef664a626d
Removing intermediate container efd75f8fb602
Successfully built 2cef664a626d
Successfully tagged splitbeta/testing2:latest
omars-mbp:split omarjandali$ docker run -d spltibeta/testing2

Here is the project running:

omars-mbp:split omarjandali$ docker ps
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS               NAMES
fc14f03a18b0        splitbeta/testing2   "python manage.py ..."   3 seconds ago       Up 3 seconds        8000/tcp            loving_volhard

THe webpage is giving the following error when it is supposed to display a template page....

This site can’t be reached

127.0.0.1 refused to connect.

I got it running yesterday but it is not working any more... I dont know why. I didnt change anything

I am logged into my dockerhub account in my terminal

Body:
It seems your Docker run command doesn't publish port 8000. By default, docker won't publish any container ports on the host system if you don't tell it to explicitly. Try using the -p or --publish option of docker run:

docker run -d -p 8000:8000 spltibeta/testing2

Alternatively, you can use the -P or --publish-all option to publish all exposed ports of your container on your host system. This will assign a random port on the host.

docker run -d -P spltibeta/testing2


来源: stackexchange

问:
Rails controller testing: Testing in isolation or integration?
I'm a bit confused when testing Rails controller, whether to test them in isolation(mocking, less DB hits: faster), or in an integration way(no mocking, a lot of DB hits: slower).

Say we have this example:

```<code>class ProductsController

  def create
    product = Product.new(product_params)
    if product.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def product_params
    require(:product).permit(:name, :price)
  end

end

RSpec.describe ProductsController do

  describe '#create in isolation' do
    it "pass" do
      params = { name: "name", price: 100}
      mocked_product = double(save: true)
      expect(Product).to receive(:new).with(params).and_return(mocked_product)

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

  describe '#create in integration' do
    it "pass" do
      params = { name: "name", price: 100}

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

end
</code>```

Testing in isolation doesn't hit the DB which makes it faster, however what if in Product model
we added a description field that is required, where we forget to add it to product_params method, which will
result in Product record not receiving description, and it won't be valid when saved.

Then the first test will pass with no problems, making a false positive that our controller code is okay, where actually
it is not because we have to change product_params method for it to work

The second test will fail because we didn't mock creating the product.

I think this is an open question/topic any way, so I wonder if there is best practices when doing controller tests.

EDIT(generalizing the idea)

I think this can be generalized as it is not limited to controllers but the concept of testing in isolation, the basic idea is the following:

Assume we have a function func(x,y), this function has its own units tests. Then when we have another servive(S) calling func, we will just stub func call as it is tested elsewhere, in order to save time from executing func (especially when it consumes time, like DB hits!)

expect(func).to receive(some_x, some_y).and_return(some_value)

This is the basic idea of testing in isolation.

The problem with this, what if the method signature of func didn't change, however the arguments passed to func from S now will make func throw some exception, due to some implementation changes in func itself, where S is still calling func with the old arguments values, which will result in exception now. And since we mocked calls to func, S test won't catch this error and the code will be deployed successfully.

I believe this is the general pattern

答:
It really depends on what your priorities are, and what sacrifices you're willing to make for fast tests.

Mocked data will definitely mean faster tests as you're removing the database layer. The cost of this is that if there is a bug that only arises when your controller is interacting with your data persistence layer, you won't catch the bug. Fast unit testing vs slow full-stack-many-pieces-working-together-at-the-sam- time testing.

Opinions vary on this. The overall trend in rails testing seems to be moving to integration/feature/system tests and abandoning most controller tests. This is because there is a lot more at play these days with advanced CSS styling and Javascript coming into play. There is no right answer.

ContentLicense: CC BY-SA 3.0

Body:
I'm a bit confused when testing Rails controller, whether to test them in isolation(mocking, less DB hits: faster), or in an integration way(no mocking, a lot of DB hits: slower).

Say we have this example:

class ProductsController

  def create
    product = Product.new(product_params)
    if product.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def product_params
    require(:product).permit(:name, :price)
  end

end

RSpec.describe ProductsController do

  describe '#create in isolation' do
    it "pass" do
      params = { name: "name", price: 100}
      mocked_product = double(save: true)
      expect(Product).to receive(:new).with(params).and_return(mocked_product)

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

  describe '#create in integration' do
    it "pass" do
      params = { name: "name", price: 100}

      post :create, params: { product: params }

      expect(response).to be_redirect
    end
  end

end

Testing in isolation doesn't hit the DB which makes it faster, however what if in Product model
we added a description field that is required, where we forget to add it to product_params method, which will
result in Product record not receiving description, and it won't be valid when saved.

Then the first test will pass with no problems, making a false positive that our controller code is okay, where actually
it is not because we have to change product_params method for it to work

The second test will fail because we didn't mock creating the product.

I think this is an open question/topic any way, so I wonder if there is best practices when doing controller tests.

EDIT(generalizing the idea)

I think this can be generalized as it is not limited to controllers but the concept of testing in isolation, the basic idea is the following:

Assume we have a function func(x,y), this function has its own units tests. Then when we have another servive(S) calling func, we will just stub func call as it is tested elsewhere, in order to save time from executing func (especially when it consumes time, like DB hits!)

expect(func).to receive(some_x, some_y).and_return(some_value)

This is the basic idea of testing in isolation.

The problem with this, what if the method signature of func didn't change, however the arguments passed to func from S now will make func throw some exception, due to some implementation changes in func itself, where S is still calling func with the old arguments values, which will result in exception now. And since we mocked calls to func, S test won't catch this error and the code will be deployed successfully.

I believe this is the general pattern


问:
Using reserved instances in an Elastic Beanstalk Load Balancer
I am running an Elastic Beanstalk load-balanced application for a year now. I'm looking for ways to cut back on costs and have discovered I could potentially use reserved ec2 instances instead of the On-Demand instances we are currently using. Currently, my load balancer uses two instances.

I want to make the switch but am unsure about how the process is actually done. I want everything to be crystal clear before doing anything.

From my understanding, if I reserve two of the same type of instance as used in my App, (t2.large with Linux) for the same availability zones (1 in  eu-west1b, another in eu-west1c) I could use these instances for the load balancer. Will the same-type instances I currently have deployed immediately fall under rates of a reserved instance? Will I have to rebuild my environment and and build two new instances that match the reserved ones?

答:
For anyone looking for a bit more certainty than John's (correct) answer, here's the official AWS docs on the subject:

In this scenario, you have a running On-Demand Instance (T2) in your account, for which you're currently paying On-Demand rates. You purchase a Reserved Instance that matches the attributes of your running instance, and the billing benefit is immediately applied. Next, you purchase a Reserved Instance for a C4 instance. You do not have any running instances in your account that match the attributes of this Reserved Instance. In the final step, you launch an instance that matches the attributes of the C4 Reserved Instance, and the billing benefit is immediately applied.

From here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-reserved-instances.html


问:
Build a Wikipedia URL
How can I build a Wiki URL in java language?

Is there any API ready to use?

答:
I am not aware of any such API. However you can make your own factory method:

```<code>    public class WikipediaURLFactory {

    private static final String WIKIPEDIA_BASE_URL = "https://en.wikipedia.org/wiki/";

    public static String createWikiURLString(String search) {
        return WIKIPEDIA_BASE_URL + search;
    }

    public static URL createWikiURL(String search) throws MalformedURLException {
        return new URL(createWikiURLString(search));
    }

    public static Status accessPage (URL url) throws IOException {
        Status status = new Status();
        status.setUrl(url);
        status.setExists(true);

        if (getResponseCode(url) == 404) {
            status.setExists(false);
        }

        return status;
    }

    private static int getResponseCode (URL url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        return connection.getResponseCode();
    }
}
</code>```

Your status class:

```<code>private boolean exists;
    private URL url;

    public Status () {}

    public boolean isExists() {
        return exists;
    }

    public void setExists(boolean exists) {
        this.exists = exists;
    }

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }
</code>```

And here is the main test class:

```<code>public class Main {

    public static void main(String[] args) {

        try {

            // this will return true
            URL url = WikipediaURLFactory.createWikiURL("JavaScript");
            Status status = WikipediaURLFactory.accessPage(url);
            String negation = status.isExists() ? "" : "doesn't";
            System.out.println("The webpage " + url + " " + negation + " exist");

            // this will return false as page JafaScript doesn't exist on wiki
            url = WikipediaURLFactory.createWikiURL("JafaScript");
            status = WikipediaURLFactory.accessPage(url);
            negation = status.isExists() ? "" : "doesn't";
            System.out.println("The webpage " + url + " " + negation + " exist");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
</code>```

You may add other necessary fields in Status class (for example page content) if you need them. This is just an example.

ContentLicense: CC BY-SA 4.0

Title: Build a Wikipedia URL

Body:
I am not aware of any such API. However you can make your own factory method:

    public class WikipediaURLFactory {

    private static final String WIKIPEDIA_BASE_URL = "https://en.wikipedia.org/wiki/";

    public static String createWikiURLString(String search) {
        return WIKIPEDIA_BASE_URL + search;
    }

    public static URL createWikiURL(String search) throws MalformedURLException {
        return new URL(createWikiURLString(search));
    }

    public static Status accessPage (URL url) throws IOException {
        Status status = new Status();
        status.setUrl(url);
        status.setExists(true);

        if (getResponseCode(url) == 404) {
            status.setExists(false);
        }

        return status;
    }

    private static int getResponseCode (URL url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        return connection.getResponseCode();
    }
}

Your status class:

private boolean exists;
    private URL url;

    public Status () {}

    public boolean isExists() {
        return exists;
    }

    public void setExists(boolean exists) {
        this.exists = exists;
    }

    public URL getUrl() {
        return url;
    }

    public void setUrl(URL url) {
        this.url = url;
    }

And here is the main test class:

public class Main {

    public static void main(String[] args) {

        try {

            // this will return true
            URL url = WikipediaURLFactory.createWikiURL("JavaScript");
            Status status = WikipediaURLFactory.accessPage(url);
            String negation = status.isExists() ? "" : "doesn't";
            System.out.println("The webpage " + url + " " + negation + " exist");

            // this will return false as page JafaScript doesn't exist on wiki
            url = WikipediaURLFactory.createWikiURL("JafaScript");
            status = WikipediaURLFactory.accessPage(url);
            negation = status.isExists() ? "" : "doesn't";
            System.out.println("The webpage " + url + " " + negation + " exist");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

You may add other necessary fields in Status class (for example page content) if you need them. This is just an example.


问:
Double quotes converted to box when generating chm from HTML Help Workshop
I am creating documentation through Sphinx and restructured text, then issuing the following commands:

$ make html

$ make htmlhelp.

Once that is complete I use HTML Help Workshop to compile a chm file.

The plain HTML documentation looks good, text looks how I want it to.

However when I open the chm file all double quotes are converted to boxes:

Here's a portion of my restructured text:

```<code>Opening the FTP in Windows File Explorer
""""""""""""""""""""""""""""""""""""""""

To open the FTP in Windows File Explorer (this may need to be done through a network administrator using group policies):

- Open IE
- Go to the *Tools* menu and select *Internet Options*
- Go to the *Advanced* tab
- Check the box "*Enable ftp folder view (Outside of Internet Explorer)*"

Adding a FTP shortcut to Windows File Explorer
""""""""""""""""""""""""""""""""""""""""""""""

You may want to add a shortcut to it either on your desktop or straight under *My Computer* in Windows File Explorer. The File Explorer shortcut is useful as it only requires you to log in when you first access it during your windows session. To do so:

- Open Windows Explorer
- Right-click on "My Computer" in the navigation panel on the left
- Choose "Add new network location"
- Use the wizard to create a new network location for your FTP site
- The FTP site will now show up in My Computer as a network location. You can make shortcuts from there by right-clicking on the connection and choosing "send to" > "desktop (as shortcut)".
</code>```

Entering @quot; displays literally as @quot;

How can I fix the restructured text so that both the html and htmlhelp formats display the double quotes?

答:
The solution: I have Sphinx using a theme called RTD (ReadTheDocs), if you find the theme source code, open the layout.html in any plain text editor.

Found mine here: C:\Python27\Lib\site-packages\sphinx_rtd_theme\layout.html

Find:

```<code>  <meta charset="utf-8">
</code>```

Place conditional logic around it, will omit the utf-8 setting upon building html help:

```<code>  {% if 'htmlhelp' not in builder %}
  <meta charset="utf-8">
  {% endif %}
</code>```

make the htmlhelp, compile the htmlhelp and display, quotes are now displaying correctly:

Body:
I am creating documentation through Sphinx and restructured text, then issuing the following commands:

$ make html

$ make htmlhelp.

Once that is complete I use HTML Help Workshop to compile a chm file.

The plain HTML documentation looks good, text looks how I want it to.

However when I open the chm file all double quotes are converted to boxes:

Here's a portion of my restructured text:

Opening the FTP in Windows File Explorer
""""""""""""""""""""""""""""""""""""""""

To open the FTP in Windows File Explorer (this may need to be done through a network administrator using group policies):

- Open IE
- Go to the *Tools* menu and select *Internet Options*
- Go to the *Advanced* tab
- Check the box "*Enable ftp folder view (Outside of Internet Explorer)*"

Adding a FTP shortcut to Windows File Explorer
""""""""""""""""""""""""""""""""""""""""""""""

You may want to add a shortcut to it either on your desktop or straight under *My Computer* in Windows File Explorer. The File Explorer shortcut is useful as it only requires you to log in when you first access it during your windows session. To do so:

- Open Windows Explorer
- Right-click on "My Computer" in the navigation panel on the left
- Choose "Add new network location"
- Use the wizard to create a new network location for your FTP site
- The FTP site will now show up in My Computer as a network location. You can make shortcuts from there by right-clicking on the connection and choosing "send to" > "desktop (as shortcut)".

Entering @quot; displays literally as @quot;

How can I fix the restructured text so that both the html and htmlhelp formats display the double quotes?

Body:
The solution: I have Sphinx using a theme called RTD (ReadTheDocs), if you find the theme source code, open the layout.html in any plain text editor.

Found mine here: C:\Python27\Lib\site-packages\sphinx_rtd_theme\layout.html

Find:

  <meta charset="utf-8">

Place conditional logic around it, will omit the utf-8 setting upon building html help:

  {% if 'htmlhelp' not in builder %}
  <meta charset="utf-8">
  {% endif %}

make the htmlhelp, compile the htmlhelp and display, quotes are now displaying correctly:


问:
Foreach() and each() running out of memory, chunking not working
I am writing an artisan console command that loops through all the records in a table and regenerates a field on that table.

The field is a hash and is generated as an md5() of a particular string.

Initially my code looked like this:

// Get all recipes
$recipes = Recipe::all();

$hashProgress = $this->output->createProgressBar(count($recipes));

// Loop over each recipe and generate a new hash for it
foreach ($recipes as $recipe)
{
    $hashString = '';

    $hashString .= $recipe->field1;
    $hashString .= $recipe->field2;
    $hashString .= $recipe->field3;
    $hashString .= $recipe->field4;
    $hashString .= $recipe->field5;
    $hashString .= $recipe->field6;
    $hashString .= $recipe->field7;

    $extras1Total = $recipe->extras1->sum('amount');
    $hashString .= $recipe->extras1->reduce(function ($str, $item) use ($extras1Total) {
        return $str . $item->name . ($extras1Total == 0 ? $item->amount : ($item->amount / $extras1Total * 100));
    }, '');

    $extras2Total = $recipe->extras2->sum('amount');
    $hashString .= $recipe->extras2->reduce(function ($str, $item) use ($extras2Total) {
        return $str . $item->name . ($extras2Total == 0 ? $item->amount : ($item->amount / $extras2Total * 100));
    }, '');

    $extras3Total = $recipe->extras3->sum('amount');
    $hashString .= $recipe->extras3->reduce(function ($str, $item) use ($extras3Total) {
        return $str . $item->name . ($extras3Total == 0 ? $item->amount : ($item->amount / $extras3Total * 100));
    }, '');

    $extras4Total = $recipe->extras4->sum('amount');
    $hashString .= $recipe->extras4->reduce(function ($str, $item) use ($extras4Total) {
        return $str . $item->name . ($extras4Total == 0 ? $item->amount : ($item->amount / $extras4Total * 100));
    }, '');

    $recipe->update([
        'hash' => md5($hashString),
    ]);

    $hashProgress->advance();
}

$hashProgress->finish();
$this->info(' Recipe hashes regenerated.');
```

<p>After getting to around 10,000 of 28,000 records it would die with a memory exhausted error:</p>

<blockquote>
  <p>PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes)</p>
</blockquote>

<p>I thought <code>chunk</code>ing this might help:</p>

<pre class="lang-php prettyprint-override"><code>// Get all recipes
$recipes = Recipe::all();

$hashProgress = $this->output->createProgressBar(count($recipes));

// Loop over each recipe and generate a new hash for it
foreach ($recipes->chunk(1000) as $chunk)
{
    foreach ($chunk as $recipe)
    {
        $hashString = '';

        $hashString .= $recipe->field1;
        $hashString .= $recipe->field2;
        $hashString .= $recipe->field3;
        $hashString .= $recipe->field4;
        $hashString .= $recipe->field5;
        $hashString .= $recipe->field6;
        $hashString .= $recipe->field7;

        $extras1Total = $recipe->extras1->sum('amount');
        $hashString .= $recipe->extras1->reduce(function ($str, $item) use ($extras1Total) {
            return $str . $item->name . ($extras1Total == 0 ? $item->amount : ($item->amount / $extras1Total * 100));
        }, '');

        $extras2Total = $recipe->extras2->sum('amount');
        $hashString .= $recipe->extras2->reduce(function ($str, $item) use ($extras2Total) {
            return $str . $item->name . ($extras2Total == 0 ? $item->amount : ($item->amount / $extras2Total * 100));
        }, '');

        $extras3Total = $recipe->extras3->sum('amount');
        $hashString .= $recipe->extras3->reduce(function ($str, $item) use ($extras3Total) {
            return $str . $item->name . ($extras3Total == 0 ? $item->amount : ($item->amount / $extras3Total * 100));
        }, '');

        $extras4Total = $recipe->extras4->sum('amount');
        $hashString .= $recipe->extras4->reduce(function ($str, $item) use ($extras4Total) {
            return $str . $item->name . ($extras4Total == 0 ? $item->amount : ($item->amount / $extras4Total * 100));
        }, '');

        $recipe->update([
            'hash' => md5($hashString),
        ]);

        $hashProgress->advance();
    }
}

$hashProgress->finish();
$this->info(' Recipe hashes regenerated.');
</code>```

But I am still getting a memory exhaustion error.

How can I loop through all these records and achieve what I am after without increasing the memory limit?

答:
The way you're "chunking" is actually consuming more memory than the initial code.

What you're doing is getting all the records at once, storing them in $recipes and then chunking the results by calling the chunk() on the resulted collection.

Instead, you need to call the method with the same name, chunk(), on the underlying Recipe model's query builder and generate hashes chunk by chunk:

```<code>Recipe::chunk(1000, function ($recipies) {
    // Hash generation logic here
});
</code>```

This way, you eliminate having a huge $recipes variable which I'm sure is the bottleneck here. Depending on the available memory, you might need to tweak the chunk size a bit to avoid memory exhaustion.

Also, I'd try to use fewer variables when generating the hash instead of leaving a trail of $extras1Total, extras2Total, ... variables. All of them can be replaced with a $total that will be rewritten over and over. This is micro-optimization though.

P.S. In case of significant database write stress (which is rare with 28k total), you might want considering to do the final updates in one (or few) go(es) instead of doing it per record.

Body:
I am writing an artisan console command that loops through all the records in a table and regenerates a field on that table.

The field is a hash and is generated as an md5() of a particular string.

Initially my code looked like this:

// Get all recipes
$recipes = Recipe::all();

$hashProgress = $this->output->createProgressBar(count($recipes));

// Loop over each recipe and generate a new hash for it
foreach ($recipes as $recipe)
{
    $hashString = '';

    $hashString .= $recipe->field1;
    $hashString .= $recipe->field2;
    $hashString .= $recipe->field3;
    $hashString .= $recipe->field4;
    $hashString .= $recipe->field5;
    $hashString .= $recipe->field6;
    $hashString .= $recipe->field7;

    $extras1Total = $recipe->extras1->sum('amount');
    $hashString .= $recipe->extras1->reduce(function ($str, $item) use ($extras1Total) {
        return $str . $item->name . ($extras1Total == 0 ? $item->amount : ($item->amount / $extras1Total * 100));
    }, '');

    $extras2Total = $recipe->extras2->sum('amount');
    $hashString .= $recipe->extras2->reduce(function ($str, $item) use ($extras2Total) {
        return $str . $item->name . ($extras2Total == 0 ? $item->amount : ($item->amount / $extras2Total * 100));
    }, '');

    $extras3Total = $recipe->extras3->sum('amount');
    $hashString .= $recipe->extras3->reduce(function ($str, $item) use ($extras3Total) {
        return $str . $item->name . ($extras3Total == 0 ? $item->amount : ($item->amount / $extras3Total * 100));
    }, '');

    $extras4Total = $recipe->extras4->sum('amount');
    $hashString .= $recipe->extras4->reduce(function ($str, $item) use ($extras4Total) {
        return $str . $item->name . ($extras4Total == 0 ? $item->amount : ($item->amount / $extras4Total * 100));
    }, '');

    $recipe->update([
        'hash' => md5($hashString),
    ]);

    $hashProgress->advance();
}

$hashProgress->finish();
$this->info(' Recipe hashes regenerated.');

After getting to around 10,000 of 28,000 records it would die with a memory exhausted error:

PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 4096 bytes)

I thought chunking this might help:

// Get all recipes
$recipes = Recipe::all();

$hashProgress = $this->output->createProgressBar(count($recipes));

// Loop over each recipe and generate a new hash for it
foreach ($recipes->chunk(1000) as $chunk)
{
    foreach ($chunk as $recipe)
    {
        $hashString = '';

        $hashString .= $recipe->field1;
        $hashString .= $recipe->field2;
        $hashString .= $recipe->field3;
        $hashString .= $recipe->field4;
        $hashString .= $recipe->field5;
        $hashString .= $recipe->field6;
        $hashString .= $recipe->field7;

        $extras1Total = $recipe->extras1->sum('amount');
        $hashString .= $recipe->extras1->reduce(function ($str, $item) use ($extras1Total) {
            return $str . $item->name . ($extras1Total == 0 ? $item->amount : ($item->amount / $extras1Total * 100));
        }, '');

        $extras2Total = $recipe->extras2->sum('amount');
        $hashString .= $recipe->extras2->reduce(function ($str, $item) use ($extras2Total) {
            return $str . $item->name . ($extras2Total == 0 ? $item->amount : ($item->amount / $extras2Total * 100));
        }, '');

        $extras3Total = $recipe->extras3->sum('amount');
        $hashString .= $recipe->extras3->reduce(function ($str, $item) use ($extras3Total) {
            return $str . $item->name . ($extras3Total == 0 ? $item->amount : ($item->amount / $extras3Total * 100));
        }, '');

        $extras4Total = $recipe->extras4->sum('amount');
        $hashString .= $recipe->extras4->reduce(function ($str, $item) use ($extras4Total) {
            return $str . $item->name . ($extras4Total == 0 ? $item->amount : ($item->amount / $extras4Total * 100));
        }, '');

        $recipe->update([
            'hash' => md5($hashString),
        ]);

        $hashProgress->advance();
    }
}

$hashProgress->finish();
$this->info(' Recipe hashes regenerated.');

But I am still getting a memory exhaustion error.

How can I loop through all these records and achieve what I am after without increasing the memory limit?

Body:
The way you're "chunking" is actually consuming more memory than the initial code.

What you're doing is getting all the records at once, storing them in $recipes and then chunking the results by calling the chunk() on the resulted collection.

Instead, you need to call the method with the same name, chunk(), on the underlying Recipe model's query builder and generate hashes chunk by chunk:

Recipe::chunk(1000, function ($recipies) {
    // Hash generation logic here
});

This way, you eliminate having a huge $recipes variable which I'm sure is the bottleneck here. Depending on the available memory, you might need to tweak the chunk size a bit to avoid memory exhaustion.

Also, I'd try to use fewer variables when generating the hash instead of leaving a trail of $extras1Total, extras2Total, ... variables. All of them can be replaced with a $total that will be rewritten over and over. This is micro-optimization though.

P.S. In case of significant database write stress (which is rare with 28k total), you might want considering to do the final updates in one (or few) go(es) instead of doing it per record.


问:
Amazon device farm - @Tests are not executing in order
I have used @Tests(priority=1) etc,. but tests are not executing in order.

New session is created for every @Test method in amazon device farm.

 Following is the log message [XCUITest] Sending createSession command to WDA

答: AWS Device Farm does not currently support test ordering, this is a know issue and in our backlog.</p>


问:
Delphi Seattle 10, multi-threaded/core performance
I have an application that is 100% Delphi code.  It is a 64 bit windows console application, with a workload manager, and a fixed number of workers.  This is done via creation of threads and each thread is a worker.  The thread does not die, it pulls works from its own queue that the workload manager populates.

This appears to work just fine.

What I am finding, however, is that on a 16 core system I am seeing processing times around 90 minutes (it has 2,000,000+ workloads; and each does database work).  When I added 16 to 32 cores, I saw the performance drop!  There is no database contention.  Essentially, the DB is waiting for things to do.

Each thread has its own DB connection.  Each thread's queries use only that threads connection.

I updated the Delphi MM to use ScaleMM2; which made a big improvement; but I am still at a loss as to why increasing cores reduces performance.

When app has 256 threads, on 32 cores, CPU total use at 80%.
When app has 256 threads, on 16 cores, CPU total use at 100% (which is why I wanted to add cores) -- and it got slower :-(

I have applied as much as the advice as I can understand to the code-base.

ie - Functions not returning strings, using Const for arguments, protecting "shared" data with small critical sections (actually using Multi-read Exclusive Write).  I currently do not assign processor affinity; I was reading conflicting advice on using it .. so I am currently not (would be trival to add, just not there today).

Questions - slanted towards I "think" the issue is around thread contention ...

How do I find confirm thread-contention is the issue?  Are there tools available specifically for this type of contention identification?
How can I determine what is using "heap" and what is not, to further reduce contention there?

Insights, guidance, pointers would be appreciated.

Can provide relevant code areas ... if I knew what was relevant.

```<code>Procedure TXETaskWorkloadExecuterThread.Enqueue(Const Workload: TXETaskWorkload);
Begin
  // protect your own queue
  FWorkloadQueue.Enter;
  FWorkloads.Add(Workload);
  FWorkloadQueue.Leave;
End;

Procedure TXETaskManager.Enqueue(Const Workload: TXETaskWorkload);
Begin
  If FWorkloadCount >= FMaxQueueSize Then Begin
    WaitForEmptyQueue;
    FWorkloadCount := 0;
  End;

  FExecuters[FNextThread].Enqueue(Workload);
  // round-robin the queue
  Inc(FNextThread);
  Inc(FWorkloadCount);
  If FNextThread >= FWorkerThreads Then Begin
    FNextThread := 0;
  End;
End;

Function TXETaskWorkloadExecuterThread.Dequeue(Var Workload: TXETaskWorkload): Boolean;
Begin
  Workload := Nil;
  Result := False;

  FWorkloadQueue.Enter;
  Try
    If FNextWorkload < FWorkloads.Count Then Begin
      Workload := FWorkloads[FNextWorkload];
      Inc(FNextWorkload);
      If Workload Is TXETaskWorkLoadSynchronize Then Begin
        FreeAndNil(Workload);
        Exit;
      End;
      Result := True;
    End Else Begin
      FWorkloads.Clear;
      FNextWorkload := 0;
      FHaveWorkloadInQueue.ResetEvent;
      FEmptyAndFinishedQueue.SetEvent;
    End;
  Finally
    FWorkloadQueue.Leave;
  End;
End;
</code>```

EDIT ---

Thanks for all the comments.  Clarifications.

This system/VM has nothing else on it.  The executable in question is the only thing using the CPU.  Single threaded performance means linear.  I have simply made this a divide/conquer.  If I have 5,000,000 cars to park, and I have 30 drivers with 30 different parking lots.  I can tell each driver to wait for the other drive to finish parking, it will be slower than telling 30 drivers to concurrently park cars.

Profiling in single threaded shows there is nothing that is causing this.  I have seen mention on this board about Delphi and multi-core performance "gotcha's" (mostly related to string handling and LOCK).

The DB essentially is saying that it is bored, and waiting for things to do.  I have checked with a copy of Intels vTune.  Generally speaking, it says ... locks.  But, I cannot find out where.   What I have is pretty simple to my mind, and the current areas for locks are necessary and small.  What I cannot see is locks that might be happening due to other things .. like strings creating a lock, or thread 1 causing some issue on the main process via accessing that data (even though protected via a critical section).

Continuing to research.  Thanks again for the feedback/ideas.

答:
Your Workload Manager is deciding which thread gets which work item. If a given thread blocks (say the work is long, DB latency, etc), you are queuing more items to that thread even though they might not get processed for awhile, if at all.

Typically, work items should be stored in a single shared queue that multiple threads then pull from.  When any given thread is ready, it pulls the next available work item.  For example:

```<code>constructor TXETaskManager.Create;
var
  I: Integer;
begin
  FWorkloadQueue := TCriticalSection.Create;
  FWorkloads := TList<TXETaskWorkload>.Create;
  FEmptyQueue := TEvent.Create(nil, True, True, '');
  FHaveWorkloadInQueue := TEvent.Create(nil, True, False, '');
  FNotFullQueue := TEvent.Create(nil, True, True, '');
  FTermEvent := TEvent.Create(nil, True, False, '');
  ...
  FMaxQueueSize := ...;
  FWorkerThreads := ...;
  for I := 0 to FWorkerThreads-1 do
    FExecuters[I] := TXETaskWorkloadExecuterThread.Create(Self);
end;

destructor TXETaskManager.Destroy;
begin
  for I := 0 to FWorkerThreads-1 do
    FExecuters[I].Terminate;
  FTermEvent.SetEvent;
  for I := 0 to FWorkerThreads-1 do
  begin
    FExecuters[I].WaitFor;
    FExecuters[I].Free;
  end;
  FWorkloadQueue.Free;
  FWorkloads.Free;
  FEmptyQueue.Free;
  FHaveWorkloadInQueue.Free;
  FNotFullQueue.Free;
  FTermEvent.Free;
  ...

  inherited;
end;

procedure TXETaskManager.Enqueue(Const Workload: TXETaskWorkload);
begin
  FWorkloadQueue.Enter;
  try
    while FWorkloads.Count >= FMaxQueueSize do
    begin
      FWorkloadQueue.Leave;
      FNotFullQueue.WaitFor(INFINITE);
      FWorkloadQueue.Enter;
    end;

    FWorkloads.Add(Workload);

    if FWorkloads.Count = 1 then
    begin
      FEmptyQueue.ResetEvent;
      FHaveWorkloadInQueue.SetEvent;
    end;

    if FWorkloads.Count >= FMaxQueueSize then
      FNotFullQueue.ResetEvent;
  finally
    FWorkloadQueue.Leave;
  end;
end;

function TXETaskManager.Dequeue(var Workload: TXETaskWorkload): Boolean;
begin
  Result := False;
  Workload := nil;

  FWorkloadQueue.Enter;
  try
    if FWorkloads.Count > 0 then
    begin
      Workload := FWorkloads[0];
      FWorkloads.Delete(0);
      Result := True;

      if FWorkloads.Count = (FMaxQueueSize-1) then
        FNotFullQueue.SetEvent;

      if FWorkloads.Count = 0 then
      begin
        FHaveWorkloadInQueue.ResetEvent;
        FEmptyQueue.SetEvent;
      end;
    end;
  finally
    FWorkloadQueue.Leave;
  end;
end;

constructor TXETaskWorkloadExecuterThread.Create(ATaskManager: TXETaskManager);
begin
  inherited Create(False);
  FTaskManager := ATaskManager;
end;

procedure TXETaskWorkloadExecuterThread.Execute;
var
  Arr: THandleObjectArray;
  Event: THandleObject;
  Workload: TXETaskWorkload;
begin
  SetLength(Arr, 2);
  Arr[0] := FTaskManager.FHaveWorkloadInQueue;
  Arr[1] := FTaskManager.FTermEvent;

  while not Terminated do
  begin
    case TEvent.WaitForMultiple(Arr, INFINITE, False, Event) of
      wrSignaled:
      begin
        if Event = FTaskManager.FHaveWorkloadInQueue then
        begin
          if FTaskManager.Dequeue(Workload) then
          try
            // process Workload as needed...
          finally
            Workload.Free;
          end;
        end;
      end;
      wrError: begin
        RaiseLastOSError;
      end;
    end;
  end;
end;
</code>```

If you find threads are not getting enough work, you can adjust your thread count as needed. You typically shouldn't be using very many more threads than you have CPU cores available.

Body:
I have an application that is 100% Delphi code.  It is a 64 bit windows console application, with a workload manager, and a fixed number of workers.  This is done via creation of threads and each thread is a worker.  The thread does not die, it pulls works from its own queue that the workload manager populates.

This appears to work just fine.

What I am finding, however, is that on a 16 core system I am seeing processing times around 90 minutes (it has 2,000,000+ workloads; and each does database work).  When I added 16 to 32 cores, I saw the performance drop!  There is no database contention.  Essentially, the DB is waiting for things to do.

Each thread has its own DB connection.  Each thread's queries use only that threads connection.

I updated the Delphi MM to use ScaleMM2; which made a big improvement; but I am still at a loss as to why increasing cores reduces performance.

When app has 256 threads, on 32 cores, CPU total use at 80%.
When app has 256 threads, on 16 cores, CPU total use at 100% (which is why I wanted to add cores) -- and it got slower :-(

I have applied as much as the advice as I can understand to the code-base.

ie - Functions not returning strings, using Const for arguments, protecting "shared" data with small critical sections (actually using Multi-read Exclusive Write).  I currently do not assign processor affinity; I was reading conflicting advice on using it .. so I am currently not (would be trival to add, just not there today).

Questions - slanted towards I "think" the issue is around thread contention ...

How do I find confirm thread-contention is the issue?  Are there tools available specifically for this type of contention identification?
How can I determine what is using "heap" and what is not, to further reduce contention there?

Insights, guidance, pointers would be appreciated.

Can provide relevant code areas ... if I knew what was relevant.

Procedure TXETaskWorkloadExecuterThread.Enqueue(Const Workload: TXETaskWorkload);
Begin
  // protect your own queue
  FWorkloadQueue.Enter;
  FWorkloads.Add(Workload);
  FWorkloadQueue.Leave;
End;

Procedure TXETaskManager.Enqueue(Const Workload: TXETaskWorkload);
Begin
  If FWorkloadCount >= FMaxQueueSize Then Begin
    WaitForEmptyQueue;
    FWorkloadCount := 0;
  End;

  FExecuters[FNextThread].Enqueue(Workload);
  // round-robin the queue
  Inc(FNextThread);
  Inc(FWorkloadCount);
  If FNextThread >= FWorkerThreads Then Begin
    FNextThread := 0;
  End;
End;

Function TXETaskWorkloadExecuterThread.Dequeue(Var Workload: TXETaskWorkload): Boolean;
Begin
  Workload := Nil;
  Result := False;

  FWorkloadQueue.Enter;
  Try
    If FNextWorkload < FWorkloads.Count Then Begin
      Workload := FWorkloads[FNextWorkload];
      Inc(FNextWorkload);
      If Workload Is TXETaskWorkLoadSynchronize Then Begin
        FreeAndNil(Workload);
        Exit;
      End;
      Result := True;
    End Else Begin
      FWorkloads.Clear;
      FNextWorkload := 0;
      FHaveWorkloadInQueue.ResetEvent;
      FEmptyAndFinishedQueue.SetEvent;
    End;
  Finally
    FWorkloadQueue.Leave;
  End;
End;

EDIT ---

Thanks for all the comments.  Clarifications.

This system/VM has nothing else on it.  The executable in question is the only thing using the CPU.  Single threaded performance means linear.  I have simply made this a divide/conquer.  If I have 5,000,000 cars to park, and I have 30 drivers with 30 different parking lots.  I can tell each driver to wait for the other drive to finish parking, it will be slower than telling 30 drivers to concurrently park cars.

Profiling in single threaded shows there is nothing that is causing this.  I have seen mention on this board about Delphi and multi-core performance "gotcha's" (mostly related to string handling and LOCK).

The DB essentially is saying that it is bored, and waiting for things to do.  I have checked with a copy of Intels vTune.  Generally speaking, it says ... locks.  But, I cannot find out where.   What I have is pretty simple to my mind, and the current areas for locks are necessary and small.  What I cannot see is locks that might be happening due to other things .. like strings creating a lock, or thread 1 causing some issue on the main process via accessing that data (even though protected via a critical section).

Continuing to research.  Thanks again for the feedback/ideas.

Body:
Your Workload Manager is deciding which thread gets which work item. If a given thread blocks (say the work is long, DB latency, etc), you are queuing more items to that thread even though they might not get processed for awhile, if at all.

Typically, work items should be stored in a single shared queue that multiple threads then pull from.  When any given thread is ready, it pulls the next available work item.  For example:

constructor TXETaskManager.Create;
var
  I: Integer;
begin
  FWorkloadQueue := TCriticalSection.Create;
  FWorkloads := TList<TXETaskWorkload>.Create;
  FEmptyQueue := TEvent.Create(nil, True, True, '');
  FHaveWorkloadInQueue := TEvent.Create(nil, True, False, '');
  FNotFullQueue := TEvent.Create(nil, True, True, '');
  FTermEvent := TEvent.Create(nil, True, False, '');
  ...
  FMaxQueueSize := ...;
  FWorkerThreads := ...;
  for I := 0 to FWorkerThreads-1 do
    FExecuters[I] := TXETaskWorkloadExecuterThread.Create(Self);
end;

destructor TXETaskManager.Destroy;
begin
  for I := 0 to FWorkerThreads-1 do
    FExecuters[I].Terminate;
  FTermEvent.SetEvent;
  for I := 0 to FWorkerThreads-1 do
  begin
    FExecuters[I].WaitFor;
    FExecuters[I].Free;
  end;
  FWorkloadQueue.Free;
  FWorkloads.Free;
  FEmptyQueue.Free;
  FHaveWorkloadInQueue.Free;
  FNotFullQueue.Free;
  FTermEvent.Free;
  ...

  inherited;
end;

procedure TXETaskManager.Enqueue(Const Workload: TXETaskWorkload);
begin
  FWorkloadQueue.Enter;
  try
    while FWorkloads.Count >= FMaxQueueSize do
    begin
      FWorkloadQueue.Leave;
      FNotFullQueue.WaitFor(INFINITE);
      FWorkloadQueue.Enter;
    end;

    FWorkloads.Add(Workload);

    if FWorkloads.Count = 1 then
    begin
      FEmptyQueue.ResetEvent;
      FHaveWorkloadInQueue.SetEvent;
    end;

    if FWorkloads.Count >= FMaxQueueSize then
      FNotFullQueue.ResetEvent;
  finally
    FWorkloadQueue.Leave;
  end;
end;

function TXETaskManager.Dequeue(var Workload: TXETaskWorkload): Boolean;
begin
  Result := False;
  Workload := nil;

  FWorkloadQueue.Enter;
  try
    if FWorkloads.Count > 0 then
    begin
      Workload := FWorkloads[0];
      FWorkloads.Delete(0);
      Result := True;

      if FWorkloads.Count = (FMaxQueueSize-1) then
        FNotFullQueue.SetEvent;

      if FWorkloads.Count = 0 then
      begin
        FHaveWorkloadInQueue.ResetEvent;
        FEmptyQueue.SetEvent;
      end;
    end;
  finally
    FWorkloadQueue.Leave;
  end;
end;

constructor TXETaskWorkloadExecuterThread.Create(ATaskManager: TXETaskManager);
begin
  inherited Create(False);
  FTaskManager := ATaskManager;
end;

procedure TXETaskWorkloadExecuterThread.Execute;
var
  Arr: THandleObjectArray;
  Event: THandleObject;
  Workload: TXETaskWorkload;
begin
  SetLength(Arr, 2);
  Arr[0] := FTaskManager.FHaveWorkloadInQueue;
  Arr[1] := FTaskManager.FTermEvent;

  while not Terminated do
  begin
    case TEvent.WaitForMultiple(Arr, INFINITE, False, Event) of
      wrSignaled:
      begin
        if Event = FTaskManager.FHaveWorkloadInQueue then
        begin
          if FTaskManager.Dequeue(Workload) then
          try
            // process Workload as needed...
          finally
            Workload.Free;
          end;
        end;
      end;
      wrError: begin
        RaiseLastOSError;
      end;
    end;
  end;
end;

If you find threads are not getting enough work, you can adjust your thread count as needed. You typically shouldn't be using very many more threads than you have CPU cores available.


问:
How do I go about centering my drop-down nav menu?
I’m trying to figure out how to reposition the entire
 element to the center of the screen, yet every time I try a new method the drop-down items get jumbled up by either shifting slightly to the right or they lay on top of one another.

Can someone lend a hand, let me know what I’m doing wrong and give me some tips to make it a bit easier?

Here’s what I’m working with.

html,
body {
  margin: 0px;
  padding: 0px;
}

.menu ul {
  /*This is blank because nothing I tried works*/
}

ul {
  list-style: none;
  font-family: cursive;
  margin: 0;
  padding: 0;
}

ul li {
  float: left;
  display: block;
  height: 50px;
  width: 200px;
  background-color: lightgray;
}

ul li a {
  display: block;
  color: black;
  text-decoration: none;
  line-height: 50px;
  text-align: center;
}

ul li a:hover {
  background-color: lightblue;
}

ul li ul li {
  display: none;
}

ul li:hover ul li {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="style.css" rel="stylesheet" type="text/css">
  <title>Test</title>
</head>

<body>
  <div class="menu">
    <ul>
      <li>About
        <ul>
          <li>About</li>
          <li>About</li>
          <li>About</li>
          <li>About</li>
        </ul>
      </li>
      <li>About
        <ul>
          <li>About</li>
          <li>About</li>
          <li>About</li>
        </ul>
      </li>
      <li>About
        <ul>
          <li>About</li>
          <li>About</li>
        </ul>
      </li>
      <li>About</li>
    </ul>
  </div>
</body>

</html></code>```

答:
```<code>ul {
  display: flex;
  justify-content: center;
}
</code>```

Add this code to your UL tag, it should center the whole thing

Body:
I’m trying to figure out how to reposition the entire
 element to the center of the screen, yet every time I try a new method the drop-down items get jumbled up by either shifting slightly to the right or they lay on top of one another.

Can someone lend a hand, let me know what I’m doing wrong and give me some tips to make it a bit easier?

Here’s what I’m working with.

html,
body {
  margin: 0px;
  padding: 0px;
}

.menu ul {
  /*This is blank because nothing I tried works*/
}

ul {
  list-style: none;
  font-family: cursive;
  margin: 0;
  padding: 0;
}

ul li {
  float: left;
  display: block;
  height: 50px;
  width: 200px;
  background-color: lightgray;
}

ul li a {
  display: block;
  color: black;
  text-decoration: none;
  line-height: 50px;
  text-align: center;
}

ul li a:hover {
  background-color: lightblue;
}

ul li ul li {
  display: none;
}

ul li:hover ul li {
  display: block;
}

<!DOCTYPE html>

  <link href="style.css" rel="stylesheet" type="text/css">
  <title>Test</title>

About

About

About

About

About

About

About

About

About

About

About

About

About

Body:
ul {
  display: flex;
  justify-content: center;
}

Add this code to your UL tag, it should center the whole thing


问:
Peek ahead when iterating an array of arrays in PHP
I have a mysql query object result which I want to parse through. Let's say the array looks like this.

```<code>$superheroes = array(
    [0] => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        "age"=>"33",
        "sex"=>"male",
    ),
    [1] => array(
        "name" => "jLaw",
        "email" => "jlaw@mail.com",
        "age"=>"22",
        "sex"=>"female",
    ),
    [2] => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        "age"=>"36",
        "sex"=>"male",
    ),
    [3] => array(
        "name" => "Gal Gadot",
        "email" => "gal@mail.com",
        "age"=>"22",
        "sex"=>"female",
    )
);
</code>```

I want to iterate through this array, and while I am at each array, I want to look ahead in the next array, and find out the age difference between current male hero and next immediate female in the list. I found a lot of posts that talk about
1. array_keys
2. caching iterators,
3. prev, next, etc.

But all of them are talking about one dimensional arrays. Here Is what I tried

```<code>foreach ($superheroes as $key => $list){
if($list['sex']=="male"){
    $currentHerosAge=$list['age'];
    while($next=next($superheroes)){
        if($next['sex']=="female"){
            $diff=$currentHerosAge -$next['age'];
            echo "Age diff: ".$diff;
            break;
        }
    }
}
</code>```

}

But when I try this, for array[0], next misses the array[1], and picks up array[3]. Not sure how to work this out.

答:
this code works, here's your solution for that situation (i will update explaining why) + editing the Clark - Gal part, one more comparison.

Execute it here if you like. this is a fancy version with echo's just to illustrate the running logic and what is happening inside the loops :) of course the final result can be much more simple.

```<code>     <?php

     $superheroes = [
     [
        "name" = "Peter Parker",
        "email" = "peterparker@mail.com",
        "age"="33",
        "sex"="male",
        ],[
        "name" = "jLaw",
        "email" = "jlaw@mail.com",
        "age"="22",
        "sex"="female",
        ],[
        "name" = "Clark Kent",
        "email" = "clarkkent@mail.com",
        "age"="36",
        "sex"="male",
        ],[
        "name" = "Gal Gadot",
        "email" = "gal@mail.com",
        "age"="22",
        "sex"="female",
    ]
];

     $length = count($superheroes);
     $counterReset = 0;

     while ($current = current($superheroes) )
     {
         $length -= 1;

         if($current['sex']=="male"){
             $currentHerosAge = $current['age'];
             while($next = next($superheroes)){
                 $counterReset += 1;

                 if($next['sex']=="female"){
                     $diff=$currentHerosAge - $next['age'];
                     echo "\n C: ".$current['name']." to ".$next['name']." Age diff: ".$diff."\n";
                     break;
                 }
             }
         }

         if($counterReset  0){
             for($i = 0; $i < $counterReset; $i++){
                 prev($superheroes);
             }
             $counterReset = 0;
         }

         if($length == 0){
             break;
         }
         next($superheroes);
     }
</code>```

current() next() prev() all act as pointers. Which means that every time you call them you control the movement of the assuming "head" of array or element you are calling. For this reason every time you move with next() you must make sure you also return back to the desired position in order to continue looping the regular loop :)

References next(), current(), prev() and reset()

execution logic

You declaration of the array or arrays was bringing a PHP Warning PHP Warning:  Illegal offset type in /home/ on line 21 and was empty. For that reason I re-declared that way.

Body:
I have a mysql query object result which I want to parse through. Let's say the array looks like this.

$superheroes = array(
    [0] => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        "age"=>"33",
        "sex"=>"male",
    ),
    [1] => array(
        "name" => "jLaw",
        "email" => "jlaw@mail.com",
        "age"=>"22",
        "sex"=>"female",
    ),
    [2] => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        "age"=>"36",
        "sex"=>"male",
    ),
    [3] => array(
        "name" => "Gal Gadot",
        "email" => "gal@mail.com",
        "age"=>"22",
        "sex"=>"female",
    )
);

I want to iterate through this array, and while I am at each array, I want to look ahead in the next array, and find out the age difference between current male hero and next immediate female in the list. I found a lot of posts that talk about
1. array_keys
2. caching iterators,
3. prev, next, etc.

But all of them are talking about one dimensional arrays. Here Is what I tried

foreach ($superheroes as $key => $list){
if($list['sex']=="male"){
    $currentHerosAge=$list['age'];
    while($next=next($superheroes)){
        if($next['sex']=="female"){
            $diff=$currentHerosAge -$next['age'];
            echo "Age diff: ".$diff;
            break;
        }
    }
}

}

But when I try this, for array[0], next misses the array[1], and picks up array[3]. Not sure how to work this out.

Body:
this code works, here's your solution for that situation (i will update explaining why) + editing the Clark - Gal part, one more comparison.

Execute it here if you like. this is a fancy version with echo's just to illustrate the running logic and what is happening inside the loops :) of course the final result can be much more simple.

     <?php

     $superheroes = [
     [
        "name" = "Peter Parker",
        "email" = "peterparker@mail.com",
        "age"="33",
        "sex"="male",
        ],[
        "name" = "jLaw",
        "email" = "jlaw@mail.com",
        "age"="22",
        "sex"="female",
        ],[
        "name" = "Clark Kent",
        "email" = "clarkkent@mail.com",
        "age"="36",
        "sex"="male",
        ],[
        "name" = "Gal Gadot",
        "email" = "gal@mail.com",
        "age"="22",
        "sex"="female",
    ]
];

     $length = count($superheroes);
     $counterReset = 0;

     while ($current = current($superheroes) )
     {
         $length -= 1;

         if($current['sex']=="male"){
             $currentHerosAge = $current['age'];
             while($next = next($superheroes)){
                 $counterReset += 1;

                 if($next['sex']=="female"){
                     $diff=$currentHerosAge - $next['age'];
                     echo "\n C: ".$current['name']." to ".$next['name']." Age diff: ".$diff."\n";
                     break;
                 }
             }
         }

         if($counterReset  0){
             for($i = 0; $i < $counterReset; $i++){
                 prev($superheroes);
             }
             $counterReset = 0;
         }

         if($length == 0){
             break;
         }
         next($superheroes);
     }

current() next() prev() all act as pointers. Which means that every time you call them you control the movement of the assuming "head" of array or element you are calling. For this reason every time you move with next() you must make sure you also return back to the desired position in order to continue looping the regular loop :)

References next(), current(), prev() and reset()

execution logic

You declaration of the array or arrays was bringing a PHP Warning PHP Warning:  Illegal offset type in /home/ on line 21 and was empty. For that reason I re-declared that way.


问:
How to use babel with npm package that will be used by react
Trying to do what I thought was a simple thing.

I have a node package that uses advanced js syntax. I want to depend on it in a react project.

So I installed babel packages via --save-dev, and added a .babelrc:

```<code>{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}
</code>```

That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:

```<code>{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },
  "main": "lib/index.js",
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}
</code>```

When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.

Why is this so difficult? What am I doing wrong?

答:
I am not sure I understand the need here correctly, but could you not just run the babel call in prepare or prepublish scripts? That way only local npm install calls would pick that up.

See more about npm scripts lifecycle: https://docs.npmjs.com/misc/scripts

Body:
Trying to do what I thought was a simple thing.

I have a node package that uses advanced js syntax. I want to depend on it in a react project.

So I installed babel packages via --save-dev, and added a .babelrc:

{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}

That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:

{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },
  "main": "lib/index.js",
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}

When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.

Why is this so difficult? What am I doing wrong?


问:
How to simulate position tracking of an iot thing?
I need to simulate the position tracking for my 'IoT thing' in my IoT platform Thingworx. For eg: If I have a car as a Thing, and it has two modes moving and stopped. I need to simulate the changing latitude and longitude for the car when it is in 'moving' state and store the generated coordinates so that they can be later displayed on the Google map widget in the mashup. Similarly, if the car is stopped then it should display the location where it was last stopped. I have the following questions:

How do I achieve this? As in, should I create and use a service or a subscription (with speed values as the trigger)?

What sort of code snippet will be required for such a functionality?

Should I employ the Google api?

Also how do you store the changing values of the lat/long in the variable which has a datatype 'Location'?

Thanks!

答:
What you ask for is not easy to explain in a few words! The best way is to show you an example that uses the Google Map API and may interest you also as it uses CSS transitions to smooth the trip of you car (or Hansel and Gretel in my case).

You can see the fully documented code for the Brotkrumen Web App here. It includes a aaa_readme.txt

Note that knowing when someone has stopped is not straight forward and has to be obtained heuristically. I provide a number of secs parameter that must elapse sans interesting movement-change to work out you've stop and for how long. Try running Brotkrumen in your car and it should work out when you were at the lights (At least in Perth they take forever) and will show you when you press the Map Trip or Replay button.


问:
BASH: Find number in text -> variable
I need little help from the community:

I have these two lines in a large text file:

```<code>Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS
</code>```

How I can find, extract and assign the numbers to variables?

```<code>clients=42
active=4
</code>```

SED, AWK, GREP? Which one should I use?

答:
```<code>str='Connected clients: 42 4 ACTIVE CLIENTS IN LAST 20 SECONDS'

set -- $str
clients=$3
active=$4
</code>```

If it's two lines, fine.

```<code>str1='Connected clients: 42'
str2='4 ACTIVE CLIENTS IN LAST 20 SECONDS'

set -- $str1
clients=$3
set -- $str2
active=$1
</code>```

Reading two lines from a file may be done by

```<code>{ read str1; read str2; } < file
</code>```

Alternately, do the reading and writing in AWK, and slurp the results into Bash.

```<code>eval "$(awk '/^Connected clients: / { print "clients=" $3 }
             /[0-9]+ ACTIVE CLIENTS/ { print "active=" $1 }
            ' filename)"
</code>```

Title: BASH: Find number in text -> variable

Body:
I need little help from the community:

I have these two lines in a large text file:

Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS

How I can find, extract and assign the numbers to variables?

clients=42
active=4

SED, AWK, GREP? Which one should I use?

Body:
str='Connected clients: 42 4 ACTIVE CLIENTS IN LAST 20 SECONDS'

set -- $str
clients=$3
active=$4

If it's two lines, fine.

str1='Connected clients: 42'
str2='4 ACTIVE CLIENTS IN LAST 20 SECONDS'

set -- $str1
clients=$3
set -- $str2
active=$1

Reading two lines from a file may be done by

{ read str1; read str2; } < file

Alternately, do the reading and writing in AWK, and slurp the results into Bash.

eval "$(awk '/^Connected clients: / { print "clients=" $3 }
             /[0-9]+ ACTIVE CLIENTS/ { print "active=" $1 }
            ' filename)"

ContentLicense: CC BY-SA 2.5


问:
Imported Module is undefined Angular4
Very new to Angular so this is probably a setup issue. But I have a module that is undefined when I try and import it into another module and I think it has to do with the order because when I switch it the other module can't be imported.

My tree looks like this

```<code>|-- src/
|   |-- app/
|   |   |-- components/
|   |   |   |-- login/
|   |   |   |   |-- login.compact.component.html
|   |   |   |   |-- login.component.html
|   |   |   |   |-- login.component.ts
|   |   |   |   |-- login.service.ts
|   |   |   |   |-- login.module.ts
|   |   |   |-- ...
|   |   |   |-- components.module.ts
|   |   |-- shared/
|   |   |   |-- header/
|   |   |   |-- footer/
|   |   |   |-- navigation/
|   |   |   |-- shared.module.ts
|   |   |-- app.component.html
|   |   |-- app.component.ts
|   |   |-- app.module.ts
|   |   |-- app.routes.ts
</code>```

I was trying to add a compact version of login to my navigation bar

navigation.component.html

```<code><nav>
   ....
   <mylogin></mylogin>
</nav>
</code>```

But when I add the LoginModule to the imports of the SharedModule I get this errror Unexpected value 'undefined' imported by the module 'LoginModule'

In my app.module.ts I have

```<code>import {SharedModule} from './shared/shared.module';

import {ComponentsModule} from './components/components.module';
....
@NgModule({
declarations: [
    AppComponent,
],
imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    SharedModule,
    ComponentsModule,
    BsDropdownModule.forRoot(),
    RouterModule.forRoot(
        APP_ROUTES,
        {enableTracing: true})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

Is this a bad way to structure the app? Or is it wrong to try and import login into the shared module to use in navigation?

答:
First of all, I don't know how you have imported the LoginModule into SharedModule as you haven't provided the SharedModule.

Secondly, if you wish to import one module into another module. You need to add exports: [] with all the declarations that you want to import to the other module. Here's an example:

Module A

```<code>@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    CapitalizePipe,
    SentenceCasePipe,
    FirstNamePipe,
  ],
  exports: [
    CapitalizePipe,
    SentenceCasePipe,
    FirstNamePipe,
  ]
})
export class PipesModule {
}
</code>```

Module B that imports Module A

```<code>@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    PipesModule,
    NgbModule,
    RouterModule,
    AppRoutingModule
  ],
  declarations: [],
  providers: []
})
export class HomeModule {
}
</code>```

As you can see, the PipesModule from module A is imported into module B by adding all the declarations in the exports: []; which allows them to be able to load on to different modules on demand.

FYI

Adding things to the AppModule will result in all of those things to be loaded into the browser DOM on application load. That means if you add modules that are only used in one component; this can result in your application's load time to extend as it needs to all the modules.

So my advice to you is to plan your app as much nested style as possible with incremental module loading, making your app loads faster and smoother. An example would be:

```<code>AppModule
AppComponent
   | PublicModule
   | PublicComponent
         | LoginModule
         | LoginComponnet
                | HomeModule
                | HomeComponent
</code>```

Title: Imported Module is undefined Angular4

Body:
Very new to Angular so this is probably a setup issue. But I have a module that is undefined when I try and import it into another module and I think it has to do with the order because when I switch it the other module can't be imported.

My tree looks like this

|-- src/
|   |-- app/
|   |   |-- components/
|   |   |   |-- login/
|   |   |   |   |-- login.compact.component.html
|   |   |   |   |-- login.component.html
|   |   |   |   |-- login.component.ts
|   |   |   |   |-- login.service.ts
|   |   |   |   |-- login.module.ts
|   |   |   |-- ...
|   |   |   |-- components.module.ts
|   |   |-- shared/
|   |   |   |-- header/
|   |   |   |-- footer/
|   |   |   |-- navigation/
|   |   |   |-- shared.module.ts
|   |   |-- app.component.html
|   |   |-- app.component.ts
|   |   |-- app.module.ts
|   |   |-- app.routes.ts

I was trying to add a compact version of login to my navigation bar

navigation.component.html

   ....
   <mylogin></mylogin>

But when I add the LoginModule to the imports of the SharedModule I get this errror Unexpected value 'undefined' imported by the module 'LoginModule'

In my app.module.ts I have

import {SharedModule} from './shared/shared.module';

import {ComponentsModule} from './components/components.module';
....
@NgModule({
declarations: [
    AppComponent,
],
imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    SharedModule,
    ComponentsModule,
    BsDropdownModule.forRoot(),
    RouterModule.forRoot(
        APP_ROUTES,
        {enableTracing: true})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}

Is this a bad way to structure the app? Or is it wrong to try and import login into the shared module to use in navigation?

Body:
First of all, I don't know how you have imported the LoginModule into SharedModule as you haven't provided the SharedModule.

Secondly, if you wish to import one module into another module. You need to add exports: [] with all the declarations that you want to import to the other module. Here's an example:

Module A

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    CapitalizePipe,
    SentenceCasePipe,
    FirstNamePipe,
  ],
  exports: [
    CapitalizePipe,
    SentenceCasePipe,
    FirstNamePipe,
  ]
})
export class PipesModule {
}

Module B that imports Module A

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    PipesModule,
    NgbModule,
    RouterModule,
    AppRoutingModule
  ],
  declarations: [],
  providers: []
})
export class HomeModule {
}

As you can see, the PipesModule from module A is imported into module B by adding all the declarations in the exports: []; which allows them to be able to load on to different modules on demand.

FYI

Adding things to the AppModule will result in all of those things to be loaded into the browser DOM on application load. That means if you add modules that are only used in one component; this can result in your application's load time to extend as it needs to all the modules.

So my advice to you is to plan your app as much nested style as possible with incremental module loading, making your app loads faster and smoother. An example would be:

AppModule
AppComponent
   | PublicModule
   | PublicComponent
         | LoginModule
         | LoginComponnet
                | HomeModule
                | HomeComponent


问:
How to search string values in GraphQL
How do you query using GraphQL in a manor similar to SQL's like operator?

Example: What users have a first name starting with jason?

select * from users where first_name like "jason%"

答:
Not sure if this is relevant to you because you want it to start with "jason" (ie would return "jason bourne" but not "bourne jason") but I recently came across a way to query GraphQL in a "%Like%" manner.  For your use case it would look something like this:

```<code>export const allUsersQuery = `
  query allUsers($UserName: String!){
    allUsers(
      filter: {first_name_contains: $UserName}
    ) {
      id
      first_name
      ...INSERT_OTHER_FIELDS_HERE...
    }
  }
`;
</code>```

FWIW: I did this using a GraphCool BAAS.  I don't think you were using GraphCool because GraphCool doesn't allow "_" in variable names.

Hope this helps someone down the line :)

Title: How to search string values in GraphQL

Body:
Not sure if this is relevant to you because you want it to start with "jason" (ie would return "jason bourne" but not "bourne jason") but I recently came across a way to query GraphQL in a "%Like%" manner.  For your use case it would look something like this:

export const allUsersQuery = `
  query allUsers($UserName: String!){
    allUsers(
      filter: {first_name_contains: $UserName}
    ) {
      id
      first_name
      ...INSERT_OTHER_FIELDS_HERE...
    }
  }
`;

FWIW: I did this using a GraphCool BAAS.  I don't think you were using GraphCool because GraphCool doesn't allow "_" in variable names.

Hope this helps someone down the line :)


问:
pdflayer API post request saying I didnt not provide api_key even though it did
I am currently trying to work with the API from http://www.pdflayer.com, however I am having issues with providing the api_key through a post request with Axios.

My code looks like this:

var config = require('./../config');
var axios = require('axios');
var fs = require('fs');

const BASE_URL = 'http://api.pdflayer.com/api/convert';

module.exports = {

    createQuotePdf() {
        var data = {
            document_url: 'https://www.apple.com',
            access_key: config.pdflayer_acccess_key,
            page_size: 'A4',
            test: '1'
         }

        axios.post(BASE_URL, data)
        .then((data) => {
            console.log(data);
            fs.writeFile('./download.pdf', data.body, function(err) {
                if (err) console.log('error: ', err);
            })
        });
    }

};```

However, every time I make the request, it is saying that I did not provide the api key, even though I specified.

It would be great if someone could help me.

Best regards

答:
Have you tried appending it directly to your BASE_URL since that seams to be the way they are building it

BASE_URL = ('http://api.pdflayer.com/api/convert?access_key=', YOUR_ACCES_KEY)'

Body:
I am currently trying to work with the API from http://www.pdflayer.com, however I am having issues with providing the api_key through a post request with Axios.

My code looks like this:

var config = require('./../config');
var axios = require('axios');
var fs = require('fs');

const BASE_URL = 'http://api.pdflayer.com/api/convert';

module.exports = {

    createQuotePdf() {
        var data = {
            document_url: 'https://www.apple.com',
            access_key: config.pdflayer_acccess_key,
            page_size: 'A4',
            test: '1'
         }

        axios.post(BASE_URL, data)
        .then((data) => {
            console.log(data);
            fs.writeFile('./download.pdf', data.body, function(err) {
                if (err) console.log('error: ', err);
            })
        });
    }

};

However, every time I make the request, it is saying that I did not provide the api key, even though I specified.

It would be great if someone could help me.

Best regards


问:
Specify display mode of one2many field in an OpenERP form view
there is a field one2many...when i tried to open the view of
 that field it shows tree view but i want the form view..and want to disable the tree view.

is there any solution?

答:
On a one2many field, you can specify which display modes to use for the child view. The developer book gives a brief description of the mode attribute, and you can find an example on the Partner view's address field:

```<code><record id="view_partner_form" model="ir.ui.view">
    <field name="name">res.partner.form</field>
    <field name="model">res.partner</field>
    <field name="type">form</field>
    <field name="arch" type="xml">
        <form string="Partners">
            <group colspan="4" col="6">
                ...
            </group>
            <notebook colspan="4">
                <page string="General">
                    <field
                        colspan="4"
                        mode="form,tree"
                        name="address"
                        nolabel="1"
                        select="1">
                        <form string="Partner Contacts">
                            <field name="name" select="2"/>
                            <field name="function"/>
                            <field name="type" select="2"/>
                            ...
</code>```

This example is from server/bin/addons/base/res/partner/partner_view.xml. It sounds like you want to use mode="form" for your field.

Body:
On a one2many field, you can specify which display modes to use for the child view. The developer book gives a brief description of the mode attribute, and you can find an example on the Partner view's address field:

<record id="view_partner_form" model="ir.ui.view">
    <field name="name">res.partner.form</field>
    <field name="model">res.partner</field>
    <field name="type">form</field>
    <field name="arch" type="xml">
        <form string="Partners">
            <group colspan="4" col="6">
                ...
            </group>
            <notebook colspan="4">
                <page string="General">
                    <field
                        colspan="4"
                        mode="form,tree"
                        name="address"
                        nolabel="1"
                        select="1">
                        <form string="Partner Contacts">
                            <field name="name" select="2"/>
                            <field name="function"/>
                            <field name="type" select="2"/>
                            ...

This example is from server/bin/addons/base/res/partner/partner_view.xml. It sounds like you want to use mode="form" for your field.


问:
Android Studio Webservice call "HTTP request failed, HTTP status: 401" Unauthorized
i try to connect my Android application to a Webservice.
I wrote a new class and defined some Variables:

I´ve got the Async Class to use the Network

```<code>class GetValueTask extends AsyncTask<ApiConnector,Long,String> {
    @Override
    protected String doInBackground(ApiConnector... params) {
        //wird im Background Thread ausgeführt
        return  params[0].getValue();

    }

    @Override
    protected void onPostExecute(String s) {
        //wird im Mainthread ausgeführt
        MainActivity.this.setText(s);
    }
}
</code>```

And I have a Class where i want to call the Webservice

```<code>public class ApiConnector
{
    private static final String SOAP_ACTION ="urn:microsoft-dynamics-schemas/codeunit/AddService:Add";
    private static final String METHOD_NAME ="Add";
    private static final String NAMESPACE ="urn:microsoft-dynamics-schemas/codeunit/AddService";
    private static final String URL ="http://192.168.0.154:9047/DynamicsNAV80/WS/CRONUS%20AG/Codeunit/AddService";
    private static final String USERNAME="B.Denger";
    private static final String PASSWORD ="TestPW123!";

    public String getValue() {

        SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
        request.addProperty("no","10");

        PropertyInfo unamePI = new PropertyInfo();
        PropertyInfo passPI = new PropertyInfo();
        // Set Username
        unamePI.setName("username");
        // Set Value
        unamePI.setValue(USERNAME);
        // Set dataType
        unamePI.setType(String.class);
        // Add the property to request object
        request.addProperty(unamePI);
        //Set Password
        passPI.setName("password");
        //Set dataType
        passPI.setValue(PASSWORD);
        //Set dataType
        passPI.setType(String.class);
        //Add the property to request object
        request.addProperty(passPI);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);

        soapEnvelope.setOutputSoapObject(request);

        HttpTransportSE aht= new HttpTransportSE(URL);

        try {
            aht.call(SOAP_ACTION, soapEnvelope);
            SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
            return resultString.toString();
        }catch(Exception e ) {
            e.printStackTrace();
            return "Fail at Call";
        }
    }
}
</code>```

I have set the using-permission in the Manifest file

```<code><uses-permission android:name="android.permission.INTERNET"/>
</code>```

in my MainActivity do i execute the AsynkTask with a Button

```<code> btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GetValueTask getValueTask = new GetValueTask();
            getValueTask.execute(new ApiConnector());
        }
    });
</code>```

after execution i get following Logcat entry:

```<code>W/System.err﹕ org.ksoap2.transport.HttpResponseException: HTTP request failed, HTTP status: 401
</code>```

i googled a whole Day for it, but i did not solved the problem yet.
is there anybody who could help me, or could give me a hint where i have to search?

答:
In my case I fixed same problem by adding this code:

```<code>List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
</code>```

Complete task:

```<code>private class fnAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params)
        {
            //for linear parameter
            SoapObject loRequest = new SoapObject(sNAMESPACE, sMETHOD_NAME);
            // adding method property here serially
//            loRequest.addProperty("CountryName", "france");

            SoapSerializationEnvelope loEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            loEnvelope.implicitTypes = true;
            loEnvelope.setOutputSoapObject(loRequest);
            loEnvelope.dotNet = true;

            HttpTransportSE loHttpTransport = new HttpTransportSE(_sURL);
            loHttpTransport.debug = true;
            try
            {
                List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
                llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
                loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
            }
            catch (HttpResponseException e)
            {
                // TODO Auto-generated catch block
                Log.e("HTTPLOG", e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.e("IOLOG", e.getMessage());
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                Log.e("XMLLOG", e.getMessage());
                e.printStackTrace();
            } //send request

            Object result = null;
            try {
                result = (Object )loEnvelope.getResponse();
                //See output in the console
                Log.i("RESPONSE",String.valueOf(result));
            } catch (SoapFault e) {
                // TODO Auto-generated catch block
                Log.e("SOAPLOG", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }
    }
</code>```

Full example
http://www.nascenia.com/consuming-soap-web-services-from-android/

Body:
i try to connect my Android application to a Webservice.
I wrote a new class and defined some Variables:

I´ve got the Async Class to use the Network

class GetValueTask extends AsyncTask<ApiConnector,Long,String> {
    @Override
    protected String doInBackground(ApiConnector... params) {
        //wird im Background Thread ausgeführt
        return  params[0].getValue();

    }

    @Override
    protected void onPostExecute(String s) {
        //wird im Mainthread ausgeführt
        MainActivity.this.setText(s);
    }
}

And I have a Class where i want to call the Webservice

public class ApiConnector
{
    private static final String SOAP_ACTION ="urn:microsoft-dynamics-schemas/codeunit/AddService:Add";
    private static final String METHOD_NAME ="Add";
    private static final String NAMESPACE ="urn:microsoft-dynamics-schemas/codeunit/AddService";
    private static final String URL ="http://192.168.0.154:9047/DynamicsNAV80/WS/CRONUS%20AG/Codeunit/AddService";
    private static final String USERNAME="B.Denger";
    private static final String PASSWORD ="TestPW123!";

    public String getValue() {

        SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
        request.addProperty("no","10");

        PropertyInfo unamePI = new PropertyInfo();
        PropertyInfo passPI = new PropertyInfo();
        // Set Username
        unamePI.setName("username");
        // Set Value
        unamePI.setValue(USERNAME);
        // Set dataType
        unamePI.setType(String.class);
        // Add the property to request object
        request.addProperty(unamePI);
        //Set Password
        passPI.setName("password");
        //Set dataType
        passPI.setValue(PASSWORD);
        //Set dataType
        passPI.setType(String.class);
        //Add the property to request object
        request.addProperty(passPI);

        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);

        soapEnvelope.setOutputSoapObject(request);

        HttpTransportSE aht= new HttpTransportSE(URL);

        try {
            aht.call(SOAP_ACTION, soapEnvelope);
            SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
            return resultString.toString();
        }catch(Exception e ) {
            e.printStackTrace();
            return "Fail at Call";
        }
    }
}

I have set the using-permission in the Manifest file

<uses-permission android:name="android.permission.INTERNET"/>

in my MainActivity do i execute the AsynkTask with a Button

 btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GetValueTask getValueTask = new GetValueTask();
            getValueTask.execute(new ApiConnector());
        }
    });

after execution i get following Logcat entry:

W/System.err﹕ org.ksoap2.transport.HttpResponseException: HTTP request failed, HTTP status: 401

i googled a whole Day for it, but i did not solved the problem yet.
is there anybody who could help me, or could give me a hint where i have to search?

Body:
In my case I fixed same problem by adding this code:

List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);

Complete task:

private class fnAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params)
        {
            //for linear parameter
            SoapObject loRequest = new SoapObject(sNAMESPACE, sMETHOD_NAME);
            // adding method property here serially
//            loRequest.addProperty("CountryName", "france");

            SoapSerializationEnvelope loEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            loEnvelope.implicitTypes = true;
            loEnvelope.setOutputSoapObject(loRequest);
            loEnvelope.dotNet = true;

            HttpTransportSE loHttpTransport = new HttpTransportSE(_sURL);
            loHttpTransport.debug = true;
            try
            {
                List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
                llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
                loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
            }
            catch (HttpResponseException e)
            {
                // TODO Auto-generated catch block
                Log.e("HTTPLOG", e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.e("IOLOG", e.getMessage());
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                Log.e("XMLLOG", e.getMessage());
                e.printStackTrace();
            } //send request

            Object result = null;
            try {
                result = (Object )loEnvelope.getResponse();
                //See output in the console
                Log.i("RESPONSE",String.valueOf(result));
            } catch (SoapFault e) {
                // TODO Auto-generated catch block
                Log.e("SOAPLOG", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }
    }

Full example
http://www.nascenia.com/consuming-soap-web-services-from-android/


问:
Telerik RadToolTipManager Tooltip position incorrect in Chrome
I am using telerik RadToolTipManager control to show tooltip on html controls.(anchor tag, span label etc.) as below in my .ascx page in asp.net

```<code><telerik:RadToolTipManager OnClientBeforeShow="BeforeShow_Tootip" ID="BVAutoRadToolTipManager" runat="server" ToolTipZoneID="tooltipZoneDiv" Position="TopRight" HideDelay="500" AutoCloseDelay="10000" Skin="Vista" AutoTooltipify="True">
        </telerik:RadToolTipManager>
</code>```

above code is working fine in IE and FF and display tootip at TopRight as I set Position="TopRight" in markup.

Issue: Now, when I open my page in Chrome it show tooltip on correct position on page load first time. but when I Scroll the page down then the tool tip position is far above the mouse pointer.

Can you please give me a suggestions that Is there any way to set the position correct when user hover the element. How can we set position Using OnClientBeforeShow event of RadToolTipManager.

Thanks

Any help will be very much appreciated ..!!

答:
This was reported as a bug (Wrong placement (position) of RadToolTip in Chrome 61). Workaround is to override the _getPosRelativeToMouse method.

This Js code should fix the issue.

```<code>Telerik.Web.UI.RadToolTip.prototype._getPosRelativeToMouse = function (targetBounds) {
    var elemX = targetBounds.x;
    var elemY = targetBounds.y;

    //Get last recorded mouse position
    var pos = this._getMousePosition();
    var mouseX = pos.clientX;
    var mouseY = pos.clientY;

    //Take into consideration the offsetScroll!
    var standard = $telerik.standardsMode;
    //$telerik.standardsMode does not do a good job! Extra check is needed for FF!!
    //And yet another check needed for Safari! It should always be set to false in order to get the calculations right
    if (!$telerik.isIE && document.compatMode != "CSS1Compat") standard = false;
    else if ($telerik.isSafari && !(Telerik.Web.Browser.chrome && Telerik.Web.Browser.version >= 61)) standard = false;

    if (standard) {
        elemX -= $telerik.getCorrectScrollLeft(document.documentElement);
        elemY -= document.documentElement.scrollTop;
    }
    else //NEW: Add support for quircksmode
    {
        elemX -= $telerik.getCorrectScrollLeft(document.body);
        elemY -= document.body.scrollTop;
    }

    //Calculate the position of the mouse, relative to the targetcontrol
    var deltaX = mouseX - elemX;
    var deltaY = mouseY - elemY;

    return { x: deltaX, y: deltaY };
}
</code>```

Body:
I am using telerik RadToolTipManager control to show tooltip on html controls.(anchor tag, span label etc.) as below in my .ascx page in asp.net

<telerik:RadToolTipManager OnClientBeforeShow="BeforeShow_Tootip" ID="BVAutoRadToolTipManager" runat="server" ToolTipZoneID="tooltipZoneDiv" Position="TopRight" HideDelay="500" AutoCloseDelay="10000" Skin="Vista" AutoTooltipify="True">
        </telerik:RadToolTipManager>

above code is working fine in IE and FF and display tootip at TopRight as I set Position="TopRight" in markup.

Issue: Now, when I open my page in Chrome it show tooltip on correct position on page load first time. but when I Scroll the page down then the tool tip position is far above the mouse pointer.

Can you please give me a suggestions that Is there any way to set the position correct when user hover the element. How can we set position Using OnClientBeforeShow event of RadToolTipManager.

Thanks

Any help will be very much appreciated ..!!

Body:
This was reported as a bug (Wrong placement (position) of RadToolTip in Chrome 61). Workaround is to override the _getPosRelativeToMouse method.

This Js code should fix the issue.

Telerik.Web.UI.RadToolTip.prototype._getPosRelativeToMouse = function (targetBounds) {
    var elemX = targetBounds.x;
    var elemY = targetBounds.y;

    //Get last recorded mouse position
    var pos = this._getMousePosition();
    var mouseX = pos.clientX;
    var mouseY = pos.clientY;

    //Take into consideration the offsetScroll!
    var standard = $telerik.standardsMode;
    //$telerik.standardsMode does not do a good job! Extra check is needed for FF!!
    //And yet another check needed for Safari! It should always be set to false in order to get the calculations right
    if (!$telerik.isIE && document.compatMode != "CSS1Compat") standard = false;
    else if ($telerik.isSafari && !(Telerik.Web.Browser.chrome && Telerik.Web.Browser.version >= 61)) standard = false;

    if (standard) {
        elemX -= $telerik.getCorrectScrollLeft(document.documentElement);
        elemY -= document.documentElement.scrollTop;
    }
    else //NEW: Add support for quircksmode
    {
        elemX -= $telerik.getCorrectScrollLeft(document.body);
        elemY -= document.body.scrollTop;
    }

    //Calculate the position of the mouse, relative to the targetcontrol
    var deltaX = mouseX - elemX;
    var deltaY = mouseY - elemY;

    return { x: deltaX, y: deltaY };
}