text:
Q: Order creation not working through rest api in Magento 2.1 I am using Magento 2.1.6 CE and also am using default rest api's for create mobile app. In that I follow below steps to create an order, But order is not created.
Step 1:- Create an empty cart for customer using POST /rest/V1/carts/mine/

Step 2:- Add product to cart using POST /rest/V1/carts/mine/items

Step 3:- Get cart totals using GET /rest/V1/carts/mine/totals/

Step 4:- Get Shipping methods by customer address id using POST /rest/V1/carts/mine/estimate-shipping-methods-by-address-id

Step 5:- Add billing and shipping address using POST /rest/V1/carts/mine/billing-address

Step 6:- Set shipping information using POST /rest/V1/carts/mine/shipping-information

Step 7:- Set payment information and create order using POST /rest/V1/carts/mine/set-payment-information

Note:
Am tried PUT /rest/V1/carts/mine/order method also but it returns following error.

How can I get this done?
Please suggest me is there any default options available to done this.
Thanks in advance!

A: You can use following method to create order using api.
Order Place:
<?php
require_once 'api.php';

require dirname(__FILE__) . '/../../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
require dirname(__FILE__) . '/../abstract.php';
$obj = $bootstrap->getObjectManager();
$resource = $obj->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();

// The URL to your Magento 2 instance (ending with /index.php/rest/V1)
$api_url = 'site_url/index.php/rest/V1';
// Set the integrations access token.
$token = 'auth_token';

$magento = new MagentoClient($token, $api_url);
$json = $_POST['json_obj'];
$json_cart_array =array();
$json_cart_array = json_decode($json,true);
$cart_id = $json_cart_array['cart_id'];
$payment_method = $json_cart_array['payment_method'];
//$payment_method = $json_cart_array['payment_method'];

// Create customer cart using customer id.
$ordered = $magento->placeOrderCust($cart_id, $payment_method);
$result1 = json_decode($ordered, 1);
//print_r($result1);exit();

API Class:
<?php
class MagentoClient {
  public $bearer_token = 'auth_token';
  public $base_url = 'magento_base_url';

  public function __construct($token, $base_url) {
    $this->base_url = $base_url;
    $this->bearer_token = $token;
  }

