问:
File system path for images
I'm writing a custom helper that extends HtmlHelper and overriding the \HtmlHelper::image() method to calculate the image dimensions and add them as HTML attributes. What I have so far works fine for regular pictures:

```<code>public function image($path, $options = array()) {
    if (!array_key_exists('width', $options) && !array_key_exists('height', $options)) {
        $stamp = Configure::read('Asset.timestamp');
        Configure::write('Asset.timestamp', false);

        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        list($width, $height) = @getimagesize(rtrim(WWW_ROOT, '\\/') . $path);
        if (!is_null($width)) {
            $options['width'] = $width;
        }
        if (!is_null($height)) {
            $options['height'] = $height;
        }

        Configure::write('Asset.timestamp', $stamp);
    }
    return parent::image($path, $options);
}
</code>```

… but has these flaws:

Pictures from plug-ins can't be located on disk (and they should), e.g.:

```<code>echo $this->Html->image('/debug_kit/img/cake.icon.png', array('alt' => 'CakePHP'));
</code>```

… produces this file system path:

```<code>…\src\webroot/debug_kit/img/cake.icon.png
</code>```

… thus getimagesize() fails because actual location is:

```<code>…\src\Plugin\DebugKit\webroot\img\cake.icon.png"
</code>```

External pictures (which should be ignored) go through the full process:

```<code>echo $this->Html->image('http://placekitten.com/200/300');
…\src\webroothttp://placekitten.com/200/300
</code>```

I've been looking for a builtin method to convert a CakePHP picture URL (in any format accepted by \HtmlHelper::image() into a file system path (o something like null when doesn't apply) but I couldn't find any. Native features that need a disk path, such as \Helper::assetTimestamp() are wrapped in tons of non-reusable code.

Is there an elegant solution?

答:
I'd say that there are pretty much only 3 options:

Submit a patch to add asset filesystem path retrieval functionality to the core.

Copy a lot of code from the helper (assetUrl(), webroot(), and assetTimestamp()).

Use web requests for local URLs (ideally combined with caching).

Title: File system path for images

Body:
I'm writing a custom helper that extends HtmlHelper and overriding the \HtmlHelper::image() method to calculate the image dimensions and add them as HTML attributes. What I have so far works fine for regular pictures:

public function image($path, $options = array()) {
    if (!array_key_exists('width', $options) && !array_key_exists('height', $options)) {
        $stamp = Configure::read('Asset.timestamp');
        Configure::write('Asset.timestamp', false);

        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        list($width, $height) = @getimagesize(rtrim(WWW_ROOT, '\\/') . $path);
        if (!is_null($width)) {
            $options['width'] = $width;
        }
        if (!is_null($height)) {
            $options['height'] = $height;
        }

        Configure::write('Asset.timestamp', $stamp);
    }
    return parent::image($path, $options);
}

… but has these flaws:

Pictures from plug-ins can't be located on disk (and they should), e.g.:

echo $this->Html->image('/debug_kit/img/cake.icon.png', array('alt' => 'CakePHP'));

… produces this file system path:

…\src\webroot/debug_kit/img/cake.icon.png

… thus getimagesize() fails because actual location is:

…\src\Plugin\DebugKit\webroot\img\cake.icon.png"

External pictures (which should be ignored) go through the full process:

echo $this->Html->image('http://placekitten.com/200/300');
…\src\webroothttp://placekitten.com/200/300

I've been looking for a builtin method to convert a CakePHP picture URL (in any format accepted by \HtmlHelper::image() into a file system path (o something like null when doesn't apply) but I couldn't find any. Native features that need a disk path, such as \Helper::assetTimestamp() are wrapped in tons of non-reusable code.

Is there an elegant solution?


来源: stackexchange

问:
Entity - what type are two join tables
I need to bring the data from two join tables. What type will be the dataset? Do I need to create a class that contains the properties from these two tables to use for the dataset type or I can use the types from the Entity mode. How can I modify my method to work properly? </p>

```<code>public static IEnumerable<Result> GetCarrier()
{
    IEnumerable <Result> result = new IEnumerable<>();
    try
    {
        using (MyEntities myEntity = new MyEntities())
        {
            var result = from s in Carriers car
                     CoreEnt ent ON car.CoreEntID equals ent.CoreEntID
                     where car.NeedsTransfer == True
                     select s;
        }
        return result;
    }
    catch (Exception ex)
    {
        return result;
    }
}
</code>```

答:
The linq query can be as follows.</p>

```<code>try
    {

        using (MyEntities myEntity = new MyEntities())
        {
            var result = (from s in Carriers
                         join ent in CoreEnt on s.CoreEntID equals ent.CoreEntID
                         where s.NeedsTransfer == True
                         select s).Single();
            //using Single()/FirstOrDefault() depends on what is the type of other objects. If it shows error to you than you can remove it
        }
        return result;
    }
    catch (Exception ex)
    {
        return result;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Entity - what type are two join tables

Body:
I need to bring the data from two join tables. What type will be the dataset? Do I need to create a class that contains the properties from these two tables to use for the dataset type or I can use the types from the Entity mode. How can I modify my method to work properly?

public static IEnumerable<Result> GetCarrier()
{
    IEnumerable <Result> result = new IEnumerable<>();
    try
    {
        using (MyEntities myEntity = new MyEntities())
        {
            var result = from s in Carriers car
                     CoreEnt ent ON car.CoreEntID equals ent.CoreEntID
                     where car.NeedsTransfer == True
                     select s;
        }
        return result;
    }
    catch (Exception ex)
    {
        return result;
    }
}

Body:
The linq query can be as follows.

try
    {

        using (MyEntities myEntity = new MyEntities())
        {
            var result = (from s in Carriers
                         join ent in CoreEnt on s.CoreEntID equals ent.CoreEntID
                         where s.NeedsTransfer == True
                         select s).Single();
            //using Single()/FirstOrDefault() depends on what is the type of other objects. If it shows error to you than you can remove it
        }
        return result;
    }
    catch (Exception ex)
    {
        return result;
    }


问:
Could not find a method onClick(View) in the activity class TintContextWrapper for onClick if using themes
I'm getting the Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton exception recently after adding the ability to select a dark or light theme for my app.

I do set the theme in the manifest and then I use following BaseActivity:

```<code>public abstract class BaseActivity extends AppCompatActivity
{
    private final int mLightTheme;
    private final int mDarkTheme;

    public BaseActivity(int lightTheme, int darkTheme)
    {
        mLightTheme = lightTheme;
        mDarkTheme = darkTheme;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(MainApp.getPrefs().darkTheme() ? mDarkTheme : mLightTheme);
        super.onCreate(savedInstanceState);
    }
}
</code>```

Any ideas what else could cause this issue? I got the issue from a device running 4.2.2...

NOT working solutions

similar issues suggest to remove the theme tag from the xml file => I'm not using it in my xml, so this is not the case for me

Stacktrace

```<code>java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'btBack'
    at android.view.View$1.onClick(View.java:3602)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    ... 11 more
    java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Change android.support.v7.widget.AppCompatButton to Button.

It will work for u.

Other way.

You can use setOnClickListener in Your Activity for Click event.

Body:
I'm getting the Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton exception recently after adding the ability to select a dark or light theme for my app.

I do set the theme in the manifest and then I use following BaseActivity:

public abstract class BaseActivity extends AppCompatActivity
{
    private final int mLightTheme;
    private final int mDarkTheme;

    public BaseActivity(int lightTheme, int darkTheme)
    {
        mLightTheme = lightTheme;
        mDarkTheme = darkTheme;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(MainApp.getPrefs().darkTheme() ? mDarkTheme : mLightTheme);
        super.onCreate(savedInstanceState);
    }
}

Any ideas what else could cause this issue? I got the issue from a device running 4.2.2...

NOT working solutions

similar issues suggest to remove the theme tag from the xml file => I'm not using it in my xml, so this is not the case for me

Stacktrace

java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'btBack'
    at android.view.View$1.onClick(View.java:3602)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    ... 11 more
    java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)


问:
Maven node skipping Spring Boot deployment artefact on Jelastic
I'm using the new Jelastic Spring Boot node which seems to work great if you upload a packaged Spring Boot jar.

However using the Maven build nodes to build and deploy from Github directly just gives the following;

```<code>[INFO] --- jelastic-maven-plugin:1.8:deploy (default-cli) @ <app> ---
[INFO] Skiping deploy artifact. Artifact packaging not WAR or EAR
[INFO] ----------------------------------------------------------------------

[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.514 s
</code>```