  public function request($endpoint, $method = 'GET', $body = FALSE) {

    // Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $this->base_url . $endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);

      $headers = array();
    $headers[] = "Authorization: Bearer " . $this->bearer_token;
    if ($body) {
      $headers[] = "Content-Type: application/json";
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
      echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
    return $result;
  }

  public function getProduct($product_id) {
    return $this->request('/products/' . $product_id . '/', 'GET');
  }

  public function createCart() {
    return $this->request('/guest-carts/', 'POST');
    // var_dump($this->request('/guest-carts/', 'POST'));
    // die;
  }

  public function addToCart($cart_id, $product_sku, $quantity = 1) {
    $order = array(
      'cartItem' => array(
        'quote_id' => $cart_id,
        'sku' => $product_sku,
        'qty' => $quantity,
      )
    );
    return $this->request('/guest-carts/' . $cart_id . '/items',
      'POST',
      json_encode($order)
      );
  }

  public function addToCartCust($cart_id, $product_sku, $quantity = 1,$options) {
    if(isset($options['extension_attributes']['configurable_item_options']) && $options != '' && count($options['extension_attributes']['configurable_item_options']) > 0){
      $order = array(
      'cartItem' => array(
        'quote_id' => $cart_id,
        'sku' => $product_sku,
        'qty' => $quantity,
        'product_option' => $options
      )
    );
    }else{
      $order = array(
      'cartItem' => array(
        'quote_id' => $cart_id,
        'sku' => $product_sku,
        'qty' => $quantity
      )
    );

    }
    //json_encode($order);

    return $this->request('/carts/' . $cart_id . '/items',
      'POST',
      json_encode($order)
      );
  }

  public function setShipping($cart_id, $shipping) {
    return $this->request('/guest-carts/' . $cart_id . '/shipping-information',
      'POST',
      json_encode($shipping)
    );
  }

  public function setShippingCust($cart_id, $shipping) {
    return $this->request('/carts/' . $cart_id . '/shipping-information',
      'POST',
      json_encode($shipping)
    );
  }

  public function placeOrder($cart_id, $payment_method = 'cashondelivery') {
    $payment = array(
      'paymentMethod' => array('method' => $payment_method)
    );

    return $this->request('/guest-carts/' . $cart_id . '/order',
      'PUT',
      json_encode($payment)
    );
  }

   public function placeOrderCust($cart_id, $payment_method = 'cashondelivery') {
    $payment = array(
      'paymentMethod' => array('method' => $payment_method)
    );

    return $this->request('/carts/' . $cart_id . '/order',
      'PUT',
      json_encode($payment)
    );
  }

  public function getPaymentMethods($cart_id) {
    return $this->request('/guest-carts/' . $cart_id . '/payment-information', 'GET');
  }

 public function createCustCart($cid)
 {
     return $this->request('/customers/' . $cid . '/carts', 'POST');
 }

}

This code is available on github but now i forgot the link.
Hope it helps.


text:
Q: sql update set ? = ? where ? = ? (python, sqlite3) Python, slite3
c.execute("UPDATE accounts SET ? = ? WHERE num=?", (db['choise'], db['data'], db['num']))

so i don't know what is wrong with it
db is shelve database

A: The column (and table) names cannot be parameterized. Use string formatting for it and query parameterization for the rest of variables:
c.execute("UPDATE accounts SET {column} = ? WHERE num = ?".format(column=db['choise']), (db['data'], db['num']))

That said, make sure you properly validate/sanitize/escape the db['choise'] value or really trust the source of it (though don't trust anyone when it comes to database interactions).

A: Column names cannot be given as arguments. You can try
c.execute("UPDATE accounts SET "+str(db['choise'])+" = ? WHERE num=?", (db['data'], db['num']))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I tell if a jquery ui dialog query has been initialized? I have the following code to detect if a jquery ui dialog is open:
if ($("#dialog-myDialog").dialog("isOpen")) {
      return;
}

which works fine but I found a situation where this code get called prior to the dialog being initialized in the first place and this if statement seems to just blow up in this case.
What is the best way to check if a jquery ui dialog has been initialized so I can properly handle this situation.

A: If you use a solution which relies on the presence of a css class added by a component that is out of your control, then you run the risk of this not working if a new version of the component changes the way it manages classes.
A more reliable solution would be to add your own existence indicator at dialog initialization:
$("#popup").attr("_dialogInitialized", "yes").dialog( { ... } )

Then check for your indicator when you need to:
if ($("#popup[_dialogInitialized]").length == 1) {
    // dialog has been previously initialized
} else {
    // dialog has been not yet been initialized
}

A: Test whether the element has the ui-dialog-content class:
if ($("#dialog-myDialog").hasClass("ui-dialog-content") &&
    $("#dialog-myDialog").dialog("isOpen")) {
    return;
}

A: Add a class when initilizing:
$("selector").addClass("initialized").dialog( { ... } );

Then check for the class when needed:
if ($("selector").hasClass("initialized")) { ... }


text:
Q: Where/how do you use Android Annotations? I need to change the background of a view programmatically so I was following this.  It says to make sure that you mark it with annotations.  Where do I do that?  I've tried the top of the class, the top of the method, inside the method.  I'm confused.  It's a little bothersome that I even need annotations to do this very simple/common thing anyway.
if (android.os.Build.VERSION.SDK_INT >=
    android.os.Build.VERSION_CODES.JELLY_BEAN) {
    rowView.setBackground(R.drawable.blue_background);
}
else {
    rowView.setBackgroundDrawable(R.drawable.blue_background);
}

The setBackground method gives me an error saying it is only available for APIs level 16 and above while my app supports lower than that.
The setBackgroundDrawable method is deprecated as of API level 16.
I'm being told to use @TargetApi(16) and @SuppressWarnings("deprecation") but where?  I'm using Eclipse for my IDE on Windows 7.

A: If you double-click on the error, Eclipse will create an auto-fix and the problem should disappear.


text:
Q: How to rule for invalid identifiers in lex? I want to rule invalid identifiers for lex , i tried this but not working, if identifier starts with numbers must be error, there can be another things
[0-9][a-zA-Z]*          fprintf(yyout,"ERROR IDENTIFIER\n");printf("%s: ERROR IDENTIFIER\n",yytext);

A: First of all: Welcome to StackOverflow.
Your rule should be:
[0-9]+[a-zA-Z]+

because you need at least one digit and at least one letter.
Currently your rule [0-9][a-zA-Z]* matches things like 0, 7, 4Hello, ... because * means zero-or-more.
Typically invalid token definitions are added for better error reporting. I'm wondering if that's indeed what you're explicitly intend to do? Because normally, when you start a new grammar (assuming you are because your question is about basic Lex rules), you just specify the valid token and let Lex & Yacc error handling catch wrong input.
So, if you not intended to explicitly improve error reporting, please delete this rule and only add rules for valid tokens (for now).


text:
Q: GridLayout in ScrolledForm not showing scrollBar I have components in a View and adding them in a ScrolledForm. But as soon as I use GridLayout, it is not showing the scrollbars any of the sides.

A: Try setting GridData.widthHint parameter to some relatively small value like 100. This will force the layout to not get too wide. Make sure to also set it to fill horizontally.
This should be all that's necessary if your layout doesn't have any controls that increase their height as width is constrained (like wrapped label). If you do, you will notice that your vertical scrollbars have too much slack in them. Reply here and I will give you the rest of the solution.


text:
Q: Laravel 4 file not uploading         $destinationPath = public_path().'/uploads/';
if (Input::hasFile('photo'))
        {
            $res = Input::file('photo')->move($destinationPath);
            echo $destinationPath;

            if($res)
            {
                echo '<br />good';
            }
            else
            {
                echo 'bad'.$res;
            }
            exit;
        }

my enctype form is enctype="multipart/form-data", the uploads folder exists and its access is 777, the above statement returns good, the path is correct, what I'am doing wrong?

A:     $photo = Input::file('photo');

    if (Input::hasFile('photo'))
    {

        $file            = Input::file('photo');
        $destinationPath = public_path().'/uploads/';
        $filename        = $file->getClientOriginalName();
        $uploadSuccess   = $file->move($destinationPath, $filename);
        $user->logo_path = $filename;
    }

    $object->save();

//  Don't forget to save it using a save function, otherwise your hard work will be for nothing
// $object : use your object like user, car, ...


text:
Q: Auth Forgot Password issue in Laravel 5.6 I am using Laravel's auth functionality. It's working fine except Forgot Password. I am trying to override following on ForgotPasswordController.
public function showLinkRequestForm()
{
    return view('admin.forgot');
}

It loads the form view for reset password and URL as follows:
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');

But when pressing submit button putting email address it shows following errors:

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

For your kind information, I didn't make any change without DB connection at .env file.
How can I send a reset link to the email address?
I hope someone will be able to help me with this.

A: Are you using mailgun by any chance, if so that is your problem? You need to authorize your mailgun account by adding a card. Alternatively, you can add individual emails to the allowed list however you won't know the emails in advance, so just authorize your mailgun and all will be well.


text:
Q: Reading static variable in Parallel.Foreach Is it safe to read from the static variable inside of Parallel.ForEach
class Program
{
    private static string _startTime;

    static void Main(string[] args)
    {
        _startTime = DateTime.Now.ToString();
        Parallel.ForEach(args,
        arg =>
        {
            Process(arg);
        });
    }

    private static void Process(string arg)
    {
        //Can I read _processStartTime variable here
        var startDateTime = _startTime;

    }
}

This article mentions about reading from a static variable but did not provide more information.
https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/potential-pitfalls-in-data-and-task-parallelism

A: Reading is fine (so long as all threads are just reading).
Editing requires thread-safety. If any thread will edit the data, even if the others are just reading, thread-safety needs to be addressed.
If the thing you were reading got it's data from computation or an external source, you'd need to think about thread-safety too, but in this particular example it's perfectly safe because it will always be the same value every time.
If you had a more real life example, you'll need to be aware of potential pitfalls, but for simple reads, it's not an issue.


text:
Q: Cannot see my label outlet when draging file owner in Interface builder I have this in my .h controller
@interface helloViewController : UIViewController {
    IBOutlet UIlabel *label;

}

-(IBAction)hello:sender(id);

@end

I opened the corresponding .xib file and I could drag and associate the button -hello to the file owner but trying to associate the label doesn't work: it suggests me to associate -view outlet instead why ?

A: Your method declaration should be:
-(IBAction)hello:(id)sender;

Also, UILabel needs a capital L
IBOutlet UILabel *label


text:
Q: Xcode 8.3 can't support Swift 2.3 I'm using Swift 2.3 in my project. Yesterday, I updated Xcode to version 8.3 but my project can't build successfully any more. I got this error message.

"Swift Language Version" (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit > Convert > To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.

Please help me! Thanks!

A: It is said in release note clearly that Xcode 8.3 doesn't support swift 2.x any more. You can either choose to use wizard to update your code to swift 3.1, or go back to Xcode 8.2.1.
https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html

A: That's true.
You have to convert your code to Swift 3. Or try to download a lower version of Xcode.


text:
Q: Ansible: How can I set serial numbers for hosts I am trying to provision hosts on EC2, so I am working with Ansible Dynamic Inventory.
What I want to do is; to set serial number for each node.
For example: "myid" configuration of Zookeeper
Zookeeper requires serial number named "myid" for each node; 1 for hostA, 2 for hostB, 3 for hostC and so on.
Here is the part of my playbook that copies "myid" file to hosts.
- name: Set myid
  sudo: yes
  template: src=var/lib/zookeeper/myid.j2 dest=/var/lib/zookeeper/myid

And myid.j2 should be something like this below.
{{ serial_number }}

The question is: What should the variable "{{ serial_number }}" be like?

A: I found a nice clean way to do this using Ansible's with_index_items syntax:
tasks:
  - name: Set Zookeeper Id
    set_fact: zk_id={{item.0 + 1}}
    with_indexed_items: "{{groups['tag_Name_MESOS_MASTER']}}"
    when: item.1 == "{{inventory_hostname}}"

/etc/zookeeper/conf/myid template can then be set to
{{zk_id}}

This assumes you are using AWS dynamic inventory.

A: I solved this by assigning a number to each EC2 instance as a tag when creating them. I then refer to that tag when creating the myid file. Below are the tasks I used to create my EC2 instances with all non-important fields left out for brevity.
- name: Launch EC2 instance(s)
  with_sequence: count="{{ instance_count }}"
  ec2:
    instance_tags:
      number: "{{ item }}"

Then when installing ZooKeeper on these servers, I use the dynamic inventory to obtain all the servers tagged with zookeeper and use the number tag in the myid file.
- name: Render and copy myid file
  copy: >
    content={{ ec2_tag_number }}
    dest=/etc/zookeeper/conf/myid

Note: when creating the EC2 instances, I needed to use with_sequence rather than the count field in the ec2 module. Otherwise I wouldn't have an index to capture for the tag.

If you want the playbook to handle being able to add nodes to the current cluster, you can query for the number of EC2 instances tagged with zookeeper and add that to the iteration index. This is fine to have normally because current_instance_count will be 0 if there aren't any.
- name: Determine how many instances currently exist
  shell: echo "{{ groups['tag_zookeeper'] | length }}"
  register: current_instance_count
- name: Launch EC2 instance(s)
  with_sequence: count="{{ instance_count }}"
  ec2:
    instance_tags:
      number: "{{ item|int + current_instance_count.stdout|int }}"

A: There is no need to use template, you can directly assign the content of myid file in the playbook. Assume you have collect all ec2 instance into the group "ec2hosts".
- hosts: ec2hosts
  user: ubuntu
  sudo:Trues

  tasks:
    - name: Set Zookeeper Id
      copy: >
      content={{ item.0 + 1 }}
      dest=/var/lib/zookeeper/myid
      with_indexed_items: "{{groups['ec2hosts']}}"
      when: item.1 == "{{inventory_hostname}}"


text:
Q: Vue v-for list does not update after data changed The idea is simple:
The Vue instance loads groups from an API.
This groups are shown using a v-for syntax.
The groupdata is formatted properly, and added to app.groups using .push function, which should update the v-for list.
However, the v-for list will not update.
When I change v-for="group in groups" (loaded externally) to v-for="group in people" (already in the app), it does give output.
HTML

Realtime Socket Chat

 @{{ group.name }}

                            Join

Vue
var app = new Vue({
    el: "#app",
    data: {
        groups: [],
        people: [{name: 'hi'}, {name: 'lol'}]
    },
    mounted: function() {
        this.load()
    },
    methods: {
        load: function() {
            axios.get('http://example.com/groups')
                .then(function (response) {

                console.log(response.data.groups);

                response.data.groups.forEach(function(group) {
                    app.groups.push(group);
                });

                // app.groups.forEach(function (group) {
                //    group.link = '/g/' + group.id + '/join';
                // });
                // console.log(response.data.groups);

                console.log(this.groups); //outputs [{...}, {...}] so this.groups is good
            })
            .catch(function (error) {
                this.errors.push(error);
                console.log(error);
            })
        }
    }

});

API
{
"groups": [
    {
  "id": 1,
  "name": "Photography Chat",
  "created_at": "2017-11-26 08:50:16",
  "updated_at": "2017-11-26 08:50:16"
},

{
  "id": 2,
  "name": "Media Chat",
  "created_at": "2017-11-26 08:50:16",
  "updated_at": "2017-11-26 08:50:16"
}

]
}

A: It seems like app is undefined when your load function is executed. So, using ES6 arrow function syntax, your load function should look like this:
load: function() {
  axios.get('http://example.com/groups')
    .then(response => {
      let groups = response.data.groups || []

      groups.forEach(group => {
        this.groups.push(group)
      })

      console.log(this.groups)

    })
    .catch(error => {
      this.errors.push(error)
      console.log(error)
    })
}

A: A fact I left out in the question (because I assumed it would not matter) was that I am working within the Laravel framework, Laravel automatically imports Vuejs within main.js. Which does not play nice when Vue is loaded in additionally. I removed main.js and it works.


text: Q: Convert UIImage to Bitmap in xamarin I want to convert a UIImage to Bitmap in iOS, Bitmap conversion in android is very easy by using BitmapFactory.DecodeByteArray() but in iOS I am not able to find any method.


text:
Q: ¬p ⊬ ⎕(p → q): Where's the mistake in my proof? My professor noted on one of his slides that ¬p ⊬ ⎕(p → q). Intuitively, this seems correct; however, I can only prove that it is false. I suspect I've made a mistake in my proof. Where have I gone wrong?

*

*¬(¬p→⎕(p → q)), w0✓

*¬p ∧ ◊¬(p → q), w0✓

*¬p, w0

*◊¬(p → q), w0✓w1

*w0Rw1

*¬(p → q),w1✓

*p∧¬q, w1✓

*p, w1

*¬q, w1

*⊥: (3.¬p w0, 5.w0Rw1, 8. p w1)

It is false that it is false that ¬p→⎕(p → q), so it is true that ¬p→⎕(p → q). If it is true that ¬p→⎕(p → q), then it cannot be the case that  ¬p ⊬ ⎕(p → q).

A: You have $\neg p$ back in $w_0$, and $p$ in $w_1$. But there's no contradiction between those two, even if $w_0Rw_1$!
It is absolutely fundamental that a propositional variable can take different values at different worlds, even if those worlds are related by the accessibility relation.


text:
Q: Why LLVM does not remember an integer range when the variable has been constrained by an if statement? There is a problem that has become quite popular these last days regarding the LLVM/GCC inability to optimize a trivial loop when the range is quite obvious.
Godbolt for all the examples below: https://godbolt.org/z/b3PzrsE5e
The code below will not optimize and the generated assembly will produce a loop.
uint64_t sum1( uint64_t num ) {
    uint64_t sum = 0;
    for ( uint64_t j=0; j<=num; ++j ) {
        sum += 1;
    }
    return sum;
}

produces
sum1(unsigned long):                               # @sum1(unsigned long)
        xorl    %eax, %eax
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
        addq    $1, %rax
        cmpq    %rdi, %rax
        jbe     .LBB0_1
        retq

However if one adds a limiter to the range of the variable, like an AND mask, the loop is able to optimize. You can also easily make it optimize if you change the condition j<=num to j<num+1.
uint64_t sum2( uint64_t num ) {
    num &= 0xFFFFFFFFULL;
    uint64_t sum = 0;
    for ( uint64_t j=0; j<=num; ++j ) {
        sum += 1;
    }
    return sum;
}

produces
sum2(unsigned long):                               # @sum2(unsigned long)
        movl    %edi, %eax
        addq    $1, %rax
        retq

while curbing the range with an if statement does not have any effect
uint64_t sum3( uint64_t num ) {
    uint64_t sum = 0;
    if ( num <= 0xFF ) {
        for ( uint64_t j=0; j<=num; ++j ) {
            sum += 1;
        }
    }
    return sum;
}

Produces assembly code again with a loop.
sum3(unsigned long):                               # @sum3(unsigned long)
        xorl    %eax, %eax
        cmpq    $255, %rdi
        ja      .LBB3_2
.LBB3_1:                                # =>This Inner Loop Header: Depth=1
        addq    $1, %rax
        cmpq    %rdi, %rax
        jbe     .LBB3_1
.LBB3_2:
        retq

For that sake, even __builtin_assume( num < 0x100ULL ) has no effect on the result.
I have looked into the LLVM code and traced this to the failed statement at
  // lib/Transforms/Scalar/IndVarSimplify.cpp:1430
  const SCEV *MaxExitCount = SE->getSymbolicMaxBackedgeTakenCount(L);
  if (isa<SCEVCouldNotCompute>(MaxExitCount)) {
    printf( "Could not compute\n");
    return false;
  }
...

which then ends up in
//  lib/Analysis/ScalarEvolution.cpp:7253
  const SCEV *ScalarEvolution::getExitCount(const Loop *L,
                                          const BasicBlock *ExitingBlock,
                                          ExitCountKind Kind) {
  switch (Kind) {
  case Exact:
  case SymbolicMaximum:
    return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
  case ConstantMaximum:
    return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
  };
  llvm_unreachable("Invalid ExitCountKind!");
}

What I don't understand is why the boundary cannot be inferred if the if statement makes it clear? Is this a feature that could be implemented? Am I in the right track?


text:
Q: camera2 createConstrainedHighSpeedCaptureSession on pixel 4a fails I am trying to capture a high fps video utilizing createConstrainedHighSpeedCaptureSession, the same code runs OK on OnePlus 8T / Honor 10 but does fail on Pixel 4a
startPreview code:
        surfaces.clear();
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;

        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

        mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
        Surface previewSurface = new Surface(texture);

        surfaces.add(previewSurface);
        mPreviewBuilder.addTarget(previewSurface);

        setUpMediaRecorder();
        surfaces.add(mMediaRecorder.getSurface());
        mPreviewBuilder.addTarget(mMediaRecorder.getSurface());

        mCameraDevice.createConstrainedHighSpeedCaptureSession(surfaces, new CameraCaptureSession.StateCallback() { ...

the error:
01-11 16:12:22.335 11406 11438 W System.err: java.lang.IllegalArgumentException: Surface size 1841x1036 is not part of the high speed supported size list [1280x720, 1920x1080]
    01-11 16:12:22.336 11406 11438 W System.err:    at android.hardware.camera2.utils.SurfaceUtils.checkConstrainedHighSpeedSurfaces(SurfaceUtils.java:266)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.hardware.camera2.impl.CameraDeviceImpl.createCaptureSessionInternal(CameraDeviceImpl.java:741)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.hardware.camera2.impl.CameraDeviceImpl.createConstrainedHighSpeedCaptureSession(CameraDeviceImpl.java:638)
    01-11 16:12:22.336 11406 11438 W System.err:    at com.revelio.highspeedvideodemo.CaptureHighSpeedVideoModeFragment.startPreview(CaptureHighSpeedVideoModeFragment.java:527)
    01-11 16:12:22.336 11406 11438 W System.err:    at com.revelio.highspeedvideodemo.CaptureHighSpeedVideoModeFragment.access$300(CaptureHighSpeedVideoModeFragment.java:64)
    01-11 16:12:22.336 11406 11438 W System.err:    at com.revelio.highspeedvideodemo.CaptureHighSpeedVideoModeFragment$2.onOpened(CaptureHighSpeedVideoModeFragment.java:190)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:168)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.os.Handler.handleCallback(Handler.java:938)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.os.Handler.dispatchMessage(Handler.java:99)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.os.Looper.loopOnce(Looper.java:201)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.os.Looper.loop(Looper.java:288)
    01-11 16:12:22.336 11406 11438 W System.err:    at android.os.HandlerThread.run(HandlerThread.java:67)

CaptureHighSpeedVideoModeFragment.java:527 is the mCameraDevice.createConstrainedHighSpeedCaptureSession from the code snippet above
I am setting the previewSize and videoSize to 1920x1080, but somehow that is not respected on the Pixel 4a
where does that 1841x1036 resolution come from? why does this code work on other phones but not on the Pixel 4a?
How do I make the preview surface stick with the resolution I want it to stick to?
thanks for any hints

A: I saw that all camera devices are by default forced to use the highest fps available. The exception is with the Pixel 4a devices which has a bug from the manufacturer. All other devices are forced to record video with the highest fps available for the camera device. I went as far as to investigate the camera manager also.
CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES will return maximum [30-30] fps but not slow motions fps range. and it returns it only for Pixel 4a devices, even though they are reported to support 60fps. here is the code: Check Code
line 29 to line 52

A: for anyone else that would have the same problem, i solved it by changing the layout from match_parent to fixed resolution, in my case I want full hd so i just set the
<com.revelio.highspeedvideodemo.AutoFitTextureView
    android:id="@+id/texture"
    android:layout_width="1920px"
    android:layout_height="1080px" />

its not the prettiest solution, but solves my immediate problem
probably would be better to use a SurfaceView instead of TextureView, but couldn't find any examples how to do that
as for the answer proposed by Eternal Life - fps is not the problem here, pls see the error that i got, the textureView resolution did not match the createConstrainedHighSpeedCaptureSession supported resolutions even that i was setting it, the only thing that works seams to be the layout fixed resolution ... but thx for trying to help, appreciated

A: You may be trying to set up the camera before the UI layout has completed. The TextureView sets a buffer size after it gets it layout dimensions, and you need to make sure you call setDefaultBufferSize after that point.
Are you waiting for TextureView.SurfaceTextureListener.onSurfaceTextureSizeChanged or onSurfaceTextureAvailable before calling TextureView.getSurfaceTexture()?


text:
Q: How to perform an insert with a select statement to put in multiple rows with HQL Need to know how to do an insert with HQL with a select and that select contains a union. Here's my test case
create table simple_author (
id bigint generated by default as identity,
first_name varchar(255),
last_name varchar(255),
primary key (id))

@Entity
public class SimpleAuthor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
private String firstName;
private String lastName;}

Assume the requirement is to insert 2 authors and if one fails for whatever reason the other is not persisted in the database.
Using just SQL and if Oracle or H2 I can do
Insert into simple_author(first_name, last_name) select 'bob','smith' from dual union select 'frank', 'brown' from dual
Or if using SQL Server:
Insert into simple_author(first_name, last_name) select 'bob','smith' union select 'frank', 'brown'
Assume Bob Smith and Frank Brown are supplied by a user entering data in a UI.
Looking at https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#hql-insert
Seems to support a simple case.
Seems there are a couple of issues:
Doing a union and the list of values to be added in this case bob smith and frank brown
For the union have tried a couple of solutions as seen in threads
Hibernate Union alternatives
and
How to execute query with union in hibernate?
at best they only seem to get close to what is required.
So the question is How to write:
Insert into simple_author(first_name, last_name) select 'bob','smith' from dual union select 'frank', 'brown' from dual
In hsql

A: Unfortunately HQL/JPQL do not support this. Such things can be done with native query or techs like FluentJPA, which does native query under the covers.

A: at least for me I was using Spring and at the time of writing did not known within a DAO that Spring using the @Transactional annotation will manage the commit. Found out the entity manager will commit or rollback all rows based on if an exception occurs therefore I can reach the goal of an "all or nothing" being committed. So in my case the code is:
  // if an exception occurs then the transaction is rolled back there is not any
  // special code required.
  public List<SimpleAuthor> insertSimpleAuthors(List<SimpleAuthor> simpleAuthors) {
   // try {
      //em.getTransaction().begin();
      for (SimpleAuthor entity : simpleAuthors) {
        em.persist(entity);
      }
      //em.flush();
//    } catch (Exception ex) {
//      em.getTransaction().rollback();
//      throw ex;
//    }
    for (int i = 0; i < simpleAuthors.size(); i++) {
      //SimpleAuthor entity : simpleAuthors) {
      simpleAuthors.set(i,
      em.createQuery("from SimpleAuthor where firstName = :firstName and lastName = :lastName",SimpleAuthor.class)
       .setParameter("firstName", simpleAuthors.get(i).getFirstName())
       .setParameter("lastName", simpleAuthors.get(i).getLastName())
       .getSingleResult()
       );
    }
    return simpleAuthors;
  }


text:
Q: What to pass as threshold for Naive Bayes Classifier in Pyspark? I'm trying to make a ROC curve for my model while using a Naive Bayes Classifier. To do this, I need to change the value of the threshold for my classifier. The way I interpreted it, a list must be passed with the value for the threshold of each category. So if i had two categories, and t is the threshold I want to set (0 <= t <= 1), then I would have to pass a list like this: [1-t, t].
Anyways, when i tried doing the ROC curve, I got this:

Given the result, my idea was that the idea I had for the theshold might have been wrong, so I went to check the documentation for the Naive Bayes Classifier. But when I finally found an example i dont get what the criteria is for the parameter:
nb = nb.setThresholds([0.01, 10.00])

Does anyone know what must be passed to the threshold? Supose I want the theshold to be set at 0.7 (if the probability is over 0.7 i want the prediction to be 1), what should i pass to the threshold parameter?

A: As it says in pyspark.ml's documentation for NaiveBayes under the thresholds parameter:

The class with largest value p/t is predicted, where p is the original
probability of that class and t is the class's threshold.

Therefore, thresholds can be thought of as handicaps on the probabilities. To keep it simple, in the case of binary classification, you can set the thresholds as a value in the range [0, 1], such that they sum to 1. This will get you the desired rule of "Classify as True if the probability is over threshold T, otherwise classify as False".
For your specific ask of a 0.7 probability threshold, this would look like:
nb = nb.setThresholds([0.3, 0.7])

assuming that the first entry is the threshold for False and the second value is the thresold for True. Using these thresholds, the model would classify a class with False and True probabilities p_false and p_true by taking the greater value out of [p_false/0.3, p_true/0.7].
You can technically set the thresholds to any value. Just remember that the probability for class X will be divided by its respective threshold and compared against the other adjusted probabilities for the other classes.


text:
Q: The form file does not contain valid XML.Form cannot be opened.Contents is not allowed in prolog
I'm using NetBeans IDE, I'm creating a JFrame and during work on my project the computer shut down. When I run it again and run NetBeans and enter to my project design mode, it pops up this message. So how to fix the XML file for the JFrame form?

The form file does not contain valid XML.Form cannot be opened.Contents is not allowed in prolog

A: When working with Swing GUI forms, NetBeans keeps a .form XML file in the same folder as the .java source file.  The contents of this .form file is used to generate the .java code within the 'Generated Code' sections of your JFrame.
It looks like this .form file became corrupt when your computer shut down.
It's difficult to say much more without seeing the contents of this file.  Try finding this .form file and opening it in a text editor such as Notepad or Notepad++.


text:
Q: Looking for a short story about hunting aliens I read this story a few years ago while looking at various TVTropes pages. It's about a group of four, two siblings, their personal assistant and the man who's flying them to this alien hunting world. They're there to hunt down a particular beast which for some reason I can't help feeling like it had something to do with Platypuses. During the story the sister shoots a member of a non-threatening and protected race who then kidnap her in the night to try and replace the one she shot. Her brother and her (after being rescued) kill most or all of the little pack that abducted her. The story then goes on with the group's deterioration as the creature begins to hunt them and ends with the tour guide and assistant escaping.

A: Softly spoke the Gabbleduck by Neal Asher, contained in The gabble and other stories (2008). The siblings are Tholan and Tameera. Tholan's personal assitant is Anders. The story is told from the point of view of a local guide. Tameera shoots a sheq, also known as shit-eater. The other sheq kidnap her to replace the one she shot and her brother goes in pursuit. Unfortunately for the little group there's also a gabbleduck, a highly dangerous duckbilled alien creature talking nonsensical phrases, around. The twins die, Anders and the guide survive, waved goodbye by the gabbleduck.


text:
Q: Xpages JavaBean static Notes Object cause error saving In this JavaBean, I wrote some object as (static). But when I reach the logDoc.save() method, it returns error. Removing all (static), all run fine.
The error in console was:
HTTP JVM: lotus.domino.local.Document method: save, row: -1:
NotesException: Notes error: You are not authorized to perform that operation

or
HTTP JVM:lotus.domino.local.NotesBase method: CheckObject, row: -1:
NotesException: Object has been removed or recycled

depending on ACL settings for Anonymous.
Anyone can explain me whot's the problem with static objects here?
    public class AnyRest extends CustomServiceBean implements Serializable  {

    private static final long serialVersionUID = 3548995909847938225L;

    private (static) Database logDB=null;
    private (static) Document logDoc=null;
    private (static) RichTextItem logBody=null;

    private  (static) void log(String text) {
        if (logDB==null) logDB= ExtLibUtil.getCurrentDatabase();
        try {
            if (logDoc==null) {
                logDoc=logDB.createDocument();
                logDoc.replaceItemValue("form","log");
                logBody=logDoc.createRichTextItem("Body");
            }
            logBody.appendText(text);
            logBody.addNewLine();
            logDoc.save();
        } catch(NotesException ne) {
            logStackTrace(ne);
        }
    }

    private (static) void destroyLog() {

        try {
            if (logDoc!=null) {
                logDoc.save();
                logDoc.recycle();
                logDoc=null;
            }
            if (logDB!=null) {
                logDB.recycle();
                logDB=null;
            }

        } catch (Exception e) {
            logStackTrace(e);
        }
    }

    public String doPost(String strObject){
        //do useful things
        log("useful post data")
    }
}

A: Domino objects are not serializable.
You should use Domino objects within a class method only.
Store in class fields data like:

*

*Domino server's name,

*path to database,

*view's name,

*document's id or a list of documents' ids,

*document item's values,
This way you can easily get the Domino objects again when you need them.
But, never store Domino objects like session, database, view and document in class fields.
(Unless you instantiate the class at every request new and with it the fields - but this is definitely not the case when you use "static".)

A: Backend objects retrieved via the provided sessions, like that, will be recycled at the end of each request. You should rewrite the class to re-retrieve the Document each request, either creating a new one each time or stashing the UNID of the doc when it's created, and then using getDocumentByUNID.


text:
Q: Sealing a FFC ZIF connector How can I make a Flat Flex Cable (FFC) Zero Insertion Force (ZIF) connector resistant to environmental contamination?
Background/Assumptions:
I have a microwave over my stove. Every few months, the keypad begins to malfunction and register key presses without human interference. Naturally, it's one of the buttons that will start the microwave. After a while, the keypad will become non-responsive. The keypad in this unit is a sealed membrane unit with a single FFC. Nothing in the keypad requires active electronics, and the number of contacts and buttons) strongly suggests a standard sampled keypad switch matrix.
I'm pretty sure a row line adjacent to a column line is getting a low enough resistance to register as a button press. Removing the FFC from the ZIF connector and re-inserting it will fix the problem for about a day. Cleaning the FFC and flushing the ZIF connector with isopropyl alchohol will fix the problem for a few months. Considering that the electronics compartment isn't well sealed, I believe steam and other cooking byproducts are making their way into the ZIF connector and causing measurable leakage between pins.
The FFC termination is single-sided with a pitch of about 1.25mm/50 mil. The microwave is a Samsung, but I don't think that's relevant to the solution.

How can I improve the environmental resistance of a FFC connection? Looking at the connector, it seems like there is an unsealed path on both the top and bottom of the connector. My priorities (in order) are:

*

*Don't buy a new microwave - the old one works*

*Make the fix permanent so I'm not constantly disassembling the microwave

*Don't make the connection permanent (e.g. soldering the FFC to the board)

A: Hewlett Packard instruments in the 70's used to specify maintenance for their gold plated card edge fingers using only Pink Pearl©® Rubber erasers (lol).
Isoprop. does wonders with a Pink Pearl and the contamination could also include oil and water vapours which are excellent electrical insulators.
But the ZIF socket has a problem if the retention force is zero and does not have a "gas-tight" seal because even non-24 caret gold is still prone to some oxidation with high temp and humidity.
Examine the surface under a 10x lens and look for pitting and lubricate and wipe the mating contacts with isoprop and repeated Pink Pearl treatments to the FPC being careful not to leave any shreds inside the socket.
Then as @Almostdone has suggested use Plumber's waterproof stretch tape black tape for moisture leaks and wrap around the socket with minimal stress on the FPC yet sealing the clean surface with finger pressure after wraps.
The alternative is  Silicone which still has moisture ingress but slows it down and  it may block greasy water vapours but may be harder to repair.
That should last you more than a year.  I wonder if Korean's use this microwave for Kimchi style cooking?  If so, Samsung ought to have a better Quality Reliability Test Engineers.

The other possibility is excess pressure on membrane carbon contacts has smeared the carbon to make certain buttons like "Start" wear out faster.


text:
Q: Given list of countries draw map with those countries a different color Looking to the do what the title says - produce a world map image that colors particular countries.  I'm open to platform - Processing or Python/Basemap preferable.  Web based service ok if it has an API.
Anyone have direction on this?

A: have you looked at GIS? There are a number of open source and free clients that allow you to work with various maps (probably .dwg) with various corresponding data in xml format to produce geographical visualizations through queries and you can export a number of formats. I think this would give you either the visualization that you want or the data to plug into processing or whatever to create it.

A: Get the map data in shapefile format, look at python bindings to OGR and GDAL, or maybe try Fiona: http://sgillies.net/blog/1095/fiona/ or SciPy, or just download Qgis www.qgis.org and learn some GIS skills.
Country-level shapefiles for the world are fairly widely available www.gadm.org maybe.

A: Google Geomap did the trick here.
It's part of their chart visualizations tools.  A javascript call that returns an SVG map colored according to data that you provide.


text:
Q: bind the managedObjectContext outlet for a controller using Interface Builder? I'm trying to set up a fairly simple view that presents a table to the user. This table is connected to an Array Controller, which I want to use to retrieve records from Core Data. For some reason, I can't seem to connect the 'managedObjectContext' outlet to anything else in my app. When I created my project, there was a property generated in my app delegate which returns the MOC I need, but I can't hook it up in Interface Builder, even after prepending "IBOutlet" to the declaration. Image below showing the available connection on both ends:
http://yada.im/uploads/image/screenshot/1108/7efebc90ca7187a537da9ae003dd5f3e.png
I'm sure that I'm missing some simple step here but I can't tell what piece of glue code I'm supposed to write that will allow me to hook this up more easily. For reference, I've tried dragging a line from the controller's moc outlet to every single source I could think of, and changed the "File's Owner" class to that of my application. Stumped here!

A: Typically in the template provided by XCode the managedObjectContext comes along with AppDelegate.
You have to bind the managedObjectContext reference of the array controller to the managedObjectContext in AppDelegate.
For this you have to make an object of AppDelegate inside the xib i.e., if its not already present.(Drag an object placeholder from your object library and make its class as AppDelegate)
This makes AppDelegate visible for binding inside that xib.
Next step is actually binding the managedObjectContext. Select your array controller and go to bindings inspector. In the parameters section select App Delegate from the drop down and check on "Bind to".
Fill the "Model Key Path" field with self.managedObjectContext. Now you will find the connection in the connections inspector also.
UPDATE:
The process of creating a new AppDelegate object is to be done only if it is not already present in the main nib file (but the stub generated always has the AppDelegate object in the main nib file).
For a non main nib file, if we follow the above approach, a new AppDelegate object will be created which won't be the NSApplication's delegate. Even though this can be solved by connecting delegate outlet of the application object proxy provided in each nib, the AppDelegate object still won't be the same.
The result is two different managedObjectContext talking to the same store. Although this might appear to work properly when the changes are saved at each step, this is not what we want.
To get the right AppDelegate object, i.e. the one used in the main nib file:
-instead of creating a new AppDelegate object, bind the managedObjectContext of the array controller directly through the application to its delegate. In other words the object to bind to will be the application object and the key path used will be self.delegate.managedObjectContext.

A: The way to add objects of your entity depends on the specific logic you want to implement.
The generic and easy solution would be, binding the fields for input to the array controller like you might have done for the table and then hooking up the array controller methods to the buttons inside the sheet.
Another option is sub-classing NSArrayController and over-riding the super class methods like add: to write your code (for opening your slide sheet maybe) before calling the super class method, [super add:sender] . Don't forget to specify this sub-class of NSArrayController as the class of your array controller in the xib.


text:
Q: Empty a Python deque every 10 seconds I have a Python deque that I append each time in that deque.
pre_label = collections.deque(maxlen=5)
while True:
      #do something
      function(name)
      pre_label.append()

i have :
pre_label = deque(['john', 'zari', 'fai'], maxlen=3)

I want to have the following output every 10 seconds :
pre_label = deque([], maxlen=3)

A: So, there are a couple of ways to do this off the top of my head:

*

*Threaded solution
If you're using python 2, or you don't want to do async, this should work:
Quick disclaimer: I don't use threads all that often, so you should look for more advice on that. :)

from collections import deque

deck = deque([], maxlen=3)

## Threaded solution
from threading import Thread
import time

def clear_deque():
    """ This is a small function to clear the queue and print the contents when cleared"""
    global deck  # You should probably avoid globals, but we need a reference to the underlying object to make the clear actually work.
    while(True):
        time.sleep(3)  # you'd want to increase this to 10. Also, sleeping at the start to allow some time before the clear to happen the first time.
        contents = list(deck)
        deck = deque([], maxlen=3)
        print("\n |> Deck = {}".format(contents))

t = Thread(target=clear_deque)  # Making a new thread to call this one function
t.daemon=True  # Marking the thread as a daemon, so that it can be killed when the program exits normally
t.start()  # annnd starting the thread!

# And a dumb loop to verify the functionality
while True:
    v = input("Add stuff> ")
    deck.append(v)

t.join()

*If you're using python 3, you can implement a similar solution using an async worker. This example demonstrates how to do it, but if you go the async route, you need to make sure all of your long running processes are async, so it may require a significant re-architecture.

import asyncio
import random
from collections import deque

deck = deque([], maxlen=10)

async def clear_deque():
    global deck
    while True:
        await asyncio.sleep(3)
        contents = list(deck)
        print(f"\n |> Deck contents: {contents}")
        deck = deque([], maxlen=10)

async def add_to_deque():
    while True:
        await asyncio.sleep(random.random())
        v = random.randint(1, 10)
        print(f"Adding: {v}")
        deck.append(v)

loop = asyncio.get_event_loop()
actions = asyncio.gather(add_to_deque(), clear_deque())
loop.run_until_complete( actions )


text:
Q: An error in setup documentation of the Firebase SDK for android It seems to be an error in the Firebase setup documentation for android...
Link
The documentation says to add this to build.gradle:
buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.1.0' // google-services plugin
    }
}

allprojects {
    // ...
    dependencies {
        // ...
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

This didn't work for me and i found this solution here on Stackoverflow (add maven{...} in repositories and not in dependencies):
allprojects {
    // ...
    repositories {
        // ...
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

The question is: why this works and how Firebase official documentation can be wrong?
Thanks.

A: // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

write this code in project level build.gradle.

A: I would recommended you to take this following approach
Step 1:- Login to google account from android studio you can find this option on top right corner
Step 2:- Go to Tools>Firebase
It will bring Firebase Assistance panel to right hand side
Step 3:- Click on service you want to use and it will set the project for you
Refer this screenshot On right you can see Firebase Assistance page


text:
Q: display UIViewController Is this the right way to call UIViewController programmtically when play button is pressed
UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
                               target:self
                               action:@selector(playaudio:)];
systemItem1.style = UIBarButtonItemStyleBordered;

-(void) playaudio: (id) sender
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme"
                                                     ofType:@"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
    audioPlayer = [[AVAudioPlayer alloc]
                    initWithContentsOfURL:fileURL error:nil];

    audioPlayer.currentTime = 0;
    [audioPlayer play];
    [fileURL release];

    UIViewController* flipViewController = [[UIViewController alloc]init];
    [self.view addSubview:flipViewController.view];
}

A: If your UIViewController is stored in a NIB file you can use:
FlipViewController *flipViewController = [[FlipViewController alloc] initWithNibName:@"flipView" bundle:nil];

Then you can add its view using:
[self.view addSubview:flipViewController.view];

Or show it as a modal view (as suggested by the name of your UIViewController)
flipViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:flipViewController animated:YES];

Take a look at UIViewController Class Reference:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html
EDIT: Here is the way to dismiss a modal view using notification.
You have to set an observer in your UIViewController (the one that calls your flipViewController):
- (void)setObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationReceived:)
                                                 name:@"DismissModalView"
                                               object:nil];
}

- (void)notificationReceived:(NSNotification *)notification {
    if ([[notification name] isEqualToString:@"DismissModalView"]) {
        [self dismissModalViewControllerAnimated:YES];
    }
}

Now call setObserver in your viewDidLoad.
Remember to remove your observer in dealloc:
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // other objects
    [super dealloc];
}

Now when you want to come back in your modal view call something like this:
- (IBAction)dismissMe:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DismissModalView" object:self];
}

This last part posts a notification that arrives to your observer. When the observer gets this particular notification calls [self dismissModalViewControllerAnimated:YES]; and your modal view is dismissed.
This is the documentation: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html


text:
Q: Ruby/Nokogiri nested loop in Nexpose XML results parser failing I am trying to write a ruby script to take the Nexpose Simple XML results export, parse it, and write the required results out to a prettier format for easy review. I am using Nokogiri to parse the XML. My issue is that I have a nested loop that for each device, iterates through each service section and pulls out the name, port, and protocol attributes from each one. This will ultimately be printed back out to a file either a text file or a csv. However, my nested loops seems to only pull those three attributes from the first service section and prints them repeatedly.
Sample Input (there will be more than one of these device blocks):
<device address="10.x.x.1" id="20xx">
<fingerprint certainty="0.85">
<description>Microsoft Windows</description>
<vendor>Microsoft</vendor>
<family>Windows</family>
<product>Windows</product>
<version/>
<device-class>General</device-class>
<architecture/>
</fingerprint>
<vulnerabilities>
</vulnerabilities>
<services>
<service name="NTP" port="123" protocol="udp">
<vulnerabilities>
</vulnerabilities>
</service>
<service name="HTTP" port="8080" protocol="tcp">
<fingerprint certainty="0.75">
<description>Apache</description>
</device>