The documentation indicates this should work, any ideas where I might be going wrong?

I do notice that the jelastic-maven-plugin being used is 1.8 while in the maven repo there is a version 1.8.1 released more recently. Might this remove the offending WAR check? In which case this would be an issue with my Jelastic provider?

答:
you are right, the was a bug in maven plugin version 1.8, it is already fixed in version 1.8.1, but it looks like the configuration that is globally set in a platform that you are using is configured to use older version of maven plugin, if you let us know the hosting service provider name where you faced with this issue - we will help to resolve this problem very quickly.
Thank you for reporting this. </p>

Body:
I'm using the new Jelastic Spring Boot node which seems to work great if you upload a packaged Spring Boot jar.

However using the Maven build nodes to build and deploy from Github directly just gives the following;

[INFO] --- jelastic-maven-plugin:1.8:deploy (default-cli) @ <app> ---
[INFO] Skiping deploy artifact. Artifact packaging not WAR or EAR
[INFO] ----------------------------------------------------------------------

[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.514 s

The documentation indicates this should work, any ideas where I might be going wrong?

I do notice that the jelastic-maven-plugin being used is 1.8 while in the maven repo there is a version 1.8.1 released more recently. Might this remove the offending WAR check? In which case this would be an issue with my Jelastic provider?


问:
JS change image if/else
Im trying to change image when function ends. In IF image should change, and in else, image stays the same.

html

```<code>    <img class="owner" id="regina" src="img/uk-profile.jpg" alt="Great Britain">
  <p class="fort"><b>Fort: </b><span  id="wall">1000</span></p>
</code>```

What i have tried in JS

```<code>function finish(){
    var f = document.getElementById('wall');

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile";

    }

     else {
        alert("Battle has been lost!");

     }
}
</code>```

答:
When you use

```<code>var f = document.getElementById('wall');
</code>```

In f you have the element not the value of the element, do the following: use .innerHTML to get the value and convert it to int, then you can check if (f > -1)

```<code>var f = parseInt(document.getElementById('wall').innerHTML);
</code>```

function finish() {
  var f = parseInt(document.getElementById('wall').innerHTML);
  if (f > -1) {
    alert("Battle has been won, you now control the region!");
    var g = document.getElementById('regina').src = "http://www.newseum.org/wp-content/uploads/2015/02/xwinner.jpg.pagespeed.ic.iQ7m1XtFLg.jpg";

  } else {
    alert("Battle has been lost!");

  }
}

finish();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="owner" id="regina" src="img/uk-profile.jpg" alt="Great Britain">
<p class="fort"><b>Fort: </b><span id="wall">1000</span></p></code>```

Title: JS change image if/else

Body:
Im trying to change image when function ends. In IF image should change, and in else, image stays the same.

html

Fort: 1000

What i have tried in JS

function finish(){
    var f = document.getElementById('wall');

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile";

    }

     else {
        alert("Battle has been lost!");

     }
}

Body:
When you use

var f = document.getElementById('wall');

In f you have the element not the value of the element, do the following: use .innerHTML to get the value and convert it to int, then you can check if (f > -1)

var f = parseInt(document.getElementById('wall').innerHTML);

function finish() {
  var f = parseInt(document.getElementById('wall').innerHTML);
  if (f > -1) {
    alert("Battle has been won, you now control the region!");
    var g = document.getElementById('regina').src = "http://www.newseum.org/wp-content/uploads/2015/02/xwinner.jpg.pagespeed.ic.iQ7m1XtFLg.jpg";

  } else {
    alert("Battle has been lost!");

  }
}

finish();

<img class="owner" id="regina" src="img/uk-profile.jpg" alt="Great Britain">
<p class="fort"><b>Fort: </b><span id="wall">1000</span></p>


问:
Abstract class and unique pointer
I have the following error in my code:

error: allocating an object of abstract class type 'Material'

I don't know how to handle this case.

I'm aware that std::make_unique performs an allocation, so it can't allocate the object of type Material, but I don't know how to correct it.

```<code>#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  }
private:
  std::unique_ptr<Material> mat1_;
  std::unique_ptr<Material> mat2_;
};

int main()
{
  auto mix = Mix(Basic(), Basic());
  std::cout << mix.get_color() << '\n';
}
</code>```

答:
You can use a templated constructor to arrange for constructing the right types without needing a clone method:

```<code>#include <iostream>
#include <memory>

struct Material {
    Material() = default;
    virtual int get_color() const = 0;
};

struct Basic : Material {
    Basic() = default;
    int get_color() const override {
        return 1;
    }
};

struct Mix : Material {
    template<typename M1, typename M2>
    Mix(const M1& mat1, const M2& mat2)
        : mat1_{std::make_unique<M1>(std::move(mat1))}
        , mat2_{std::make_unique<M2>(std::move(mat2))}
    {}

    int get_color() const override {
        return mat1_->get_color() + mat2_->get_color();
    }

private:
    std::unique_ptr<Material> mat1_;
    std::unique_ptr<Material> mat2_;
};

int main() {
    auto mix = Mix(Basic(), Basic());
    std::cout << mix.get_color() << '\n';
}
</code>```

Note that this works only if you send instance of a material with a known type.

Title: Abstract class and unique pointer

Body:
I have the following error in my code:

error: allocating an object of abstract class type 'Material'

I don't know how to handle this case.

I'm aware that std::make_unique performs an allocation, so it can't allocate the object of type Material, but I don't know how to correct it.

#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  }
private:
  std::unique_ptr<Material> mat1_;
  std::unique_ptr<Material> mat2_;
};

int main()
{
  auto mix = Mix(Basic(), Basic());
  std::cout << mix.get_color() << '\n';
}

Body:
You can use a templated constructor to arrange for constructing the right types without needing a clone method:

#include <iostream>
#include <memory>

struct Material {
    Material() = default;
    virtual int get_color() const = 0;
};

struct Basic : Material {
    Basic() = default;
    int get_color() const override {
        return 1;
    }
};

struct Mix : Material {
    template<typename M1, typename M2>
    Mix(const M1& mat1, const M2& mat2)
        : mat1_{std::make_unique<M1>(std::move(mat1))}
        , mat2_{std::make_unique<M2>(std::move(mat2))}
    {}

    int get_color() const override {
        return mat1_->get_color() + mat2_->get_color();
    }

private:
    std::unique_ptr<Material> mat1_;
    std::unique_ptr<Material> mat2_;
};

int main() {
    auto mix = Mix(Basic(), Basic());
    std::cout << mix.get_color() << '\n';
}

Note that this works only if you send instance of a material with a known type.

ContentLicense: CC BY-SA 4.0


问:
Odoo 8 - add event handler on input text in javascript
is there a way to add an event handler which handles an onchange event on input text. I need to put constraint on the invoice line where the user shouldn't fill a quantity greater than the value in the text box.

```<code><field name="quantity" event="onchange(this)"/>

onchange(){
console.log..
}
</code>```

10x

答:
For your task you don't need to use js, use python code for this, you can use @api.onchange and throw warnings or you can also create db constrains from there. db constrains works only when saving while @api.onchange works during editing

And if you still want to use js and cause headaches you can use jQuery to set onchange on any fields like this

```<code>$(SELECTOR).change(function (e) {});
</code>```

Body:
is there a way to add an event handler which handles an onchange event on input text. I need to put constraint on the invoice line where the user shouldn't fill a quantity greater than the value in the text box.

<field name="quantity" event="onchange(this)"/>

onchange(){
console.log..
}

10x

Body:
For your task you don't need to use js, use python code for this, you can use @api.onchange and throw warnings or you can also create db constrains from there. db constrains works only when saving while @api.onchange works during editing

And if you still want to use js and cause headaches you can use jQuery to set onchange on any fields like this

$(SELECTOR).change(function (e) {});


问:
Retrieving Image From Firebase
The app run successfully , but the image did not show up in the table cell.</p>

```<code>let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            let pic = UIImage(data: data!)
            self.picArray.append(pic!)

        }
        self.tableViewHongKong.reloadData()
    })
</code>```

答:
Even if Callam already answered your question, I am still posting this since it is probably better way for doing it.

Instead of writing all that code just to display one image, you can use Glide which works very well with Firebase plus it is well documented in Firebase Docs. Check it out, it made everything a lot easier for me when I started using it.

https://firebase.google.com/docs/storage/android/download-files#downloading_images_with_firebaseui

Title: Retrieving Image From Firebase

Body:
The app run successfully , but the image did not show up in the table cell.

let dbRef = FIRDatabase.database().reference().child("restaurants/restaurantImage")
    dbRef.observe(.childAdded, with: {(snapshot) in
        let downloadURL = snapshot.value as! String
        let storageRef = FIRStorage.storage().reference(forURL: downloadURL)
        storageRef.data(withMaxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            let pic = UIImage(data: data!)
            self.picArray.append(pic!)

        }
        self.tableViewHongKong.reloadData()
    })


问:
awk to create html table adds space at the end of each data entry
I am using below code for creating html table from an input file which works perfectly fine, However while creating the html table it adds a space to each entry to a cell. How do I avoid getting space at the end?

```<code>awk 'BEGIN{print "<tr>";print "<th>NAME</th>";print "<th>POLICY</th>";print "<th>STATUS</th>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}' /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y') >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y').html]
</code>```

now in the input file entries are going through script as echo "$x $y $z" >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y')

Let me know how can i avoid spaces at the end of each data entry to a cell.

Input File

```<code>cat /tmp/t
    Cindy   Today   Standard
    Victor  Today   Standard
    Bob     Today   Standard
    Martha  Tomorrow    Oracle
    Sam     Tomorrow    Oracle
</code>```

Guys the problem with my code was it had

 and 	 with a new line each time which added an extra unnecessary space to the final sheet cell>

Before the output was:
Thanks @karakfa, It did the trick, the issue in my code was every  was with new line, meaning it will append a space in the actual data.

Simply the difference in final output from before and after is
Before:

```<code></tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
<tr>
<td>data1</td>
<td>data2</td>
<td>data3</td>
</tr>
</code>```

After:

```<code><tr><td>data1</td><td>data2</td><td>data3</td></tr>
<tr><td>data1</td><td>data2</td><td>data3</td></tr>
</code>```

答:
Your question doesn't include enough information to replicate the problem you're having, so the best we can do at this point is guess, and suggest better ways to do the stuff that you have included.

What about building your output using printf formatting? Using formatting will allow you to control your output much more precisely.

```<code>awk '
  BEGIN {
    printf "<table>\n"
    printf "<tr>\n <th>NAME</th> <th>POLICY</th> <th>STATUS</th>\n</tr>"
    fmtrow="<tr>\n%s</tr>"
    fmttd="\t<td>%s</td>\n"
  }
  {
    data=""
    for (i=1; i<=NF; i++) data=data sprintf(fmttd, $i)
    printf fmtrow, data
  }
  END {
    printf "\n</table>\n"
  }
'
</code>```

This implements the same functionality you had in your original script, with the for loop stepping through columns to build each row. If you know you'll only have three columns, you can simplify things:

```<code>awk '
  BEGIN {
    printf "<table>\n"
    printf "<tr>\n\t<th>NAME</th>\n\t<th>POLICY</th>\n\t<th>STATUS</th>\n</tr>"
    fmtrow="<tr>\n\t<td>%s</td>\n\t<td>%s</td>\n\t<td>%s</td>\n</tr>"
  }
  {
    printf fmtrow, $1, $2, $3
  }
  END {
    printf "\n</table>\n"
  }
'
</code>```

Bear in mind that this just recycles your input, it doesn't clean it. If the source data file has been edited on a Microsoft Windows machine, it might have Ctrl-M characters added to the end of each line, which awk would simply treat as part of the last field.

Body:
I am using below code for creating html table from an input file which works perfectly fine, However while creating the html table it adds a space to each entry to a cell. How do I avoid getting space at the end?

awk 'BEGIN{print "
";print "NAME	";print "POLICY	";print "STATUS	"} {print "
";for(i=1;i<=NF;i++)print "" $i"	";print "
"} END{print "
"}' /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y') >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y').html]

now in the input file entries are going through script as echo "$x $y $z" >> /tmp/output/Report_$(date -d '-1 day' '+%d-%b-%Y')

Let me know how can i avoid spaces at the end of each data entry to a cell.

Input File

cat /tmp/t
    Cindy   Today   Standard
    Victor  Today   Standard
    Bob     Today   Standard
    Martha  Tomorrow    Oracle
    Sam     Tomorrow    Oracle

Guys the problem with my code was it had

 and 	 with a new line each time which added an extra unnecessary space to the final sheet cell>

Before the output was:
Thanks @karakfa, It did the trick, the issue in my code was every  was with new line, meaning it will append a space in the actual data.

Simply the difference in final output from before and after is
Before:

data1
data2
data3

data1
data2
data3

After:

data1	data2	data3

data1	data2	data3

Body:
Your question doesn't include enough information to replicate the problem you're having, so the best we can do at this point is guess, and suggest better ways to do the stuff that you have included.

What about building your output using printf formatting? Using formatting will allow you to control your output much more precisely.

awk '
  BEGIN {
    printf "<table>\n"
    printf "<tr>\n <th>NAME</th> <th>POLICY</th> <th>STATUS</th>\n</tr>"
    fmtrow="<tr>\n%s</tr>"
    fmttd="\t<td>%s</td>\n"
  }
  {
    data=""
    for (i=1; i<=NF; i++) data=data sprintf(fmttd, $i)
    printf fmtrow, data
  }
  END {
    printf "\n</table>\n"
  }
'

This implements the same functionality you had in your original script, with the for loop stepping through columns to build each row. If you know you'll only have three columns, you can simplify things:

awk '
  BEGIN {
    printf "<table>\n"
    printf "<tr>\n\t<th>NAME</th>\n\t<th>POLICY</th>\n\t<th>STATUS</th>\n</tr>"
    fmtrow="<tr>\n\t<td>%s</td>\n\t<td>%s</td>\n\t<td>%s</td>\n</tr>"
  }
  {
    printf fmtrow, $1, $2, $3
  }
  END {
    printf "\n</table>\n"
  }
'

Bear in mind that this just recycles your input, it doesn't clean it. If the source data file has been edited on a Microsoft Windows machine, it might have Ctrl-M characters added to the end of each line, which awk would simply treat as part of the last field.


问:
how to make indexes and different unique indexes in Morphia Java?
Using morphia, mongoDB and JAVA 8, I'm trying to make some indexes on my entity, and some other unique indexes on different properties.
Lets say I want fields "a" and "b" be a regular indexes @Indexes({@Index(fields= {@Field("a"), @Field("b")})}).
but how I add other index field with options = @IndexOptions(unique = true) ?

Thanks

答:
You can try something like below.

```<code>@Indexes({@Index(fields= {@Field("a"), @Field("b")}), @Index(options= @IndexOptions(unique = true), fields= {@Field("c")})})
@Entity(collection_name)
public class IndexClass {

        @Id
        private Long id;
        private String a;
        private String b;
        private String c;