<device address="10.x.x.2" id="20xx">
<fingerprint certainty="0.85">
<description>Microsoft Windows</description>
<vendor>Microsoft</vendor>
<family>Windows</family>
<product>Windows</product>
<version/>
<device-class>General</device-class>
<architecture/>
</fingerprint>
<vulnerabilities>
</vulnerabilities>
<services>
<service name="DNS" port="53" protocol="udp">
<vulnerabilities>
</vulnerabilities>
</service>
<service name="HTTP" port="80" protocol="tcp">
<fingerprint certainty="0.75">
<description>Apache</description>
</device>

Ruby Code:
#! /usr/bin/env ruby

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::XML(open('report.xml').read)
device = doc.xpath('//device')

device.each do |d|
 service = d.xpath('//service')
 puts d.attr('address')

 service.each do |s|
   name = s.attr('name')
   port = s.attr('port')
   protocol = s.attr('protocol')

   puts port
   puts protocol
   puts name
 end
end

Desired Output:
10.x.x.1
123
udp
NTP
8080
tcp
HTTP

10.x.x.2
53
udp
DNS
80
tcp
HTTP

Actual Output:
123
NTP
udp
123
NTP
udp

So the code should show a list of service port, name, and protocol for each service of each device. However, the current code seems to just print the set for the first service (which is 123, NTP, and udp) over and over and over.
Am I missing something in the logic of my loop? Or do you see anything wrong with the loops? Any help getting this working would be helpful. Thanks.