     // Getters and Setters

}
</code>```

Start up code:

```<code>Morphia morphia = new Morphia();
morphia.map(IndexClass.class);
MongoClient client = new MongoClient();
Datastore datastore = morphia.createDatastore(client, db_name);
datastore.ensureIndexes();
</code>```

Body:
You can try something like below.

@Indexes({@Index(fields= {@Field("a"), @Field("b")}), @Index(options= @IndexOptions(unique = true), fields= {@Field("c")})})
@Entity(collection_name)
public class IndexClass {

        @Id
        private Long id;
        private String a;
        private String b;
        private String c;

     // Getters and Setters

}

Start up code:

Morphia morphia = new Morphia();
morphia.map(IndexClass.class);
MongoClient client = new MongoClient();
Datastore datastore = morphia.createDatastore(client, db_name);
datastore.ensureIndexes();


问:
How to specify legend position in matplotlib in graph coordinates
I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

How to put the legend out of the plot

However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?

Edit: A small example is here:

```<code>import numpy as n
f, axarr = plt.subplots(2,sharex=True)
axarr[1].set_ylim([0.611,0.675])
axarr[0].set_ylim([0.792,0.856])
axarr[0].plot([0, 0.04, 0.08],n.array([ 0.83333333,  0.82250521,0.81109048]), label='test1')
axarr[0].errorbar([0, 0.04, 0.08],n.array([ 0.8,  0.83,   0.82]),n.array([0.1,0.1,0.01]), label='test2')
axarr[1].plot([0, 0.04, 0.08],n.array([ 0.66666667,  0.64888304,  0.63042428]))
axarr[1].errorbar([0, 0.04, 0.08],n.array([ 0.67,  0.64,  0.62]),n.array([ 0.01,  0.05,  0.1]))
axarr[0].legend(bbox_to_anchor=(0.04, 0.82, 1., .102),labelspacing=0.1,       handlelength=0.1, handletextpad=0.1,frameon=False, ncol=4, columnspacing=0.7)
</code>```

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?

答:
The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is  loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.

Therefore, when specifying bbox_to_anchor, always specify loc as well.

The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

```<code>import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()
plt.show()
</code>```

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .

If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

```<code>ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)
</code>```

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.

Body:
I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

How to put the legend out of the plot

However, I'd like to use the coordinates of my x- and y-axis in the graph to specify the legend position (inside the plot), as I might need to move the figure into a large figure with a different axis environment, and I don't want to manually play around with those coordinates every time I do this. Is this possible?

Edit: A small example is here:

import numpy as n
f, axarr = plt.subplots(2,sharex=True)
axarr[1].set_ylim([0.611,0.675])
axarr[0].set_ylim([0.792,0.856])
axarr[0].plot([0, 0.04, 0.08],n.array([ 0.83333333,  0.82250521,0.81109048]), label='test1')
axarr[0].errorbar([0, 0.04, 0.08],n.array([ 0.8,  0.83,   0.82]),n.array([0.1,0.1,0.01]), label='test2')
axarr[1].plot([0, 0.04, 0.08],n.array([ 0.66666667,  0.64888304,  0.63042428]))
axarr[1].errorbar([0, 0.04, 0.08],n.array([ 0.67,  0.64,  0.62]),n.array([ 0.01,  0.05,  0.1]))
axarr[0].legend(bbox_to_anchor=(0.04, 0.82, 1., .102),labelspacing=0.1,       handlelength=0.1, handletextpad=0.1,frameon=False, ncol=4, columnspacing=0.7)

I think what confuses me is that the legend does not actually start at 0.82, and indeed for my larger plot (with 5 subplots of this type), I need to use legend coordinates bbox_to_anchor=(0.04, 1.15, 1., .102) in order to make the legend appear on coordinates (0.02, 0.83). But maybe I am getting something else wrong?

Body:
The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is  loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.

Therefore, when specifying bbox_to_anchor, always specify loc as well.

The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()
plt.show()

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .

If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.


问:
CPAN/gem-like repository for Objective-C and Cocoa?
Is there any centralized repository of useful Objective-C / Cocoa libraries as there is for Perl, Ruby, Python, etc.?

In building my first iPhone app, I'm finding myself implementing some very basic functions that would be just a quick "gem install" away in Ruby.

答: There's a new index of reusable code for Mac OS and iOS: Cocoa Objects</p>

OwnerDisplayName: Robert Sanders

LastEditorDisplayName: Paul

ContentLicense: CC BY-SA 2.5


问:
oracles implementation with smart contracts
I am trying to deploy a smart contract to a private Blockchain which uses oraclizeAPI.sol library code.
Basically the smart contract is a small implementation of oraclize.

The import does not work, either with the github link or with local import, solc compilation fails because of import.

Both of the below does not work, the contract is not getting properly compiled by solc

```<code>1.import "oraclizeAPI.sol";

2.import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";
</code>```

So, next approch i took was to copy the code of oraclizeAPI.sol, directly into the contract code file.
Now the contract gets compiled properly but the i am falling shot on gas every time, while deploying.

Error:

```<code>The contract couldn't be stored, please check your gas amount.
</code>```

Now here are the details of the Blockchain.

genesis.json

```<code>  {
        "nonce": "0x0000000000000042",
        "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "difficulty": "0x4000",
        "alloc": {
            "84840c340067c75806273d2524dfbae646a7c68f":
            { "balance": "1606938044258990275541962092341162602522202993782792835301376" }
        },
            "config": {
            "chainId": 15,
            "homesteadBlock": 0,
            "eip155Block": 0,
            "eip158Block": 0
        },
        "coinbase": "0x84840c340067c75806273d2524dfbae646a7c68f",
        "timestamp": "0x00",
        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "gasLimit": "0x8000000000000000"
    }
</code>```

I am currently trying to deply the contract using the coinbase id.

```<code>web3.eth.getBlock("latest").gasLimit
132661998547049420