A: Note that the XPath construct // means find the element anywhere in the document. You don't want to do that in the inner loop, because you've already done that for your device.
Update
Based on the new input document, here is one way to extract the information you need. I took the liberty of using CSV, for a nice Excel-ready output file. Note that there is a single parsing loop. Code:
require 'nokogiri'
require 'csv'

doc = Nokogiri::XML(open('report.xml').read)

CSV.open("devices.csv", "wb") do |csv|
  csv << ["Device", "Service", "Port", "Protocol"]
  doc.search('//service').each do |s|
    device = s.xpath('ancestor::device[1]/@address')
    name = s.attr('name')
    port = s.attr('port')
    protocol = s.attr('protocol')
    csv << [device, name, port, protocol]
  end
end

Here's the contents of devices.csv:
Device,Service,Port,Protocol
10.x.x.1,NTP,123,udp
10.x.x.1,HTTP,8080,tcp
10.x.x.2,DNS,53,udp
10.x.x.2,HTTP,80,tcp


text:
Q: Change table cell positions by strings using jQuery I'd like to change table cell positions using jQuery.
Before
— kiwi fruit
— Peach
— banana
green | fruit:  kiwi fruit
pink | fruit:  Peach
yellow | fruit:  banana
Sour | fruit:  kiwi fruit
sweet | fruit:  Peach
sweet | fruit:  banana

After - I want it change this way.
— kiwi fruit
green | fruit:  kiwi fruit
Sour | fruit:  kiwi fruit
— Peach
pink | fruit:  Peach
sweet | fruit:  Peach
— banana
yellow | fruit:  banana
sweet | fruit:  banana

They use the same format below.
"- [fruit]"
" | fruit:  [fruit]"

*2nd one before the [fruit], two spaces

        — kiwi fruit

        — Peach

        — banana

        green | fruit:  kiwi fruit

        pink | fruit:  Peach

        yellow | fruit:  banana

        Sour | fruit:  kiwi fruit

        sweet | fruit:  Peach

        sweet | fruit:  banana

I made it with sources below, but it's not practical because other fruit like 'apple','cherry',etc. can be added in the future and each time I add the new fruit I have to edit my sources.
$("tr:contains(' | fruit:  kiwi fruit')").insertAfter("tr:contains('— kiwi fruit')");
$("tr:contains(' | fruit:  Peach')").insertAfter("tr:contains('— Peach')");
$("tr:contains(' | fruit:  banana')").insertAfter("tr:contains('— banana')");

Thank you!
I asked this question 2 days ago and have not found any solution.
If someone could help me with this quiestion, I would really appriciate it.


text:
Q: How to extract values from a Pandas DataFrame, rather than a Series (without referencing the index)? I am trying to return a specific item from a Pandas DataFrame via conditional selection (and do not want to have to reference the index to do so).
Here is an example:
I have the following dataframe:
  Code  Colour  Fruit
0   1   red     apple
1   2   orange  orange
2   3   yellow  banana
3   4   green   pear
4   5   blue    blueberry

I enter the following code to search for the code for blueberries:
df[df['Fruit'] == 'blueberry']['Code']

This returns:
4    5
Name: Code, dtype: int64

which is of type:
pandas.core.series.Series

but what I actually want to return is the number 5 of type:
numpy.int64

which I can do if I enter the following code:
df[df['Fruit'] == 'blueberry']['Code'][4]

i.e. referencing the index to give the number 5, but I do not want to have to reference the index!
Is there another syntax that I can deploy here to achieve the same thing?
Thank you!...
Update:
One further idea is this code:
df[df['Fruit'] == 'blueberry']['Code'][df[df['Fruit']=='blueberry'].index[0]]

However, this does not seem particularly elegant (and it references the index).  Is there a more concise and precise method that does not need to reference the index or is this strictly necessary?
Thanks!...

A: Let's try this:
df.loc[df['Fruit'] == 'blueberry','Code'].values[0]

Output:
5

First, use .loc to access the values in your dataframe using the boolean indexing for row selection and index label for column selection.  The convert that returned series to an array of values and since there is only one value in that array you can use index '[0]' get the scalar value from that single element array.

A: Referencing index is a requirement (unless you use next()^), since a pd.Series is not guaranteed to have one value.
You can use pd.Series.values to extract the values as an array. This also works if you have multiple matches:
res = df.loc[df['Fruit'] == 'blueberry', 'Code'].values

# array([5], dtype=int64)

df2 = pd.concat([df]*5)
res = df2.loc[df2['Fruit'] == 'blueberry', 'Code'].values

# array([5, 5, 5, 5, 5], dtype=int64)

To get a list from the numpy array, you can use .tolist():
res = df.loc[df['Fruit'] == 'blueberry', 'Code'].values.tolist()

Both the array and the list versions can be indexed intuitively, e.g. res[0] for the first item.
^ If you are really opposed to using index, you can use next() to iterate:
next(iter(res))

A: you can also set your 'Fruit' column as ann index
df_fruit_index = df.set_index('Fruit')

and extract the value from the 'Code' column based on the fruit you choose
df_fruit_index.loc['blueberry','Code']

A: Easiest solution: convert pandas.core.series.Series to integer!
my_code = int(df[df['Fruit'] == 'blueberry']['Code'])
print(my_code)

Outputs:
5


text:
Q: Ember app can't find assets I am using Ember 2.6.1 to build a web application and am trying to use a custom image file in my stylesheet.
In the Ember-cli documentation, it states:

To add images, fonts, or other assets, place them in the public/assets directory. For example, if you place logo.png in public/assets/images, you can reference it in templates with assets/images/logo.png or in stylesheets with url('/assets/images/logo.png').

I tried to follow these instructions exactly.. My image file is located in the public/assets/images directory, and it's called plus.png.
In my less stylesheet, I reference url('/assets/image/plus.png'), but I always receive a 404 Not Found error:
http://localhost:8080/assets/img/plus.png 404 (Not Found)

I've tried every possible url resource path I can think of...what am I missing here?


text:
Q: A question about AUTOSAR, does [constr_1221] apply to Initial Value Representation at level 2? When i use a NumericalValueSpecification to init value for an ApplicationPrimitiveDataType of category 'BOOLEAN' with a NonqueuedSenderComSpec, it can correctly generate RTE codes without any compilation error, but as [constr_1221] said, if a DataPrototype is typed by an ApplicationPrimitiveDataType its initValue shall be provided by an ApplicationValueSpecification. So, does [constr_1221] apply to Initial Value Representation at level 2?

A: Yes, any DataPrototype that is typed by an ApplicationDataType shall only be initialized by means of an ApplicationValueSpecification. A NumericalValueSpecification or TextValueSpecification can be used to initialize a DataPrototype typed by an ImplementationDataType.


text:
Q: Algebraic representation of an absolute value. I tried several ways, but i could not come up with any way to have an equation as such:
|n| = ...

without using the absolute value signs on the right side of the equation.
I do not know if there is any way...
I tried using some form of n * i^(an + b) but those efforts were futile.
And I couldn't think of any other way to approach this.

A: One way is to note that the square root has "branches":
$$(\sqrt n)^2=n\tag 1$$
$$\sqrt{n^2}=|n|\tag 2$$
Note that $(1)$ would dip into the imaginary numbers for a moment if $n\lt 0$.  $(2)$ is true because the square root of a number is one of two solutions to the equation involving the square.
$$x^2=4,x=2,-2$$
$$\sqrt 4=2,-\sqrt 4=-2$$


text:
Q: React redux + fetch data from Firebase While I am trying to fetch user data from firebase in my user reducer like this :
const initialState = {
    user : {
        firstname : "",
        lastname : "",
        todoList : [],
        addressBook : []
    }
};

const usersReducer = async (state = initialState, action) => {
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);

    switch(action.type) {

        case FETCH_USER_DATA:
            const docRef = doc(db, "users", action.payload.userUid);
            const docSnap = await getDoc(docRef);
            if (docSnap.exists()) {
              console.log("Document data:", docSnap.data());
            } else {
              console.log("No such document!");
            }
            return {
                user: {firstname: docSnap.data().firstname, lastname: docSnap.data().lastname, todoList: [], addressBook: []}
            }

        default:
            return state;
    }
}

When I get my user state in my components I receive this object :

{"_A": null, "_x": 0, "_y": 1, "_z": {"user": {"addressBook": [Array], "firstname": "XXX", "lastname": "XXX", "todoList": [Array]}}}

I dont' understand why I get this attribute in my object: "_A": null, "_x": 0, "_y": 1, "_z":

A: It works for me:
const ref = db
  .collection('users')
  .doc(action.payload.userUid)

const doc = await ref.get();

if (!doc.exists) {
  console.log('Not exists');
} else {
  console.log('data', doc.data())
}


text:
Q: Laravel Pivot Table belongsToMany I'm new on php and Laravel, so I have a lot of doubts.
I'm using phpmyadmin and have the next relationship:
Table:| productos | tipos  | marcas | producto_tipo_marca (pivot table)
      | id        |  id    | id     | id
      | id_tipo   | nombre | nombre | id_producto
      | id_marca  |        |        | id_tipo
      |           |        |        | id_marca