web3.eth.getBalance('0x84840c340067c75806273d2524dfbae646a7c68f').e
60
</code>```

contract code:

```<code>contract oraclizeExample is usingOraclize {

    string public data;

    event newOraclizeQuery(string description);
    event newData(string data);
    event eventC(string data);

    function oraclizeExample() payable {
        update();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        data = result;
        newData(result);
        //return result;
    }

    function eventCheck(string dataFClient) returns (string) {
        eventC(dataFClient);
        return dataFClient;
    }

    function update() payable returns (string) {
        newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query("URL", "json(https://jewel-api.herokuapp.com/jewel/58d89d264d59a000110829bb).invoice_num");
        return "update function was called!";
    }

}
</code>```

The code of contract creation.

```<code>var ContractABI = web3.eth.contract(JSON.parse(interface));
var SaveContract = ContractABI.new(
    {
        from: account,
        data: bytecode,
        gas: '93048696279858031'
    }, function (e, contract) {
        if(e){
            console.log(e, contract);
            return;
        }

        if (typeof contract.address !== 'undefined') {
            console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
            fs.writeFileSync('./contracts_data/'+ contract_name + '_final', 'Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash)
            return;
        }

    });
</code>```

If you want to check the complete contract code with the and the way i am doing this please got to this link.

https://github.com/utkarsh17ife/oraclizeExample/tree/master/contracts_data

Or the complete implementation with node as well:

https://github.com/utkarsh17ife/oraclizeExample

And yes i am able to mine other contract using this setup.

Comment if you need further info on this.

答: If you are using a private chain you must run the ethereum-bridge, you are getting a throw because your smart contract invokes the oraclize_query function on deployment (constructor function) but no Oraclize contracts were found on your chain.</p>

Body:
I am trying to deploy a smart contract to a private Blockchain which uses oraclizeAPI.sol library code.
Basically the smart contract is a small implementation of oraclize.

The import does not work, either with the github link or with local import, solc compilation fails because of import.

Both of the below does not work, the contract is not getting properly compiled by solc

1.import "oraclizeAPI.sol";

2.import "github.com/oraclize/ethereum-api/oraclizeAPI.sol";

So, next approch i took was to copy the code of oraclizeAPI.sol, directly into the contract code file.
Now the contract gets compiled properly but the i am falling shot on gas every time, while deploying.

Error:

The contract couldn't be stored, please check your gas amount.

Now here are the details of the Blockchain.

genesis.json

  {
        "nonce": "0x0000000000000042",
        "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "difficulty": "0x4000",
        "alloc": {
            "84840c340067c75806273d2524dfbae646a7c68f":
            { "balance": "1606938044258990275541962092341162602522202993782792835301376" }
        },
            "config": {
            "chainId": 15,
            "homesteadBlock": 0,
            "eip155Block": 0,
            "eip158Block": 0
        },
        "coinbase": "0x84840c340067c75806273d2524dfbae646a7c68f",
        "timestamp": "0x00",
        "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
        "gasLimit": "0x8000000000000000"
    }

I am currently trying to deply the contract using the coinbase id.

web3.eth.getBlock("latest").gasLimit
132661998547049420

web3.eth.getBalance('0x84840c340067c75806273d2524dfbae646a7c68f').e
60

contract code:

contract oraclizeExample is usingOraclize {

    string public data;

    event newOraclizeQuery(string description);
    event newData(string data);
    event eventC(string data);

    function oraclizeExample() payable {
        update();
    }

    function __callback(bytes32 myid, string result) {
        if (msg.sender != oraclize_cbAddress()) throw;
        data = result;
        newData(result);
        //return result;
    }

    function eventCheck(string dataFClient) returns (string) {
        eventC(dataFClient);
        return dataFClient;
    }

    function update() payable returns (string) {
        newOraclizeQuery("Oraclize query was sent, standing by for the answer..");
        oraclize_query("URL", "json(https://jewel-api.herokuapp.com/jewel/58d89d264d59a000110829bb).invoice_num");
        return "update function was called!";
    }

}

The code of contract creation.

var ContractABI = web3.eth.contract(JSON.parse(interface));
var SaveContract = ContractABI.new(
    {
        from: account,
        data: bytecode,
        gas: '93048696279858031'
    }, function (e, contract) {
        if(e){
            console.log(e, contract);
            return;
        }

        if (typeof contract.address !== 'undefined') {
            console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
            fs.writeFileSync('./contracts_data/'+ contract_name + '_final', 'Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash)
            return;
        }

    });

If you want to check the complete contract code with the and the way i am doing this please got to this link.

https://github.com/utkarsh17ife/oraclizeExample/tree/master/contracts_data

Or the complete implementation with node as well:

https://github.com/utkarsh17ife/oraclizeExample

And yes i am able to mine other contract using this setup.

Comment if you need further info on this.


问:
How do cells work in Buck?
I understand that there is an undocumented feature in buck called cells. There are some tests that demonstrate how they work, but is there any more written information about them?

How do cells work in Buck?

答:
Have a look at this example repo.

What Problem Does Cells Solve?

Cells are a great fit for this situtation:

You have a library in a repo that builds with Buck

You want to use that library in your project

You copy the library into your project but the library's BUCK files don't work, because the root (//) has changed to the root of your project

You don't want to rewrite your library's BUCK files!

Cells allow us to create isolated sub-projects that have their own .buckconfig and their own Buck target heirarchy. Cells can use targets from other cells when those targets are exported.

How Does it Work?

The meat of the example is in .buckconfig:

```<code>[repositories]
  neither = vendor/neither
</code>```

The repositories tag tells Buck where each cell lives in your project's folder structure. Each cell has an alias. Here we have neither = vendor/neither, which means the subfolder vendor/neither is a cell with the name neither.

We can refer to targets inside of a cell using this syntax: cell-name//:target-in-cell.

So to make our example target depend on LoopPerfect/neither:

```<code>deps = [
  'neither//:neither',
],
</code>```

This is a really powerful feature, because it makes a library's BUCK files portable. All you need to do to expose a target inside of a cell is to make it public:

```<code>visibility = [
  'PUBLIC',
]
</code>```

Title: How do cells work in Buck?

Body:
Have a look at this example repo.

What Problem Does Cells Solve?

Cells are a great fit for this situtation:

You have a library in a repo that builds with Buck

You want to use that library in your project

You copy the library into your project but the library's BUCK files don't work, because the root (//) has changed to the root of your project

You don't want to rewrite your library's BUCK files!

Cells allow us to create isolated sub-projects that have their own .buckconfig and their own Buck target heirarchy. Cells can use targets from other cells when those targets are exported.

How Does it Work?

The meat of the example is in .buckconfig:

[repositories]
  neither = vendor/neither

The repositories tag tells Buck where each cell lives in your project's folder structure. Each cell has an alias. Here we have neither = vendor/neither, which means the subfolder vendor/neither is a cell with the name neither.

We can refer to targets inside of a cell using this syntax: cell-name//:target-in-cell.

So to make our example target depend on LoopPerfect/neither:

deps = [
  'neither//:neither',
],

This is a really powerful feature, because it makes a library's BUCK files portable. All you need to do to expose a target inside of a cell is to make it public:

visibility = [
  'PUBLIC',
]


问:
Docker - Unable to locate package docker-engine
I am trying to install docker in Ubuntu 16.04. I am following this link for docker installation. I am ending up with Unable to locate package docker-engine

My current kernal version - 4.4.0-38-generic
Ubuntu version - 16.04

答: The main solution which solved most of the issues in docker is installing 64-bit version of ubuntu. I was running with 32-bit(i686). Hope it helps ! !</p>


问:
Detected a case where constraints ambiguously suggest a height of zero
After updating to Xcode 6.1 beta 2 when I run my app that contains tableview cells, the debug assistant says:

```<code>Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.
</code>```

Before, when I used Xcode 5 on this project, I would get a few errors but those have gone away since I upgraded. I have no other errors or warnings now. I have already tried adjusting the sizes of all the tableview cells and also tried using standard height but I still get the same warning:

```<code>Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.
</code>```

I have also read through all similar topics on this but none of their solutions help. When I test the app with the simulator, the app runs fine except the pictures that are supposed to be in the tableView cells aren't there.

答: I had this problem when my labels and views in the custom tableViewCell were constrained to the customCell, not its Content View. When I cleared the constraints and connected them to cells Content View the problem was solved. </p>

Body:
After updating to Xcode 6.1 beta 2 when I run my app that contains tableview cells, the debug assistant says:

Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.

Before, when I used Xcode 5 on this project, I would get a few errors but those have gone away since I upgraded. I have no other errors or warnings now. I have already tried adjusting the sizes of all the tableview cells and also tried using standard height but I still get the same warning:

Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.

I have also read through all similar topics on this but none of their solutions help. When I test the app with the simulator, the app runs fine except the pictures that are supposed to be in the tableView cells aren't there.


问:
How to make Toolbar transparent?
It is self Q&A post
I have transparent ActionBar which overlays layout. After migration to the latest support library I have been forced to get rid off the ActionBar in favor of the Toolbar. The old ways to make it transparent and overlay that layout doesn't work anymore.

```<code><style name="CustomActionBarTheme" parent="@android:style/Theme.AppCompat">
    <item name="android:windowActionBarOverlay">true</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="android:actionBarStyle">@style/TransparentActionBar</item>
</style>

<style name="TransparentActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@android:color/transparent</item>
</style>
</code>```

答:
Just add android:background="@android:color/transparent"  like below in your appbar layout

```<code><android.support.design.widget.AppBarLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@android:color/transparent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>`
</code>```

Title: How to make Toolbar transparent?

Body:
Just add android:background="@android:color/transparent"  like below in your appbar layout

<android.support.design.widget.AppBarLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@android:color/transparent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>`


问:
create a data frame with a function
i have a data.frame with many values and calculations. One of the values is the wind speed. What i did is to calculate different energies from changing wind speeds. I did it manually and built the data frame row by row just like the following:

```<code>zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
         "A_rotor (m^2)")

zz$V2 <- c("2",  # wind_speed
         "1.2",      # density
         "0.00482", # Cd
         "112",     # d_rotor
         "")

zz$V3[1] <- "" # v_in
zz$V3[2] <- "" # density
zz$V3[3] <- "" # Cd
zz$V3[4] <- "" # d_rotor
zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor
</code>```

This is just an excerpt of my data.frame, but i hope you can see my intention.
What i now want is to create always the same data frame with changing parameters, e.g. the wind speed (let's say 3 and 4 m/s).
And it would be also cool to change more than one value at the same time (let's say wind speed 5 and density 1 or wind speed 6 and density 2).
I tried to solve this problem with a function but it did not work. It only gave me a single value but not the complete data frame.

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)

make_speed <- function(x)

{
  zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

  zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
           "A_rotor (m^2)")

  zz$V2 <- c("speed_vector[x]",  # v_in
           "1.2",      # density
           "0.00482", # Cd
           "112",     # d_rotor
           "")

  zz$V3[1] <- "" # v_in
  zz$V3[2] <- "" # density
  zz$V3[3] <- "" # Cd
  zz$V3[4] <- "" # d_rotor
  zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor
}

w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

This is the new, revised code:

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
      "length L (km)", "Width W (km)", "Height H (m)", "coefficient ()",
      "N ()", "J_h (GW)", "J_v (GW)", "f_red ()", "v (m/s)", "J_out (GW)")

V2 <- c(speed_vector[x],  # v
      "1.2",      # density
      "0.00482", # Cd
      "112",     # d
      "",
      "4.1",   # MW/km^2
      "", "",
      "700",    # Height
      "0.44",   # coefficient
      "", "", "", "", "", "")

V3 <- c(rep("",4),
      as.numeric(pi/4*(as.numeric(V2[4]))^2),
      rep("",1),
      as.numeric((16172.5*0.0898)^(1/2)),
      as.numeric((16172.5*0.0898)^(1/2)),
      rep("",2),
      as.numeric(16172.5*0.0898*as.numeric(V2[4])/3.075),

as.numeric(as.numeric(V2[2])/2*as.numeric(V3[8])*1000*as.numeric(V2[9])*
   (as.numeric(V2[1])^3)/10^9),

as.numeric((as.numeric(V2[2])*as.numeric(V2[3])*as.numeric(V3[8])*1000*
   as.numeric(V3[7])*1000*(as.numeric(V2[1])^3))/10^9),

as.numeric(as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)/
   ((as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)+3/2*
   as.numeric(V3[11])/(as.numeric(V3[8])*1000)*as.numeric(V2[10])*
   as.numeric(V3[5])),

as.numeric(as.numeric(V3[14])^(1/3)*as.numeric(V2[1])),

as.numeric(as.numeric(V2[2])/2*(as.numeric(V3[8])*1000)*as.numeric(V2[9])*
   as.numeric(V3[15])^3/10^9))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

an easier example:

```<code>speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
"V(m/s)")