(I work names in english)
So, the table product(productos) have a realtionship with the foreing_keys id_type(id_tipo) and id_brand(id_marca). A product have Many-Many relationship with type and brand.
Question 1: Did a need a Pivot Table or not? (Sorry but I'm alone in my job and have the doubt)
I have been working with jquery and listing data (all fine) but on the product.index I whant to show the id_type->nambe and the id_brand->nambe, but all I can show on the datatable it's the id_type and id_brand (showing only numeric data):
View: product.index
@foreach($products as $product)
    {{ $product->id_type}}
    {{ $product->id_brand }}
@endforeach

When I do something like:
@foreach($products as $product)
    {{ $product->id_type->name}}
    {{ $product->id_brand->name}}
@endforeach

Have the error: Trying to get property of non-object (View: C:\xampp\htdocs\posm\app\views\productos\index.blade.php)
So, I watch a lot of tutorials but can't get the core.
In my models have this:
Product (Model)
protected $guarded = array();
protected $table = 'products';
protected $fillable = array('id_type','id_brand');

Question 2: Did I need to specify somethin like: id_type->name or I can't do somethin like that?
Type (Model)
protected $guarded = array();
protected $table = 'type';
protected $fillable = array('name');

public function products(){
    return $this->belongsToMany('Product'); //Access the model Product.
}

Brand (Model)
protected $guarded = array();
protected $table = 'brand';
protected $fillable = array('name');

public function products(){
    return $this->belongsToMany('Product'); //Access the model Product.
}

ProductController
public function index()
{
    $products = $this->product->all();
    return View::make('product.index', compact('product'));
}

Question 3: Did I need to add some code here to specify than product get the id_type->name and id_brand->name or just let it like I have it?
Questions:
What I need to do?
¿Just for get the id_type->name and the id_brand->name on my jquery datatable?
¿I need a pivot table and do some code on models and controllers? Or can get the type and brand name directly on the view product.blade?
Sorry for the long question. I'll be grateful for any help. Thanks!

A: I'm not and advanced mysql user, but I think you don't need the pivot table.
You need the tables: productos, tipos and marcas.
If you are accessing the data from the "Product" model, you need to add this relation in Product.php:
(I didn't understand if you are using english or spanish for your code).
public function type()
{
    return $this->belongsTo('Type', 'type_id');
}

public function brand()
{
    return $this->belongsTo('Brand', 'brand_id');
}

If you need to automatically load this relationships on every query, you need to add this property:
public $with = ['type', 'brand'];

If not, you can specify when making the query instead of adding the $with property, like this:
Product::with(['type', 'brand'])->get();

Then you can do:
$products = Product::with(['type', 'brand'])->get();

And in the view:
@foreach($products as $product)
    {{ $product->type->name }}
    {{ $product->brand->name }}
@endforeach

I didn't test the code, so check it before using it!
The Laravel documentation is great, you should take a look at it: http://laravel.com/docs/4.2/eloquent


text:
Q: Email notification to all Opportunity Team Members The task is to notify all Opportunity Team Members every time new chatter post appears in feed inside of the Oppty. Now we use the following script:
trigger emailFollowers on FeedItem (after insert) {
  String OppKeyPrefix = Opportunity.sObjectType.getDescribe().getKeyPrefix();
    for (FeedItem f: trigger.new) {
    String parentId = f.parentId;
        if (parentId.startsWith(OppKeyPrefix)) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 List<Opportunity> OppOb = [select Opportunity.Name  from Opportunity where Opportunity.id = :f.ParentID];
//List<OpportunityTeamMember> OTMList = [Select User.name from OpportunityTeamMember where OpporunityId =:f.ParentID ];
 List<EntitySubscription> followers = [select id, subscriberid, subscriber.name, subscriber.email from EntitySubscription where parentid = :f.ParentID];

        String[] toAddresses = new List<String>();

        for (EntitySubscription follower : followers) {
            toAddresses.add(follower.subscriber.email);
        }

        mail.setToAddresses(toAddresses);

        //mail.setTemplateID(templateId.Id);
        String Subject = 'New post in opportunity feed ' + OppOb[0].Name ;
        mail.setSubject(Subject);
        List<User> UserList = [select User.Name from User where User.Id =: f.CreatedById ];

String Body ='User '+UserList[0].name+' posted: ' +f.body+' '+f.CreatedDate ;
        mail.setHTMLBody(Body);

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
}

The script works very well but all the members have to FOLLOW every opportunity in chatter. When uncomment line 8 the error is:

Invalid type OpportunityTeamMember

We also tried to replace line 8 with:
SELECT User.Email FROM OpportunityTeamMember WHERE OpportunityId = :oppId AND User.isActive = true

Error: Invalid type: Schema.OpportunityTeamMember

and
SELECT Id, (SELECT User.Email FROM OpportunityTeamMembers WHERE User.IsActive = true) FROM Opportunity WHERE Id IN :changedOppsIds

ERROR at Row:1: Column:36
      Didn't understand relationship 'OpportunityTeamMembers' in FROM part of query call. If you are attempting to use a custom
  relationship, be sure to append the '__r' after the custom
  relationship name. Please reference your WSDL or the describe call for
  the appropriate names.

Any suggestions on how to improve the script to make it work and avoid following opptys for Team Members?

A: use this code, I have tested it and it is working fine in my org:
trigger emailFollowers on FeedItem (after insert) {
  String OppKeyPrefix = Opportunity.sObjectType.getDescribe().getKeyPrefix();
    for (FeedItem f: trigger.new) {
    String parentId = f.parentId;
        if (parentId.startsWith(OppKeyPrefix)) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 List<Opportunity> OppOb = [select Opportunity.Name  from Opportunity where Opportunity.id = :f.ParentID];
List<OpportunityTeamMember> followers = [Select User.name,user.email from OpportunityTeamMember where OpportunityId =: f.ParentID];
// List<EntitySubscription> followers = [select id, subscriberid, subscriber.name, subscriber.email from EntitySubscription where parentid = :f.ParentID];

        String[] toAddresses = new List<String>();

        for (OpportunityTeamMember follower : followers) {
            toAddresses.add(follower.user.email);
        }

        mail.setToAddresses(toAddresses);

        //mail.setTemplateID(templateId.Id);
        String Subject = 'New post in opportunity feed ' + OppOb[0].Name ;
        mail.setSubject(Subject);
        List<User> UserList = [select User.Name from User where User.Id =: f.CreatedById ];

String Body ='User '+UserList[0].name+' posted: ' +f.body+' '+f.CreatedDate ;
        mail.setHTMLBody(Body);

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
}


text:
Q: Using OAuth with Jira REST calls in .NET / F# I am trying to create a .NET application in F# that calls out to the Jira REST API to read/create issues.
I generated a .pub and .pem with OpenSSL, and created an application link in Jira with the public key.
Here is the signing function that I put together (based off of some C# code I found in a blog post) that gets me the initial token response:
let rsasha1 (signingKey : string) str =
    let rsa = new RSACryptoServiceProvider()
    rsa.FromXmlString(signingKey)
    let shaHashObject = new SHA1Managed()
    let data = Encoding.ASCII.GetBytes(str : string)
    let hash = shaHashObject.ComputeHash(data)
    let signedValue = rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"))
    Convert.ToBase64String(signedValue, Base64FormattingOptions.None)

And this is the function that I'm using to do the call (also found from a snippet online)
/// Request a token and return:
///  oauth_token, oauth_token_secret, oauth_callback_confirmed
let requestToken() =

    let queryParameters =
        ["oauth_callback", "oob"
         "oauth_consumer_key", consumerKey
         "oauth_nonce", System.Guid.NewGuid().ToString().Substring(24)
         "oauth_signature_method", "RSA-SHA1"
         "oauth_timestamp", currentUnixTime().ToString()
         "oauth_version", "1.0"]

    let signingString = baseString "POST" requestTokenURI queryParameters

    let rsaSignature = rsasha1 consumerSecretXML signingString

    let realQueryParameters = ("oauth_signature", rsaSignature)::queryParameters

    let req = WebRequest.Create(requestTokenURI, Method="POST")
    let headerValue = createAuthorizeHeader realQueryParameters
    req.Headers.Add(HttpRequestHeader.Authorization, headerValue)

    let resp = req.GetResponse()
    let stream = resp.GetResponseStream()
    let txt = (new StreamReader(stream)).ReadToEnd()

    let parts = txt.Split('&')
    (parts.[0].Split('=').[1],
     parts.[1].Split('=').[1],
     parts.[2].Split('=').[1] = "true")

This successfully returns token information, but I am unsure what to do next once I have the token. The original C# code that I based this off of was using HMACSHA1 instead of RSASHA1 and simply concatenated the consumer secret with the token secret and then called the signing function again.
I am unable to get this working that way. I had to convert my private key in the .pem file into XML in order to read it into the RSACryptoServiceProvider. If I try to concatenate the token secret onto the private key before converting, I get an error.
How do I go about signing the token secret so that I can do subsequent REST calls to Jira?

A: This is probably not the answer you want, but I did something close to what you need. I am not using anything else then "ordinary" authentication (by JSON), but then again I am reusing the Session variable JSESSIONID (cookie) when I am authenticated.
If this works for you (your authentication, and then grabbing the JSESSIONID and then reusing it), the following code should kind of work (as a principle).
Mind that I am using FSharp.Data <package id="FSharp.Data" version="2.3.1" targetFramework="net46" /> and maybe some "friends" (some other package dependencies) in the same run.
Please also note that I am referencing a file for the returned JSON of the query, so if you you are going to use the JSON-provider and doing a search or something like that, you need some JSON to infer the search result from.
Hopefully the code will give you some pointers.
And yes, this code is probably not the finest moment of F# ;-)
#r "System.Servicemodel"
#r "System.Xml"
#r @"..\packages\FSharp.Data.2.3.1\lib\net40\fsharp.data.dll"

open FSharp.Data
[<Literal>]
let baseUrl = "https://jira"

[<Literal>]
let jiraUrlQuery = baseUrl + "/rest/api/2/search?jql=text%20~%20%22some text%22%20ORDER%20BY%20created%20DESC"

[<Literal>]
let loginUrl = "/rest/auth/1/session"

//[<Literal>]
let creds = sprintf "{\"username\": \"%s\", \"password\": \"%s\" }"

[<Literal>]
let loginInfoExample = "{\"session\":{\"name\":\"JSESSIONID\",\"value\":\"åæø8F95074F7398C68961708066EC6342A8\"},\"loginInfo\":{\"failedLoginCount\":7,\"loginCount\":434,\"lastFailedLoginTime\":\"2016-08-02T13:15:27.392+0200\",\"previousLoginTime\":\"2016-08-05T08:46:45.168+0200\"}}"

type LoginInfo = JsonProvider< loginInfoExample >

let login = Http.Request(baseUrl+loginUrl, httpMethod="POST", body=HttpRequestBody.TextRequest( creds "SomeUserName" "SomePassword" ), headers= [ "Content-Type", "application/json" ])
//let login = JsonValue.Request(baseUrl+loginUrl, httpMethod="POST",  headers= [ "Content-Type", "application/json" ])

let getText =
    function
    | Text s -> s
    | _ -> ""

let loggedIn = LoginInfo.Parse(getText login.Body).Session.Value.ToString()

type JiraIssues = JsonProvider< ".\JIRA\query.json" > //jiraUrlQuery>

let listOfCases = JiraIssues.Parse(Http.Request(jiraUrlQuery, cookies=["JSESSIONID", loggedIn] ).Body |> getText)

listOfCases.Issues |> Seq.map (fun x -> x.Fields.Summary, x.Fields.Created) |> Seq.sortByDescending (fun (s,c) -> c) |> Seq.iter (fun (s,c) -> printfn "%A: %s" c s)

A: We couldn't get OAuth working, but inspired by @Helge's answer, we were able to fake logging in the way a user does.
#r "System.Net.Http"

open System
open System.Collections.Generic
open System.Net
open System.Net.Http
open System.Net.Http.Headers

let toKVPairSeq l =
    Seq.map (fun (k, v) -> KeyValuePair(k, v)) l

let handler = new HttpClientHandler()
let client = new HttpClient(handler)
client.BaseAddress <- Uri "http://jira/"
let authRequestContent = new FormUrlEncodedContent([
                                                        "os_username", "jira-user"
                                                        "os_password", "jira-password"
                                                        "os_cookie", "true"
                                                        "os_destination", ""
                                                        "user_role", ""
                                                        "atl_token", ""
                                                        "login", "Log+In"
                                                    ] |> toKVPairSeq)
let request = new HttpRequestMessage()
let result1 = client.PostAsync("login.jsp", authRequestContent).Result
result1.EnsureSuccessStatusCode()
printf "%A %s" result1.StatusCode <| result1.Content.ReadAsStringAsync().Result
let result2 = (client.GetAsync "rest/api/latest/issue/ISSUE-1").Result
printf "%A %s" result2.StatusCode <| result2.Content.ReadAsStringAsync().Result


text:
Q: Why aren't some technically serializable input properties serializable? Serializable property is defined as:

*

*When you set a property of the element, it will be reflected in serialization queries such as getAttribute and you can see the changes in DOM Inspector

*When you get the .innerHTML of the element's parentnode, the returned html string will contain all the serializable properties as their attribute counterparts

I have made a page that looks like it's reliably printing a table of all serializable properties of the input element in Chrome and Firefox: http://jsfiddle.net/tEVLp/16/.
Custom properties are never serializable, so in firefox webkitSpeech etc are not serializable. Test in chrome for best results.
All booleans are true because serialization of a false property would be the absence of the attribute which is a false negative in the test.
So my question is, why are not properties such as .value and .checked serializable?
Technically, both are serializable. .value is just a string and the browser has no problems with serializing other boolean properties, such as .readOnly and .disabled.
My best guess is that since .defaultValue serializes to "value"-attribute and .defaultChecked serializes to "checked"-attribute, there would be a conflict and thus the
.value and .checked cannot be serialized. In that case, why are the defaultX ones chosen for these and not the ones that reflect the more useful current .value and .checked states?

A: value and checked properties do not correspond to HTML attributes so they cannot be serialized to HTML. As to why a defaultX property maps to the x attribute, I'm not sure. The alternative, a property x mapping to the x attribute and having another property such as currentX to represent the current value, seems slightly less intuitive because in general a script is going to need the current value more often than the default value.

A: The Specification for input elements defines the exact behaviour. Start reading from here (before that, the DOM interface, attributes and types are defined).
Concise summary (value is defined similarly to checked, so for brevity, I'm going to explain value only).
The "property" value reflects value def,
the "attribute" value reflects the value content attribute def.

*

*The attribute defines the default value property (ref). This value is also reflected def by the defaultValue property (ref).

*When the value attribute is set, then the value property changes (ref) *.

That was worded very concisely. I've skipped an important detail. The specification is very clear at this point, so I'll just quote the dirty value flag section:

Each input element has a boolean dirty value flag. The dirty value
  flag must be initially set to false when the element is created, and
  must be set to true whenever the user interacts with the control in a
  way that changes the value.
The value content attribute gives the default value of the input
  element. When the value content attribute is added, set, or removed,
  if the control's dirty value flag is false, the user agent must set
  the value of the element to the value of the value content attribute,
  if there is one, or the empty string otherwise, and then run the
  current value sanitization algorithm, if one is defined.


text:
Q: Access array from java controller How can I send an array with form data and access it from java controller?
I tried the code for passing array as
ajaxData.append('Array', myarray)

Also tried to access from java controller as
@RequestParam("Array") List<Integer> newArray

It is not working.

A: You should use Model Object to get all the formdata values. You can use @ModelAttribute at controller's method level.
@RequestMapping(value="/yourmapping")
public String formProcessing(@ModelAttribute FormModel formData){

}

class FormModel{
    private String field1;
    private String field2;
    private MultipartFile file;
   ...
}

http://www.startwithjava.com/spring-boot-multiple-files-upload-with-other-input-fields/


text:
Q: LÖVE and Lua. Making an .EXE file I'm making a Lua game using the 2D framework 'LÖVE'.
I needed to know HOW to make a .exe file with it! I've done the command line, sucessfully zipped up my main.lua and the image, I've renamed the file extension to .exe!! When I run the .exe, I get a file extracting application coming up. This is not supposed to happen, right? I want it to be run as a game, not as a self-extracting application. Help?

A: From the sounds of it, you are trying to save your 'lovechive' with an .exe extension; your archiver is probably 'helpfully' assuming you meant to create a self extractor, which you didn't.

Okay, lets start by talking about how runable 'lovechives' work:
When love.exe starts up, it first checks its own name, if its called something other than love or love.exe it immediately checks to see if there is somethng stuck to its end. if there is, then it tries to interpret it as if it were a 'lovechive'.
So basically, we want to stick a zip-file to love's bottom (don't worry, it likes it).

*

*Start by creating an ordinary zip archive of you game directory.

*

*Remember to check for anything you don't actually mean to ship; plenty of love games have gone out containing backup copies of the source code, test artwork, and peoples' shopping lists. Don't be a statistic.

*The filename is irrelevant for what were are doing here, so don't worry about the usual step of renaming it to a .love. just make sure that what you have is an plain-ol' ordinary zip.

*The next step depends on your host platform, but basically you now need to do the whole "stick it to love's bottom' part now, generally this is done from the command-line:

*

*On windows, the command is:
copy /b love.exe+YourGame.zip TheGame.exe
Where love.exe is the name of the main 'love' executable YourGame.zip is the name of zip file containing your game, and TheGame.exe is what you want the final game executable to be named.

*On Linux or OSX, the command is:
cat love YourGame.zip > TheGame
Where love is the name of the main 'love' executable, YourGame.zip is the name of zip file containing your game, and TheGame is what you want the final game executable to be named.

These substituting the relevant filenames should let you produce versions for Linux, and Windows
(All I know about making 'merged' OSX Apps is that its more complicated.)

For the record, it is utterly trivial to extract files from the 'merged' game. Usually nothing more than changing the file extension, sometimes not even that.
And no, zip encryption doesn't help here; it won't run because love can't read the archive. (quite sensibly, really.)
Finally, If you are distributing to the Love community, they generally prefer that you just give them the 'lovechive.'

A: From https://love2d.org/wiki/Game_Distribution :
Here's how to do it on Windows. In a console, type this:
copy /b love.exe+game.love game.exe

Then, all you have to do is zip game.exe and required DLLs, and distribute them. Yes; this does mean that the game will have a private copy of LÖVE, but there's nothing wrong with that. It also means that you will have to create one package for each platform you would like to support, or simply offer the .love alone for the other platforms.


text:
Q: Exclusion List in Journey Builder I've set up a journey in Journey Builder however I want to exclude a list of customers. When sending an email from Content Builder it allows me to exclude and suppress lists but this option is not there on Journey Builder.
Has anyone else experienced this issue and is there a way around it? Our data is not in real time so require the manual imported list to exclude for this journey.
Thanks
Keith

A: Content Builder and UI sends allow you to exclude Data Extensions . With Journey Builder, you are only allowed to to suppress / exclude customer via Suppression Lists, Domain Exclusion DEs or Exclusion Scripts. In addition to this, if you add customers to an Auto suppression list then they are excluded from all sends automatically.

References:

*

*Exclusion Script

*Exclude Domains From Exact Target

*AutoSuppression List


text:
Q: Storing meta information to class properties I've been agaonizing about this problem for some days:
I have a class Info
public class Info
  {
    private int _no;

    public int No
    {
      get
      {
        return _no;
      }
      set
      {
        _no = value;
      }
    }
  }

That class can be used anywhere in any classes (inherited or as property). The property can be considered as security relevant or not. That information is known at design time and needs to be stored for that particular property.
So for some classes which uses that class as property I want the member "No" to be set accordingly.
  public class IsRelevant
  {
    private Info _prop = new Info();
    public Info Prop { get { return _prop; } set { _prop = value; } }
  }

  public class IsNotRelevant
  {
    private Info _prop = new Info();
    public Info Prop { get { return _prop; } set { _prop = value; } }
  }

For a first try I was thinking about introducing an custom attribute like this:
[SecurityRelevant(RelevantLevel = SecurityRelevant.SecurityRelevant_Level1, IsRelevant = true)]

And then once I instanciate the class "IsRelevant", I will go through the properties and its classes and set the custom attribute as desired:
IsRelevant.Prop.No => IsRelevant = true,
eg IsNotRelevant.Prop.No => IsRelevant=false.
But as far as I understood the meta information (attributes) for a class is an instance created once for each type. So if I change the values of the custom attribute I will change it for all instances of that class (because it's bound to that type!?)
Edit: This can't be done as stated here: Change Attribute's parameter at runtime Everytime you access the custom attributes, a new instance with the default values will be created. Changes to that attribute won't be stored there.
A second approach was to store that information in an external class and save all the model paths etc. I don't like that because the information belongs to a specific class.
The third approach was to implement an interface which holds a dictionary which stores that information:
  public interface ISecRelevant
  {
    Dictionary<PropertyInfo, bool> SecInfo { get; set; }
  }

and then every class which has a security relevant property would need to implement it.
On every instantiation of that class, the information needs to be added in the dicationary. This is the best solution I came up with yet. The class which holds the information doesn't necessarily needs to be a dictionary because in a second step I want to ask an instance with a potential security relevant property if it really is relevant. So I could just pass that property in a method of that "security relevant information container" and ask if the property is relevant.
So I'm basically asking if someone has a better idea to store that information or to access it, because somehow I still don't like the solution.
So here are some general conclusions about that problem:

*

*The information whether a property is security relevant is not really a runtime information, but available upfront. So ideally I would like to store it in a "static" way

*The information is best to be attached to the property, at least to the parent class, because only it should know about that information, not any other class which uses that Info class to avoid coupling

*There are many more security relevant properties which are scatterd over a lot more classes. These are also used in a more deeper and complex object hierarchy, but I thought it basically comes down to the problem I described here.

Edit: Since I did not come up with a better idea, I implemented the third solution, but with a string for the property name. But then I stumbled into another problem when using Lists. What happens if you have a List as property with a type that has a sec-relevant property? The List would have to know where it is sitting to enable adding the information to every instance which is inserted in the List...
While searching I found another post, basicallay asks for the same thing: C# - add some meta data associated to a particular field when I am assigning a value to the field of a class?
He suggests to implement a base class which hold that kind of information. This will work for "normal" properties. But not for the list-case.
Further explanation and example:
I thought the example with "security relevant" was helping you guys to understand the problem, but maybe it just confused you. Simply said: I need to attach meta information a any property of a class (and also to the items which are maybe contained in a list). Where I need to put this information is known at design-time but is dependent on the instanciation of the classes. So it DOES matter who is instanciating the class. This is also the reason why I cant use static information.
Here is an example:
Class A {
  public int MetaProperty; // (this it the propert where i might want to add meta info)
}

Class B {
  public A ThePropertyWithMetadata;
}

Class C{
  public A TheProperty;
}

Whenever I create an instance of class B, I need to attach meta information to
InstanceOfB.ThePropertyWithMetadata.MetaProperty
On the other hand whenever I create an instance of class C, I DO NOT want to to attach any meta information to that property. I want to show that meta info in the user interface and give the user more information about that property.
So I do know when to assign the meta information, but cant put it in the classes at design time. Hope this clarifies it now :-)


text:
Q: Member template function. Why doesn't this compile? I whant to iterate in a member function over a list. In this code sample I am getting compiler error in for-line:

Expected ; before it, it not declared, end not declared.

Why?
The function is even not used in code!
template <class T> bool Settings::saveSimpleList( QString k, const T & l ){
    //...
    for ( T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it )
    {
        QString itemValue = QVariant( *it ).toString();
        //...
    }

    return true;
}

I see, I am missing something in template programming.
Thank you for your hints!

A: Do this:
for (typename T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it )
{
    QString itemValue = QVariant( *it ).toString();
    //...
}

When writing T::ConstIterator, the compiler can either interpret that as "the static member ConstIterator of type T" or as "the type defined as ConstIterator by a typedef in type T".
If your intent is the second, as here, you need to add typename to tell the compiler.

A: The compiler cannot know that T::ConstIterator is a type (because it does't know what T will be). You can indicate that by adding a typename in front of it.