V2 <- c(speed_vector[x],  # v
"1",      # density
"2", # Cd
"3",     # d
"4",   # MW/km^2
"5",    # Height
"6"   # coefficient
)

V3 <- c(as.numeric(as.numeric(V2[4]) ^ 2),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) * as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2]) + as.numeric(V2[3])),
as.numeric(as.numeric(V2[2]) + as.numeric(V3[2])),
as.numeric(as.numeric(V3[1]) + as.numeric(V3[2])))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")
</code>```

答:
EDIT: Updated with the follow-up requests for two options.

Consider this approach; it's a bit more idiomatic to store parameters in columns:

```<code>speed_racer <- function(v_in = NULL, density = NULL, Cd = NULL, d_rotor = NULL) {
  scenario <<- data.frame(v_in = c("(m/s)", v_in), density = c("(kg/m^3)", density),
                          Cd = c("()", Cd), d_rotor = c("(m)", d_rotor),
                          A_rotor = c("(m^2)", as.numeric(pi/4*(as.numeric(d_rotor)^2))))
}

speed_racer(v_in = 2.0, density = 1.2, Cd = 0.00482, d_rotor = 112.0)
</code>```

.

```<code>speed_racer <- function(v_in = NULL, density = NULL, Cd = NULL, d_rotor = NULL) {
  scenario <<- data.frame(v_in = paste(v_in, "m/s"), density = paste(density, "kg/m^3"),
                          Cd = Cd, d_rotor = paste(d_rotor, "m"),
                          A_rotor = paste(as.numeric(pi/4*(as.numeric(d_rotor)^2)), "m^2"))
}

speed_racer(v_in = 2.0, density = 1.2, Cd = 0.00482, d_rotor = 112.0)
</code>```

Title: create a data frame with a function

Body:
i have a data.frame with many values and calculations. One of the values is the wind speed. What i did is to calculate different energies from changing wind speeds. I did it manually and built the data frame row by row just like the following:

zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
         "A_rotor (m^2)")

zz$V2 <- c("2",  # wind_speed
         "1.2",      # density
         "0.00482", # Cd
         "112",     # d_rotor
         "")

zz$V3[1] <- "" # v_in
zz$V3[2] <- "" # density
zz$V3[3] <- "" # Cd
zz$V3[4] <- "" # d_rotor
zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor

This is just an excerpt of my data.frame, but i hope you can see my intention.
What i now want is to create always the same data frame with changing parameters, e.g. the wind speed (let's say 3 and 4 m/s).
And it would be also cool to change more than one value at the same time (let's say wind speed 5 and density 1 or wind speed 6 and density 2).
I tried to solve this problem with a function but it did not work. It only gave me a single value but not the complete data frame.

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)

make_speed <- function(x)

{
  zz <- as.data.frame(matrix(seq(100),nrow=5,ncol=3))

  zz$V1 <- c("v_in (m/s)","density p (kg/m^3)","Cd ()", "d_rotor (m)",
           "A_rotor (m^2)")

  zz$V2 <- c("speed_vector[x]",  # v_in
           "1.2",      # density
           "0.00482", # Cd
           "112",     # d_rotor
           "")

  zz$V3[1] <- "" # v_in
  zz$V3[2] <- "" # density
  zz$V3[3] <- "" # Cd
  zz$V3[4] <- "" # d_rotor
  zz$V3[5] <- as.numeric(pi/4*(as.numeric(zz[4,2]))^2) # A_rotor
}

w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

This is the new, revised code:

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
      "length L (km)", "Width W (km)", "Height H (m)", "coefficient ()",
      "N ()", "J_h (GW)", "J_v (GW)", "f_red ()", "v (m/s)", "J_out (GW)")

V2 <- c(speed_vector[x],  # v
      "1.2",      # density
      "0.00482", # Cd
      "112",     # d
      "",
      "4.1",   # MW/km^2
      "", "",
      "700",    # Height
      "0.44",   # coefficient
      "", "", "", "", "", "")

V3 <- c(rep("",4),
      as.numeric(pi/4*(as.numeric(V2[4]))^2),
      rep("",1),
      as.numeric((16172.5*0.0898)^(1/2)),
      as.numeric((16172.5*0.0898)^(1/2)),
      rep("",2),
      as.numeric(16172.5*0.0898*as.numeric(V2[4])/3.075),

as.numeric(as.numeric(V2[2])/2*as.numeric(V3[8])*1000*as.numeric(V2[9])*
   (as.numeric(V2[1])^3)/10^9),

as.numeric((as.numeric(V2[2])*as.numeric(V2[3])*as.numeric(V3[8])*1000*
   as.numeric(V3[7])*1000*(as.numeric(V2[1])^3))/10^9),

as.numeric(as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)/
   ((as.numeric(V2[9])+2*as.numeric(V2[3])*as.numeric(V3[7])*1000)+3/2*
   as.numeric(V3[11])/(as.numeric(V3[8])*1000)*as.numeric(V2[10])*
   as.numeric(V3[5])),

as.numeric(as.numeric(V3[14])^(1/3)*as.numeric(V2[1])),

as.numeric(as.numeric(V2[2])/2*(as.numeric(V3[8])*1000)*as.numeric(V2[9])*
   as.numeric(V3[15])^3/10^9))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

an easier example:

speed_vector <- c("w_sp_3" = 3, "w_sp_4" = 4)
make_speed <- function(x)
{
V1 <- c("v (m/s)","density (kg/m^3)","Cd ()", "d (m)", "A (m^2)", "N/(W*L)",
"V(m/s)")

V2 <- c(speed_vector[x],  # v
"1",      # density
"2", # Cd
"3",     # d
"4",   # MW/km^2
"5",    # Height
"6"   # coefficient
)

V3 <- c(as.numeric(as.numeric(V2[4]) ^ 2),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) * as.numeric(V2[2])),
as.numeric(as.numeric(V2[1]) + as.numeric(V2[2]) + as.numeric(V2[3])),
as.numeric(as.numeric(V2[2]) + as.numeric(V3[2])),
as.numeric(as.numeric(V3[1]) + as.numeric(V3[2])))

zz <- data.frame(V1,V2,V3)
return(zz)
}
w_speed_3 <- make_speed("w_sp_3")
w_speed_4 <- make_speed("w_sp_4")

Body:
EDIT: Updated with the follow-up requests for two options.

Consider this approach; it's a bit more idiomatic to store parameters in columns:

speed_racer <- function(v_in = NULL, density = NULL, Cd = NULL, d_rotor = NULL) {
  scenario <<- data.frame(v_in = c("(m/s)", v_in), density = c("(kg/m^3)", density),
                          Cd = c("()", Cd), d_rotor = c("(m)", d_rotor),
                          A_rotor = c("(m^2)", as.numeric(pi/4*(as.numeric(d_rotor)^2))))
}

speed_racer(v_in = 2.0, density = 1.2, Cd = 0.00482, d_rotor = 112.0)

.

speed_racer <- function(v_in = NULL, density = NULL, Cd = NULL, d_rotor = NULL) {
  scenario <<- data.frame(v_in = paste(v_in, "m/s"), density = paste(density, "kg/m^3"),
                          Cd = Cd, d_rotor = paste(d_rotor, "m"),
                          A_rotor = paste(as.numeric(pi/4*(as.numeric(d_rotor)^2)), "m^2"))
}

speed_racer(v_in = 2.0, density = 1.2, Cd = 0.00482, d_rotor = 112.0)


问:
text file inside class folder, yet cannot find it

As you can see, the file is right inside the same folder where the class file is. While I tried to have it print the path to it, that is a bummer because no matter what name I type it will always type a full path to that invented file name. The file is comma separated, that I copied pasted into gedit and tried all kinds of extensions, csv, txt and no extension.

What I am trying to do is import it into an array, but the error is clear, no such file or directory.

答:
Do not use relative paths to get files packaged with your application, it's dirty and senseless.

Path are relative to the folder in which was launched the java process. It's (usually) not your application source directory and never you file.java directory.

Even then, it's a terrible practice to put files (resources) inside your application source code. Because your java files needs to be compilated (and often packaged into a jar), the current architecture is likely to have no more meaning once packaged.

If you want to refer to a file on your computer, put it in a sensible folder (like /user/documents) and get it with its absolute path.

If you want the file to be packaged with your application, put it in a resource folder, package it in a jar and get the path with a classpath:// scheme.


问:
Hide div when a class is added via JS
I am working with fullPage.js where an active class is added to a li via JS.

What I would like to do is, when a li (#menu li:last-child) has active class, hide #menu. But, due to the active class was added via JS, the code doesn't work:

```<code>$(window).on("scroll",function() {
    if ($('li:last-child').hasClass("active")) {
        $("#menu").hide();
    }
})
</code>```

This is my HTML:

```<code><ul id="menu">
    <li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
</ul>

<div id="fullpage">
    <div class="section" id="section0">
        <div class="intro">
            <h1>Slide 1</h1>
        </div>
    </div>
    <div class="section" id="section1">
        <div class="intro">
            <h1>Slide 2</h1>
        </div>
    </div>
</div>
</code>```

答: you can try .on or .live(). because you added class added with js so you can put .hide() under live() or on() function.</p>

Title: Hide div when a class is added via JS

Body:
I am working with fullPage.js where an active class is added to a li via JS.

What I would like to do is, when a li (#menu li:last-child) has active class, hide #menu. But, due to the active class was added via JS, the code doesn't work:

$(window).on("scroll",function() {
    if ($('li:last-child').hasClass("active")) {
        $("#menu").hide();
    }
})

This is my HTML:

Slide 1

Slide 2


问:
how to disable userland-proxy for docker-compose
How to disable "userland-proxy" so that when using "docker-compose" it is disabled.

I tried running docker-compose up --userland-proxy=false but no luck.

答:
Disabling the Userland proxy is a global configuration, configured at the daemon level. You cannot change this configuration from the client, and thus not from docker compose.

To disable the proxy, you need to change the daemon configuration (see the dockerd reference. You can do so following the steps below (these steps should be done on the host that the daemon runs);

Create a file named /etc/docker/daemon.json if it does not exist, and add the "userland-proxy": false setting. The daemon.json file should be valid JSON; if this is the only configuration in that file, it should look like;

```<code>{
    "userland-proxy": false
}
</code>```

After saving the file, restart the daemon using (if your host uses systemd);

```<code>sudo systemctl restart docker
</code>```

Note: On Docker for Mac and Docker for Windows, the userland-proxy cannot be disabled, as it is an essential part of the networking (i.e. it allows connections to localhost to be forwarded to the containers)

Body:
Disabling the Userland proxy is a global configuration, configured at the daemon level. You cannot change this configuration from the client, and thus not from docker compose.

To disable the proxy, you need to change the daemon configuration (see the dockerd reference. You can do so following the steps below (these steps should be done on the host that the daemon runs);

Create a file named /etc/docker/daemon.json if it does not exist, and add the "userland-proxy": false setting. The daemon.json file should be valid JSON; if this is the only configuration in that file, it should look like;

{
    "userland-proxy": false
}

After saving the file, restart the daemon using (if your host uses systemd);

sudo systemctl restart docker

Note: On Docker for Mac and Docker for Windows, the userland-proxy cannot be disabled, as it is an essential part of the networking (i.e. it allows connections to localhost to be forwarded to the containers)


问:
Application not installed using apk but install via android studio
I have designed 2 to 3 application in android studio 2.3.1 and gradle 3.2. and all are working fine when i run application from it to any device or emulator. but when i get that apk from build folder and install manually to device or emulator. its crashes everytime and give me error classnotfound. which is MainActivity.

I am using Mac.I tried many ways. even i build new project but still same error. below is logcat of it.

```<code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.call.unblock/com.call.unblock.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.call.unblock.MainActivity" on path: DexPathList[[zip file "/data/app/com.call.unblock-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.lang.ClassNotFoundException: Didn't find class "com.call.unblock.MainActivity" on path: DexPathList[[zip file "/data/app/com.call.unblock-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                    Suppressed: java.lang.ClassNotFoundException: com.call.unblock.MainActivity
                                                     at java.lang.Class.classForName(Native Method)
                                                     at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                     at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                            ... 13 more
                                                  Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

Help me with it. i can't go further with my application without solving this issue.

答:
if code clean and re-build project is not working then that issue is in Android Studio bundle, you can import same Source code in another system it will work without any issue.
i face the same issue previously two three times but by setting code on another system same code without changes works perfectly</p>

Body:
I have designed 2 to 3 application in android studio 2.3.1 and gradle 3.2. and all are working fine when i run application from it to any device or emulator. but when i get that apk from build folder and install manually to device or emulator. its crashes everytime and give me error classnotfound. which is MainActivity.

I am using Mac.I tried many ways. even i build new project but still same error. below is logcat of it.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.call.unblock/com.call.unblock.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.call.unblock.MainActivity" on path: DexPathList[[zip file "/data/app/com.call.unblock-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                  Caused by: java.lang.ClassNotFoundException: Didn't find class "com.call.unblock.MainActivity" on path: DexPathList[[zip file "/data/app/com.call.unblock-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
                                                     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                    Suppressed: java.lang.ClassNotFoundException: com.call.unblock.MainActivity
                                                     at java.lang.Class.classForName(Native Method)
                                                     at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                     at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                     at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                            ... 13 more
                                                  Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

Help me with it. i can't go further with my application without solving this issue.


问:
How to input search query to get required image from JSON data?
I am currently building a web app using TMDB API when I type any movie name it should display me the poster of required movie. I am not getting how to search the required movie and get the URL of the poster. Links ->https://developers.themoviedb.org/3/movies/get-movie-images  and https://developers.themoviedb.org/3/configuration/get-api-configuration

My code:

```<code><html>
<head>
    <title>Test app</title>
    <style type="text/css">
        #fetch{
            position: absolute;
            text-align: center;
            left: 450px;
            top: 35px;
        }
    </style>
</head>
<body>

<form name="fetch-movie-title" id="fetch">
     <input type="text" placeholder="Enter a movie title" id="term" />
     <input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>

<script type="text/javascript">

function showdata() {
    var film = document.getElementById('term').value;
    console.log(film);
}

    var requestURL = "https://api.themoviedb.org/3/movie/9340/images?api_key=my-api-key";

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response; //request.response contains all our JSON data

        console.log(myjsondata);
        var str = "<img src = 'https://image.tmdb.org/t/p/w500"+ myjsondata.posters[2].file_path +"'/>";
        console.log(str);
        document.write(str);
    }

</script>
</body>
</html>
</code>```

答:
I can't test it as getting their API key requires too much hassle, but I guess what you need is search call:

```<code><html>
<head>
    <title>Test app</title>
    <style type="text/css">
        #fetch{
            position: absolute;
            text-align: center;
            left: 450px;
            top: 35px;
        }
    </style>
</head>
<body>

<form name="fetch-movie-title" id="fetch">
     <input type="text" placeholder="Enter a movie title" id="term" />
     <input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>

<script type="text/javascript">

function showdata() {
    var film = document.getElementById('term').value;
    console.log(film);

    var requestURL = "https://api.themoviedb.org/3/search/movie?api_key=<<api_key>>&language=en-US&query="+film+"&page=1&include_adult=false";

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response; //request.response contains all our JSON data

        console.log(myjsondata);
        var str = "<img src = 'https://image.tmdb.org/t/p/w500"+ myjsondata.results[0].poster_path+"'/>";
        console.log(str);
        document.write(str);
    }

</script>
</body>
</html>
</code>```

See this link -> https://developers.themoviedb.org/3/search/search-movies and then click on try it using your api-key as well as search query.

Body:
I am currently building a web app using TMDB API when I type any movie name it should display me the poster of required movie. I am not getting how to search the required movie and get the URL of the poster. Links ->https://developers.themoviedb.org/3/movies/get-movie-images  and https://developers.themoviedb.org/3/configuration/get-api-configuration

My code:

    <title>Test app</title>

<form name="fetch-movie-title" id="fetch">
     <input type="text" placeholder="Enter a movie title" id="term" />
     <input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>

Body:
I can't test it as getting their API key requires too much hassle, but I guess what you need is search call:

<html>
<head>
    <title>Test app</title>
    <style type="text/css">
        #fetch{
            position: absolute;
            text-align: center;
            left: 450px;
            top: 35px;
        }
    </style>
</head>
<body>

<form name="fetch-movie-title" id="fetch">
     <input type="text" placeholder="Enter a movie title" id="term" />
     <input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>

<script type="text/javascript">

function showdata() {
    var film = document.getElementById('term').value;
    console.log(film);

    var requestURL = "https://api.themoviedb.org/3/search/movie?api_key=<<api_key>>&language=en-US&query="+film+"&page=1&include_adult=false";

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response; //request.response contains all our JSON data

        console.log(myjsondata);
        var str = "<img src = 'https://image.tmdb.org/t/p/w500"+ myjsondata.results[0].poster_path+"'/>";
        console.log(str);
        document.write(str);
    }

</script>
</body>
</html>

See this link -> https://developers.themoviedb.org/3/search/search-movies and then click on try it using your api-key as well as search query.


问:
How to completely transfer flow of execution to another step in SOAP UI
I am trying to transfer the execution flow to another step in SOAPUI using groovy.
I am using gotoStepByName but the execution is returning back to the next lines of code after execution.

I always assumed runTestStepByName will call the test step .. complete the execution and continue the remaining piece of code.

While gotoTestStepByName will actually go, execute that step and continue executing the next steps without coming back and executing the remaining piece of code.

```<code>if (json.size() == 0) {
    testRunner.gotoStepByName( "DataSink")
    log.info "coming back here again"
}
</code>```

here I see the flow is actually coming back and printing 'coming back here again...'

How can I just transfer the flow of execution to another step from groovy without executing the rest of code and rest of steps before the transfer step.?

Any ideas?

答:
To transfer execution to other step (and skip any intermediate steps) you can use gotoStepByName

To stop execution of current Groovy Script you can use return statement

So the provided code from the question would look like following:

```<code>if (json.size() == 0) {
    testRunner.gotoStepByName( "DataSink") // Transfer execution to other step
    return                                 // Stop execution of current script
    log.info "coming back here again"
}
</code>```

Body:
I am trying to transfer the execution flow to another step in SOAPUI using groovy.
I am using gotoStepByName but the execution is returning back to the next lines of code after execution.

I always assumed runTestStepByName will call the test step .. complete the execution and continue the remaining piece of code.

While gotoTestStepByName will actually go, execute that step and continue executing the next steps without coming back and executing the remaining piece of code.

if (json.size() == 0) {
    testRunner.gotoStepByName( "DataSink")
    log.info "coming back here again"
}

here I see the flow is actually coming back and printing 'coming back here again...'

How can I just transfer the flow of execution to another step from groovy without executing the rest of code and rest of steps before the transfer step.?

Any ideas?

Body:
To transfer execution to other step (and skip any intermediate steps) you can use gotoStepByName

To stop execution of current Groovy Script you can use return statement

So the provided code from the question would look like following:

if (json.size() == 0) {
    testRunner.gotoStepByName( "DataSink") // Transfer execution to other step
    return                                 // Stop execution of current script
    log.info "coming back here again"
}


问:
Kafka Topic-per-Consumer Configuration
I understand that Kafka Consumer Group is load-balanced based on how many partitions exist for a specific topic. So the ideal combination is 1:1 for the number of partitions for a topic and the number of consumers in a consumer group which subscribes to the topic.

I have a scenario where each of my consumer is actually a consumer-group itself (i.e. 1 consumer per group). This mainly due to synchronisation between different databases so that the same data exists. All I am trying to do is run the same job on different environments as soon as the consumer get a message from the producer (broadcast).

For me, I don't believe that partitions/load balancing idea makes any difference. I am going with a topic that has 1 partitions and n Replication-Factor (n = total consumer groups, or consumer for my case). Does anyone think that I should still implement more than 1 partition for my case? If so, could you please mention why.

P.S. I am using the Producer/Consumer API only my messaging framework needs to have a minimum change/impact to my existing application setup.

答:
Multiple partitions are useful when you run Kafka in a cluster where the number of brokers is larger than the replication factor. So when you have 5 brokers and a replication of 3 then the 2  additional brokers are not needed. When you have two partitions with a replication of 3 you can divide 2*3 = 6 partitions over 5 brokers.

Only now there is one broker with two partitions while the others have one. So it's not spread evenly. It would be better to have more partitions to get a better spread.

There are other reasons to pick a number of partitions, but there are a lot of articles about this. What I explained is a good rule of thumb to start with.

Title: Kafka Topic-per-Consumer Configuration


问:
printing on screen and a text file
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

```
1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >
```

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

```<code>printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
</code>```

Is there an easiest way to implement this to cut down the number of lines of code?

答:
If you're writing a console application, you should be able to output to the screen (standard output) using something like:

```<code>fprintf(stdout, "Hello World\n");
</code>```

This should enable you to move the code that prints your data to its own function, and to pass in a FILE* for it to print to.  Then the function can print to the screen if you pass "stdout", or to a file if you pass in a different FILE*, e.g.:

```<code>void print_my_stuff(FILE* file) {
    fprintf( file,"Starting serial number       [%ld]\n", serial_info_p->start_int_idx);
    fprintf(file, "Current Serial number         [%d]\n", serial_info_p->current_int_idx);
    .
    .
    .
}
</code>```

OwnerDisplayName: Thi

Title: printing on screen and a text file

Body:
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);

Is there an easiest way to implement this to cut down the number of lines of code?

LastEditorDisplayName: Jonathan Leffler

Body:
If you're writing a console application, you should be able to output to the screen (standard output) using something like:

fprintf(stdout, "Hello World\n");

This should enable you to move the code that prints your data to its own function, and to pass in a FILE* for it to print to.  Then the function can print to the screen if you pass "stdout", or to a file if you pass in a different FILE*, e.g.:

void print_my_stuff(FILE* file) {
    fprintf( file,"Starting serial number       [%ld]\n", serial_info_p->start_int_idx);
    fprintf(file, "Current Serial number         [%d]\n", serial_info_p->current_int_idx);
    .
    .
    .
}

OwnerDisplayName: MattK


问:
Delayed Control Events
I have a weird delayed/off mapping event issue with a few controls within my UserControl.
The UserControl has 2 textboxes and 1 button. When I click on the button, nothing happens. When tab to the next control. The focus goes somewhere I can't see, but all the event for the button work there. I can hit the space bar and it fires with Button.click event. The same thing happens to the textboxes. I can type anything in the box I can see. Then hit tab, it goes to the box I can't see and all the events work. I went over all my code and I can't find anything that would suggest there are 2 controls on there..

Anyone have any suggestions on how to fix this??

答:
Just figured it out...
I copied some code into the New Constructor.. and in the code, I had an extra InitializeComponent()... which cause all the problems!</p>

Title: Delayed Control Events


问:
jquery post to retrieve data
```<code>$.post("test.jsp", {id : name}, function(data) {
});
</code>```

Is it possible to get db values without passing any data in jQuery post? I have a query in separate page("test.jsp") which get values from DB. Is there anyway to get values without any post data?

答: You don't need post if the data is available in your database. You just need to get it and display to users in that case.

Title: jquery post to retrieve data

Body:
$.post("test.jsp", {id : name}, function(data) {
});

Is it possible to get db values without passing any data in jQuery post? I have a query in separate page("test.jsp") which get values from DB. Is there anyway to get values without any post data?


问:
Handling Multiple request on a single resource
Recently I came across a question where it was asked if we have around 1000 users hitting a rest endpoint of a microservice and on this endpoint, it was fetching the same data from some other slow process, how could we optimize the request in this usecase? Caching is the obvious answer but how could it be optimized for large number of concurrent requests ? </p>

答:
Obviously as you say you have to go through the cache options, when you have a single application the fastest way can be Ehcache, it is a fairly simple framework to implement.

But if you want to increase the availability of the service you have to cluster it. For that you have to have a load balancer like nginx, and on the other hand to centralize the cache can be Redis db.

```<code>               Redis ( cache )
                     ^^
Nginx (LB) -> cluster of your app -> Other service
</code>```

Body:
Obviously as you say you have to go through the cache options, when you have a single application the fastest way can be Ehcache, it is a fairly simple framework to implement.

But if you want to increase the availability of the service you have to cluster it. For that you have to have a load balancer like nginx, and on the other hand to centralize the cache can be Redis db.

               Redis ( cache )
                     ^^
Nginx (LB) -> cluster of your app -> Other service