text:
Q: Backbone view events do not fire I have a simple backbone view as follows:
/**
 * Renders a form view for an event object.
 */
APP.EventFormView = Backbone.View.extend({
    tagName: 'form',

    events: {
        'keydown': 'keyPressed',
        'focus input': 'inputChanged',
        'change select': 'selectChanged',
        'change textarea': 'textareaChanged'
    },

    initialize: function() {
        this.template = _.template($('#newevent-form').html());
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(APP.eventTypes, 'update', this.render);
        this.listenTo(APP.selectedEvent, 'update', this.render);
    },

    render: function() {
        var modelJSON = this.model.toJSON();
        if ('id' in modelJSON && modelJSON.id !== "") {
            this.loadForm();
        } else if (!('id' in modelJSON) || modelJSON.id === "") {
            this.loadForm();
        } else {
            this.$el.html('');
        }
        return this;
    },

    loadForm: function() {
        var templateData = $.extend(this.model.toJSON(),
            {"event_types":APP.eventTypes.toJSON()});
        this.$el.html('');
        this.$el.html(this.template($.extend(this.model.toJSON(),
                {event_types: APP.eventTypes.toJSON()})));
        $('.ev-main-container').html('').html(this.el);
    },

    inputChanged: function(e) {
        console.log('inputChanged');
    },

    selectChanged: function(e) {
        console.log('selectChanged');
    },

    textareaChanged: function(e) {
        console.log('textareaChanged');
    },

    keyPressed: function(e) {
        console.log('key pressed');
    }
});

I initialize this view as follows under document.ready:
// Initialize the form view
APP.selectedEvent = APP.selectedEvent || new APP.Event();
APP.eventFormView = new APP.EventFormView({model: APP.selectedEvent});
APP.eventFormView.render();

But none of the events I have defined are firing for some reason, What is it that I am doing wrong here ?
Update:
Ok, I fugred out if i remove $('.ev-main-container').html('').html(this.el); from the loadForm method and instead intialize the view as follows, it works:
APP.eventFormView = new APP.EventFormView({
    model: APP.selectedEvent,
    el: $('.ev-main-container'),
});

I was able to resolve it but I still don't understand why this happens, could anyone throw a little light on what's going on and how this works.

A: jQuery's html function has a side effect that many people seem to forget about, from the fine manual:

jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

Consider what that means when you do something like this:
container.html(view.el);
container.html(view.el);

Everything will be fine after the first container.html() call. But the second will "remove ... event handlers from child elements" (such as view.el) before adding the new content. So after the second container.html() call, all the events on view.el are gone. Sound familiar?
You have lots of things that will call render on your view and render will eventually do this:
$('.ev-main-container').html('').html(this.el);

Your events will silently disappear the second time that gets called but the HTML will look just fine.
Consider this simplified example (http://jsfiddle.net/ambiguous/otnyv93e/):
var V = Backbone.View.extend({
    tagName: 'form',
    events: {
        'click button': 'clicked'
    },
    initialize: function() {
        this.template = _.template($('#t').html());
    },
    render: function() {
        this.$el.html('');
        this.$el.html(this.template());
        $('.ev-main-container').html('').html(this.el);
        return this;
    },
    clicked: function() {
        console.log('clicked');
    }
});
var v = new V;
v.render();
$('#re-render').click(function() {
    v.render();
    console.log('Re-rendered');
});

and you'll see exactly your problem.
If you make the view's el the .ev-main-container then you'll be using html() to alter the contents of el rather than altering the contents of the element that contains el. Once you're working entirely inside the el you're no longer accidentally re-using an element and no longer accidentally removing the event bindings from that element.
My rules of thumb for preventing event problems with Backbone:

*

*Never attach views to existing DOM nodes, always let views create and own their own el and let the caller put that el in a container.

*Call remove on views to dispose of them when they're no longer needed.

*Don't try to re-use views, create them when you need them and remove them when you don't need them.

*No view references anything outside its el.

There are exceptions (of course) and this approach won't solve everything but it is a good starting point and avoids most of the common problems.


text:
Q: Sending POST Requests in Watin I am trying to do send a POST request on a web page with Basic Authentication. So is there any samples showing how to automate sending POST Requests in Watin

A: I found that this post works
IE _ie = new IE();
object flags = null;
object targetFrame = null;
object headers = "Content-Type: application/x-www-form-urlencoded" + Convert.ToChar(10) + Convert.ToChar(13);
object postDataBytes = ASCIIEncoding.ASCII.GetBytes("{ mydata: 5 }");
object resourceLocator = "http://google.com";
IWebBrowser2 browser = (IWebBrowser2)_ie.InternetExplorer;
browser.Navigate2(ref resourceLocator, ref flags, ref targetFrame, ref postDataBytes, ref headers);
_ie.WaitForComplete();

My document is a json response and I'm still working on getting access to its raw contents via WatiN - currently it is being prompted to download.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should jquery for pulling SQL tables be in my index.php file or make a seperate file? Currently I have a table from an SQL query in my index.php (see below code). I've seen some tutorials show them breaking up the HTML and PHP into 2 seperate files, while others keep them in one. Is the php code supposed to be in a separate file (ie. search.php) or does it not matter? Are there any benefits doing it either way? Thanks
//index.php

Item Overview

                                            Manufacturer
                                            Parent
                                            Catalog Number
                                            Description
                                            UOM
                                            Conversion
                                            Average Price
                                            Best Price

<?php
    require_once "db.php";
    if(isset($_GET['term']))
        {

        $term = '%' . $_GET['term'] . '%';
        $sql = "SELECT * FROM Main_Search WHERE SearchName LIKE ? LIMIT 10";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $term);
        $stmt->execute();
        $result = $stmt->get_result();
          while($row = $result->fetch_assoc()) {
            echo "" . $row["MFG_Simple"] . "	";
            echo "" . $row["Parent"] . "	";
            echo "" . $row["MFG_Item_ID"] . "	";
            echo "" . $row["Description"] . "	";
            echo "" . $row["UOM"] . "	";
            echo "" . $row["Conversion"] . "	";
            echo "" . "$ " . $row["Average_Price"] . "	";
            echo "" . "$ " . $row["Best_Price"] . "	";
"
";
             }

         }
         $conn->close();

?>


text:
Q: How to use value of STRING bean in html:hidden tag? I used request.addAttribute("myStrBean", "someStr"); now I want to use it in an  tag e.g. <html:hidden name="myStrBean"/>. Obviously that isn't working, what is the correct way to do this?

A: I don't know what you are trying to achieve but
if you want to get value from request you can use scriplet i.e.
<c:set var="myStrBean" value='<%=request.getAttribute("myStrBean")%>'/>

But to set data to struts html you should use the ActionForm
example
<html:hidden name="MyActionForm" property="myStrBean" />

Edit thanks to dave :
Using EL
<c:set var="myStrBean" value="${myStrBean}" />


text:
Q: tranfer file via bluetooth to iphone using 32feet I am trying to transfer a file to my iphone using 32feet bluetooth, but cannot seem to get past the ObexWebResponse.
I have read many post on this but none of the solutions seem to work for me.
The Error i get is
// Connect failed
// The requested address is not valid in its context "address:Guid"
    private BluetoothClient _bluetoothClient;
    private BluetoothComponent _bluetoothComponent;
    private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
    private BluetoothDeviceInfo _hlkBoardDevice;
    private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
    private BluetoothWin32Authentication _bluetoothAuthenticator;

    public BTooth() {
        _bluetoothClient = new BluetoothClient();
        _bluetoothComponent = new BluetoothComponent(_bluetoothClient);
        _inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
        _bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
        _bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);

        _bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
        _bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;

        ConnectAsync();

    }

    public void ConnectAsync() {
        _inRangeBluetoothDevices.Clear();
        _hlkBoardDevice = null;
        _bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
    }

    private void PairWithBoard() {
        Console.WriteLine("Pairing...");

        bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);

        if (pairResult) {
            Console.WriteLine("Success");
            Console.WriteLine($"Authenticated equals {_hlkBoardDevice.Authenticated}");
        } else {
            Console.WriteLine("Fail"); // Instantly fails
        }
    }

    private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e) { _inRangeBluetoothDevices.AddRange(e.Devices); }

    private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e) {
        for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i) {
            if (_inRangeBluetoothDevices[i].DeviceName == "Uranus") {
                _hlkBoardDevice = _inRangeBluetoothDevices[i];
                PairWithBoard();
                TransferFile();
                return;
            }
        }
        // no devices found
    }

    private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e) {
        e.Confirm = true; // Never reach this line
    }

    // not working
    // transfers a file to the phone
    public void TransferFile() {
        string file = "E:\\test.txt",
            filename = System.IO.Path.GetFileName(file);
        string deviceAddr = _hlkBoardDevice.DeviceAddress.ToString();
        BluetoothAddress addr = BluetoothAddress.Parse(deviceAddr);

       _bluetoothClient.Connect(BluetoothAddress.Parse(deviceAddr), BluetoothService.SerialPort);

       Uri u = new Uri($"obex://{deviceAddr}/{file}");
       ObexWebRequest owr = new ObexWebRequest(u);

       owr.ReadFile(file);
       // error:
       // Connect failed
       // The requested address is not valid in its context ...
       var response = (ObexWebResponse)owr.GetResponse();

       Console.WriteLine("Response Code: {0} (0x{0:X})", response.StatusCode);

       response.Close();

    }

The pairing and authentication works just fine, and I can get the BluetoothService.Handsfree to make a call for me but the transferring of the file fails.  Not knowing what the actual error is, I tried almost every service available with no luck.
Can you help me figure out what is going on?  This is my first attempt working with Bluetooth services so I still have a ton to learn.

A: Is it possible to transfer a file from iPhone to Windows desktop via Bluetooth?
However, in case you need to transfer media files (images, videos, etc) from Android device, you can use ObexListener class provided by 32Feet library for this purpose, and then you can simply call _obexListener.GetContext() method that will block and wait for incoming connections.
Once a new connection is received, you can save the received file to local storage, as shown in the below example:
ObexListener _listener = new ObexListener();
_listener.Start();

// This method will block and wait for incoming connections
ObexListenerContext _context = _listener.GetContext();

// Once new connection is received, you can save the file to local storage
_context.Request.WriteFile(@"c:\sample.jpg");

NOTE: When working with OBEX on Windows, make sure to disable the "Bluetooth OBEX Service" Windows service, in order not to let it handle the incoming OBEX requests instead of the desired application.

A: I walked away from this for a while. and started Trying to use xamiren but then had to create a virtual Mac so that I could have the apple store to just load software on my phone.  From there xamerin 'should' work well but its another field and tons more to firgure out.


text:
Q: Is it an expensive operation to create the IOS Core Data Model objects? I have been avoiding use of the IOS Core Data Model and now have a question of efficiency.  If I want to check the count of my table frequently and at random parts of my App.  I want to know if creating the context, entity, and fetch-request for this "count" method, like this, is light-weight or expensive.  If it is expensive, which ones can I set as properties and create-once or make as singletons, etc.  I fear that the dynamic nature of the Data Model could require fresh working objects.
-(NSInteger) count {
    NSManagedObjectContext *context = [[MdCoreDataModel sharedInstance] contextFortune];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName: @"MyTable" inManagedObjectContext: context];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entityDescription];

    NSError *error = nil;
    NSUInteger countTotal = [context countForFetchRequest: fetchRequest error: &error];

    if (error) {
        NSString *stringErrorMsg = [NSString stringWithFormat:@"%@\n%@", [error localizedDescription], [error localizedFailureReason]];
        NSLog(@"%s %@", __FUNCTION__, stringErrorMsg);
        countTotal = 0;

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Debug" message: stringErrorMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alertView show];
    }

    return countTotal;
}

A: As far as I know core data is very quick, the WWDC core data best practice videos provide info on this and how to use instruments to check speed etc.


text:
Q: How should sed global substitutions behave at end-of-line? Consider the sed program s/\(,\|$\)/-/g. When run on various inputs under GNU sed, it gives the following interactions which seem a bit inconsistent:

*

*The empty string -> -

*, -> -

*a -> a-

*a, -> a-

*,a -> -a-
Whether the $ part of the expression matches the end of the line seems to depend on whether the last match ended at the end of the line. My intuition says that the g flag should repeat the match from the end of the last replacement until the regex fails to match, in which case this program should always append an extra - to the line; but of course, my intuition doesn't necessarily match the POSIX specification.
Reading the POSIX manpage for sed, it says the following about the g flag to the s command:

Globally substitute for all non-overlapping instances of the BRE rather than just the first one. If both g and n are specified, the results are unspecified.

Whether the last , in the input "overlaps" with the EOL or not seems to be open to interpretation. Is there anything else that might clarify this? Is this behavior according to specification, or is it a bug in GNU sed?

A: As noted in comments, and then discussed more extensively in the chat…
The notation you're using (specifically, the \| to mean alternation) isn't specified by POSIX sed, so it isn't clear that it there's much to be said about what POSIX mandates.  It says, in part:

The sed utility shall support the BREs described in XBD Basic Regular Expressions.

That in turn says:

The interpretation of an ordinary character preceded by a <backslash> ('\\') is undefined, except for:
• The characters ')', '(', '{', and '}'
• The digits 1 to 9 inclusive (see BREs Matching Multiple Characters)
• A character inside a bracket expression.

This mainly means you can't appeal to POSIX for the required behaviour. I think that alternatives are evaluated left-to-right, but the $ context occurs after the comma. I briefly looked through your list and didn't see surprising behaviour. The first match on the line always wins, doesn't it?
I'm not sure exactly how it works, but I'd guess that the newline is removed from the line, then the substitution is done on the character before EOL, and the scan resumes but is at EOL, so it doesn't do anything more.
POSIX sed is probably expected to be implemented in terms of the POSIX regexec() etc functions.  You pointed out that the interpretation of the g-modifier is left to sed.  I suspect that it probably behaves more or less as I hypothesized.
In the chat, we also noted that:

*

*GNU sed has -r for using extended regular expressions, but they seemed to behave similarly (when the notation was changed accordingly).

*BSD and Mac OS X sed has -E for using extended regular expressions.

*Busybox sed appeared to work similarly, so the behaviour seems to be common across multiple implementations of sed.

*Using Mac OS X, we got unexpected behaviour for:
  $ echo ",a" | sed -E 's/(,|$)/-/g'
  -
  $

In the absence of a better hypothesis, we designated that as 'inexplicable' or 'possibly (probably?) buggy'.  There's no obvious reason for the a to go missing.

*Using Perl or Python might be a sensible option.


text:
Q: How to find matches faster with SpaCy Matcher? I'm trying to use the SpaCy Matcher package to detect matches whenever there is a passive voice in the sentences. I've written the pattern below and it finds the passive verbs and sentences correctly. Though my problem right now is with speed. I have around 1 million records and each record has around 10 sentences. I was wondering whether I can do anything to make the search a bit more efficient? Like not returning the end and start tokens?
The matcher:
matcher = Matcher(nlp.vocab)
passive_rule1 = [{'DEP':'nsubjpass', 'OP':'*'}, {'DEP':'xcomp', 'OP':'*'}, {'DEP':'aux','OP':'*'},{'DEP':'auxpass'}, {'DEP':'nsubj', 'OP':'*'}, {'TAG':'VBN'}]
passive_rule2 =  [{'DEP': 'attr'}, {'DEP':'det', 'OP':'*'}, {'Tag':'NOUN', 'OP': '?'}, {'TAG':'VBN'}]

matcher.add('passive_rule1',None, passive_rule1)
matcher.add('passive_rule2 ', None, passive_rule2)

Finding matches:
df.loc[:, 'PassiveVoice'] = df.Sentence.apply(lambda x:1 if len(matcher(nlp(x)))>0 else 0)

Or if there is any other thing anyone has in mind I'll be happy to hear!

A: Putting your 1 mln. texts into a pandas' dataframe and then calling nlp 1 mln times in a loop is a bad idea. Instead, put your documents in a list, via df["Sentence"].tolist(), and process them efficiently via nlp.pipe:
import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_md", disable=["ner"])

matcher = Matcher(nlp.vocab)
passive_rule1 = [
    {"DEP": "nsubjpass", "OP": "*"},
    {"DEP": "xcomp", "OP": "*"},
    {"DEP": "aux", "OP": "*"},
    {"DEP": "auxpass"},
    {"DEP": "nsubj", "OP": "*"},
    {"TAG": "VBN"},
]
passive_rule2 = [
    {"DEP": "attr"},
    {"DEP": "det", "OP": "*"},
    {"Tag": "NOUN", "OP": "?"},
    {"TAG": "VBN"},
]

matcher.add("passive_rule1", None, passive_rule1)
matcher.add("passive_rule2", None, passive_rule2)

texts = ["this is my first sentence. about something", "this is another"]
# texts = df["Sentence"].tolist()
docs = nlp.pipe(texts, n_process = 2, batch_size=50)

for doc in docs:
    if matcher(doc):
        #do something

In addition note, with nlp.pipe() you can turn multiprocessing on with n_process=2 (choose yours) and batch process your texts with batch_size=50 (choose yours).


text:
Q: Filter Pages by Custom Field (ACF) in admin area I'm trying to filter pages in admin area by a custom field created with ACF.
I found a function here ( http://www.iamabdus.com/blog/wordpress/filter-custom-posts-by-custom-field/ ) and I adapted that code to my need.
When I click on "pages" the options load correctly, but when I click on "Filter" even if the filter work good, I receive a Warning: "Invalid argument supplied for foreach()".
The var_dump($acf_field) return NULL.
I hope I explained the problem...
Here is the code:
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );

function wpse45436_admin_posts_filter_restrict_manage_posts(){
 $acf_field_name='field_5c65759c23c46';
 $acf_field=get_field_object($acf_field_name);
 var_dump($acf_field);
 $post_type_to_filter='page';
 $type = 'post';

 if (isset($_GET['post_type'])):
  $type = $_GET['post_type'];
 endif; // isset($_GET['post_type'])

 if ($post_type_to_filter == $type):
  foreach($acf_field['choices'] as $field_value => $field_label){
   $values[$field_label]=$field_value;
  }
  ?>
  <select name="custom_field_filter_value">
   <option value="">Filtra per tipo pagina</option>
   <?php $current_v = isset($_GET['custom_field_filter_value'])? $_GET['custom_field_filter_value']:'';
    foreach ($values as $label => $value) :
     printf(
      '<option value="%s"%s>%s</option>',
      $value,
      $value == $current_v? ' selected="selected"':'',
      $label
     );
    endforeach;
   ?>
  </select>
  <?php
 endif;
}

add_filter( 'parse_query', 'wpse45436_posts_filter' );
function wpse45436_posts_filter( $query ){
 global $pagenow;
 $type = 'post';
 if (isset($_GET['post_type'])):
  $type = $_GET['post_type'];
 endif;
 $query->query_vars['meta_value'] = $_GET['custom_field_filter_value'];
}

A: Try to use this code and modify the custom post name and meta key of acf and it will work.
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
/**
 * First create the dropdown
/** Create the filter dropdown */
function wpse45436_admin_posts_filter_restrict_manage_posts(){
    $type = 'movies'; // change to custom post name.
    if (isset($_GET['movies'])) {
        $type = $_GET['movies'];
    }

    //only add filter to post type you want
    if ('movies' == $type){
        //change this to the list of values you want to show
        //in 'label' => 'value' format
        $values = array(
            'label' => 'value1',
            'label1' => 'value2',
            'label2' => 'value3',
        );
        ?>
        <select name="ADMIN_FILTER_FIELD_VALUE">
        <option value=""><?php _e('Filter By ', 'wose45436'); ?></option>
        <?php
            $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
            foreach ($values as $label => $value) {
                printf
                    (
                        '<option value="%s"%s>%s</option>',
                        $value,
                        $value == $current_v? ' selected="selected"':'',
                        $label
                    );
                }
        ?>
        </select>
        <?php
    }
}

add_filter( 'parse_query', 'wpse45436_posts_filter' );
/**
 * if submitted filter by post meta

 * @return Void
 */
function wpse45436_posts_filter( $query ){
    global $pagenow;
    $type = 'movies'; // change to custom post name.
    if (isset($_GET['movies'])) {
        $type = $_GET['movies'];
    }
    if ( 'movies' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {
        $query->query_vars['meta_key'] = 'META_KEY'; // change to meta key created by acf.
        $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
    }
}

A: So I tried Pawan's answer and while it did work, it was applying the filter all over the place, not to the custom post types I wanted.  So I made a slight modification that should make this work:
public function filter_exhibitions($post_type, $which) {
  $target = 'exhibition'; // Created this target variable and removed the $_GET stuff

  if($post_type == $target) { // Test for correct post type
    $values = array(
      'Temporary' => 'temporary', // Add your own 'Label' => 'value' pairs here
      'Permanent' => 'permanent',
      'Online'      => 'online',
    );

    ?>
    <select name="ADMIN_FILTER_FIELD_VALUE">
      <option value=""><?php _e('All exhibition types', 'artlytical-media'); // Change this to the default null value display ?></option>
    <?php
    $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
    foreach ($values as $label => $value) {
      printf(
        '<option value="%s"%s>%s</option>',
        $value,
        $value == $current_v? ' selected="selected"':'',
        $label
      );
    }
    ?>
    </select>
    <?php
  }
}
add_action( 'restrict_manage_posts', 'filter_exhibitions' );

function exhibition_posts_filter($query){
  global $pagenow;

  if(is_admin()) {
    $type = $query->query['post_type'];
    $target = 'exhibition';

    if($type == $target &&
      $pagenow == 'edit.php' &&
      isset($_GET['ADMIN_FILTER_FIELD_VALUE']) &&
      $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') {
      $query->query_vars['meta_key'] = 'exhibition_type'; // Change to meta key created by acf
      $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
    }
  }
}

add_filter( 'parse_query', 'wpse45436_posts_filter' );


text:
Q: How to configure existing project to use polymer dart 1.0.0-rc.2? I created new polymer dart project with dependences:
dependencies:
  polymer: ^1.0.0-rc.2
  web_components: ^0.12.0
  polymer_elements: ^1.0.0-rc.1
  browser: ^0.10.0
  reflectable: ^0.3.1
dependency_overrides:
  polymer_interop:
    git:
      ref: 0.2.0-rc1
      url: https://github.com/dart-lang/polymer_interop.git

and everything worked fine (I can create new dom-module and use polymer elements). But then I tried to use exactly the same dependency configuration in existing project and when I run pub get I get:
Package reflectable has no versions that match >=0.3.1 <0.4.0 derived from:
- fbnn depends on version ^0.3.1
- polymer 1.0.0-rc.2 depends on version ^0.3.1
- polymer_elements 1.0.0-rc.1 depends on version ^0.3.1

I also try to do pub cache repair but it didn't help. Any ideas what might be wrong?


text:
Q: $http requests not working in signed apk Ionic when i run my cordova ionic app directly on android studio,it's working and send $http request perfectly.
but when i installed signed .apk,http requests doesn't work
Controller.js
var postObject = new Object();
postObject.User = $scope.data.username;
postObject.Secret = $scope.data.password;
  $http({
          url: 'https://example.com/',
          method: "POST",
          data: {
            'message': postObject
          }
        })
        .then(function(response) {
            $cordovaDialogs.alert('Success', 'Info', 'OK');
          },
          function(response) {
            $cordovaDialogs.alert('Error', 'Info', 'Error');
          });

Config.xml
 <?xml version='1.0' encoding='utf-8'?>
    <widget android-versionCode="1" id="com.example.abc" version="0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
        <name>Cordova project.</name>
        <description>
           Cordova project.
        </description>
        <author email="example@gmail.com" href="https://www.example.lk/">
          example
        </author>
        <content src="index.html" />
        <access origin="*" />
        <allow-intent href="*" />
        <allow-navigation href="*" />

      <engine name="android" spec="^6.2.3" />
        <plugin name="cordova-plugin-console" spec="^1.0.7" />
        <plugin name="cordova-plugin-device" spec="^1.1.6" />
        <plugin name="cordova-plugin-firebase" spec="^0.1.24" />
        <plugin name="cordova-plugin-splashscreen" spec="^4.0.3" />
        <plugin name="cordova-plugin-statusbar" spec="^2.2.3" />
        <plugin name="cordova-plugin-whitelist" spec="^1.3.2" />
        <plugin name="ionic-plugin-keyboard" spec="^2.2.1" />

why this happen?how can i solve this problem?

A: If the request is sent to a website with an invalid certificate the requests are dropped. This happens only for release built of your application. Check the SSL certificate and try again.


text:
Q: How to programmatically access {{ form.my_field.id_for_label }}? My Django project uses Bootstrap v4.
I iterate through all the fields to add the HTML attribute class="form-control". I also need to add an HTML attribute aria-describedby="{}Help" where {} is the id_for_label for the widget.
In the template language I could print that value easily with {{ form.my_field.id_for_label }} but programmatically I don't know how to do it.
I tried it with ModelForm().fields['…'].widget.id_for_label() but that method expects an argument. And by lookind at the Django source code, the return value is literally the argument.
Any ideas?
class AbonnentForm(ModelForm):
    class Meta:
        model = Abonnent
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(AbonnentForm, self).__init__(*args, **kwargs)

        # Add Bootstrap class to all <input> elements.
        for key, value in self.fields.items():
            value.widget.attrs.update({'class': 'form-control'})

            if value.help_text:
                id_for_label = "{}Help".format(value.widget.id_for_label())
                value.widget.attrs.update({'aria-describedby': id_for_label})

        self.fields['erste_ausgabe'].widget.attrs.update({'placeholder':'MM/JJJJ'})
        self.fields['letzte_ausgabe'].widget.attrs.update({'placeholder':'MM/JJJJ'})

A: You can contruct it yourself like this:
for key, value in self.fields.items():
     value.widget.attrs.update({'class': 'form-control'})

     if value.help_text:
         django_id_for_label = self.auto_id % key  # self.auto_id == 'id_%s'
         my_id_for_label = '{}Help'.format(django_id_for_label)
         value.widget.attrs.update({'aria-describedby': my_id_for_label})


text:
Q: linear spine interpolation of time-series by groups I am dealing with a time series of balance sheet of thousands of listed companies from 1990-2018. In some years I only have annual balance sheet while in other years I have 5 balance sheets, including 1 annual and 4 quarterly balance sheets. I am trying to use all information available. The date of balance sheet is always on xxxx-01-01/xxxx-03-31/xxxx-06-30/xxxx-09-30/xxxx-12-31. I select code number, date, long-term liability and short-term liability. I want to first calculate sum of long-term and short-term liability as a new column and do a linear spine interpolation of the new column by code number for each month. The date is in the form of month year.
code       date type           cl        ll
 1   1990-12-31    A     56280000         0
 1   1991-12-31    A     77230000         0
 1   1992-12-31    A    195893200         0
 1   1993-01-01    A            0         0
 1   1994-06-30    A            0         0
 1   1994-12-31    A            0         0
 1   1996-12-31    A            0         0
 2   1991-12-31    A    374334527   3500000
 2   1992-12-31    A    688472115  19820785
 2   1993-12-31    A   1135584690  70268722
 2   1994-12-31    A   1442120726  85175588
 2   1995-06-30    A   1571620470         0

I know how to do it when time interval is constant using splinefun and na.approx. But I have no idea how to deal with non-constant time intervals. Thank you!

A: I just got the desired result. The idea is from a similar question  https://stackoverflow.com/a/31383995/10714457 . One thing worth to notice is month column is in character form. I need as.numeric(month) to convert them to numeric first.
 DF$month <- format(as.Date(DF$date), "%m")
 DF$year <- format(as.Date(DF$date), "%Y")
 res <- setDT(DF)[, .SD[match(1:12, as.numeric(month))], by = .(year, code)]
 cols <- c("ll", "cl", "ncl")
 Interpolation <- res[, (cols) :=
 lapply(.SD, na.approx, na.rm = FALSE), .SDcols = cols]


text:
Q: Problemas com modelagem de dados com Persistence.xml Criei uma aplicação da faculdade para criar tabelas automáticas pelo Hibernate com JPA
porém deu erro em algumas tabelas, que foram essas;
CatalogDAO
OrderDAO
ProductDAO
porém esta gerando o seguinte erro,
quando eu clico em  CatalogDAO gera esse erro;
        catalog0_.CATALOG_ID=?
20:07:25.347 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
20:07:25.347 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
20:07:25.359 [main] DEBUG o.h.l.e.p.AbstractLoadPlanBasedEntityLoader - Done entity load : com.accenture.extremeex.domain.Catalog#1
Exception in thread "main" javax.persistence.EntityNotFoundException: Unable to find com.accenture.extremeex.domain.Catalog with id 1
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:181)
    at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262)
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.accenture.extremeex.domain.Catalog_$$_jvst9c4_9.getCatalogName(Catalog_$$_jvst9c4_9.java)
    at com.accenture.extremeex.dao.CatalogDAO.main(CatalogDAO.java:16)

quando tento executar essa classe OrderDAO gerra esse outro erro;
   (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
20:09:08.829 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (BILLED_AMOUNT, BILLING_INFO_ADDR_LINE_1, BILLING_INFO_ADDR_LINE_2, BILLIN' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_67]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_67]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_67]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_67]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.Util.getInstance(Util.java:382) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318) ~[mysql-connector-java-5.1.15-bin.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84) [hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789) [hibernate-core-4.3.6.Final.jar:4.3.6.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181) [hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
    at com.accenture.extremeex.dao.OrderDAO.salvar(OrderDAO.java:97) [classes/:na]
    at com.accenture.extremeex.dao.OrderDAO.main(OrderDAO.java:34) [classes/:na]
20:09:08.830 [main] WARN  o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 1064, SQLState: 42000
20:09:08.830 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (BILLED_AMOUNT, BILLING_INFO_ADDR_LINE_1, BILLING_INFO_ADDR_LINE_2, BILLIN' at line 1
20:09:08.831 [main] DEBUG o.h.j.spi.AbstractEntityManagerImpl - Mark transaction for rollback
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
    at com.accenture.extremeex.dao.OrderDAO.salvar(OrderDAO.java:97)
    at com.accenture.extremeex.dao.OrderDAO.main(OrderDAO.java:34)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
    ... 2 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order (BILLED_AMOUNT, BILLING_INFO_ADDR_LINE_1, BILLING_INFO_ADDR_LINE_2, BILLIN' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 23 more

e na classe ProductDAO gera esse erro;
20:10:32.217 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
20:10:32.217 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
20:10:32.236 [main] DEBUG o.h.l.e.p.AbstractLoadPlanBasedEntityLoader - Done entity load : com.accenture.extremeex.domain.Catalog#1
Exception in thread "main" javax.persistence.EntityNotFoundException: Unable to find com.accenture.extremeex.domain.Catalog with id 1
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:181)
    at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:262)
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.accenture.extremeex.domain.Catalog_$$_jvstb59_9.getCatalogID(Catalog_$$_jvstb59_9.java)
    at com.accenture.extremeex.dao.ProductDAO.salvar(ProductDAO.java:44)
    at com.accenture.extremeex.dao.ProductDAO.main(ProductDAO.java:25)

alguem pode me ajudas? as outras tabelas foram criadas menos essas classe
o código está aqui.
https://github.com/wladyband/extreme/tree/master/ExtremeEX

A: A causa do erro nas classes "CatalogDAO" e "ProductDAO" é a mesma: Unable to find com.accenture.extremeex.domain.Catalog with id 1. Na tabela "catalog" não existe nenhum registro com CATALOG_ID igual à 1.
A causa do erro na classe "OrderDAO" é o nome da tabela "order", pois "order" é uma palavra reservada do SQL. Você pode renomear a tabela ou usar "order" entre aspas duplas. Neste segundo caso altere a anotação na classe "Order" para:
@Entity(name="\"order\"")


text:
Q: Cannot Center Popover Swift I am trying to make a popover that will allow users to swipe between images (is there a better approach to this than using a popover?).
Right now to make the popover, I have spend hours googling on simply how to make a rectangle center in the screen. From the internet my code is:
    // get a reference to the view controller for the popover
    let popController = UIStoryboard(name: "Event", bundle: nil).instantiateViewController(withIdentifier: "carouselPopover")

    // set the presentation style
    popController.modalPresentationStyle = UIModalPresentationStyle.popover

    let width = view.frame.width
    popController.preferredContentSize = CGSize(width: width, height: 300)
    // set up the popover presentation controller
    popController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.up
    popController.popoverPresentationController?.delegate = self
    popController.popoverPresentationController?.sourceView = self.view
    popController.popoverPresentationController?.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
    popController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)

    // present the popover
    self.present(popController, animated: true, completion: nil)

However, for the life of me I cannot understand why the popover is not centered
It only loses its center when I set the popController's preferred content size. Any thoughts?
TL:DR
I want to 1) center the popover on the screen, 2) Make the popover 1:1 ratio, and 3) make the width of the popover proportional to the width of the parent screen. How can I do that without 1000's lines of code.

A: You can create a custom popover class. Then you establish delegate patterns to determine if user swipes.
protocol PopoverDelegate: class {
  func imageviewDidSwipe(_ popover: Popover)
}

class Popover: UIView {

weak var delegate: PopoverDelegate?

  init(frame: CGRect) {
   super.init(frame: frame)
   backgroundColor = UIColor.white
  }

  func setupImage(_ image: UIImage) {
    let imageView = UIView(frame: CGRect.zero)
    imageView.image = image
    self.addSubview(imageView)

    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    imageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 50).isActive = true // However big you want
    imageView.widthAnchor.constraint(equalToConstant: 50).isActive = true // However big you want
  }

  func showPopover(over view: UIView) {
    view.addSubview(self)
    translatesAutoResizingMaskIntoConstraints = false
    centerXAnchor.contraint(equalTo: view.centerXAnchor).isActive = true
    centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    heightAnchor.constraint(equalToConstant: frame.height).isActive = true
    widthAnchor.constraint(equalToConstant: frame.width).isActive = true
 }

}

To use...
class vC: UIViewController {

  func ImageOnClick() {
   // change view to where you want popover to show on top of
   let popover = Popover(frame: view.frame)
   popover.setupImage(image.png)
   popover.delegate = self
   showPopover(over: view)
  }

}

extension vC: PopoverDelegate {
  func imageviewDidSwipe(_ popover: Popover) {
    // image swiped
  }
}


text:
Q: How to return specific info when a user uses CURL? I am trying to figure out how to return a specific piece of information when a user uses cURL on one of my web pages(i.e. I don't want curl to download all code). I've seen a working example of this on ifconfig.me, when you curl ifconfig.me it returns only your IP address. Is this done with Apache and redirecting the cURL user-agent or accomplished somehow through PHP/HTML?
Solved:
Thanks to @Dancrumb for pointing me in the right direction. I was able to use Apache mod_rewrite to redirect curl user-agents to a custom page with the specific information I wanted curl to pull.
RewriteEngine  on
RewriteCond %{HTTP_USER_AGENT}  ^curl/*
RewriteRule ^/index\.php$ /ip.php [L]

A: ifconfig.me, most likely, uses the User Agent string, in the header, to figure out that this is not a browser request.
If you execute:
curl ifconfig.me/ua

you get
curl/7.27.0

(or some other version string).
So, if you check the User-Agent header in the HTTP request, you can see if the request is a Curl request, a browser request or some other UA.


text:
Q: http java call which goes wrong I have a java application on Weblogic 12, i make an https call to a SAP server in REST (GET e basic authentication), everything works for 30/45 minutes but after i have "503: Service Unavailable". If I call this service from browser it always works.
HttpURLConnection  conn = (HttpURLConnection) new URL( url.toString()).openConnection();
    conn.setRequestProperty("Authorization", "Basic " + authUserEnc);
    ... //read the response stream
    conn.disconnect();

this is the error
java.io.FileNotFoundException: Response: '503: Service Unavailable' for url: 'https://fwp-as3.enelint.global:44331/sap/opu/odata/sap/ZFIOI_O1_Q006_SRV/ZFIOI_O1_Q006(ZVAR_VDMCUI_OI_M='0000022077',ZVAR_VDMCUI_OI_MTo='0000022077')/Results?saml2=disabled'
        at weblogic.net.http.HttpURLConnection.getInputStream(HttpURLConnection.java:829)
        at weblogic.net.http.SOAPHttpsURLConnection.getInputStream(SOAPHttpsURLConnection.java:42)
        at it.exprivia.bexboard.service.impl.VendorServiceImpl.getData(VendorServiceImpl.java:125)
        at it.exprivia.bexboard.controller.GrafxController.getVendorGrafxById(GrafxController.java:166)
        at sun.reflect.GeneratedMethodAccessor211.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:181)
        at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:97)
        at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:202)
        at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:101)
        at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
        at ...


text:
Q: Spring Boot: send response header based on result I have following controller in a Spring Boot application which accept and return a binary stream. I need to accept a steam, encrypt it and at the same time return the result. This streams can be pretty large and cannot be held in memory:
    @PostMapping(value = "/encrypt-stream/", consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void encryptStream(HttpServletRequest request, HttpServletResponse response){

        OutputStream os = response.getOutputStream();
        InputStream is = request.getInputStream();

        String checksum = encryptionService.encrypt(is, os);

        response.setHeader("checksum", checksum);
    }

I need to send the a header (checksum) based on the result of the service call (encryptionService.encrypt()) within the controller.
Setting header on HttpServletResponse is not working.
I have looked at implementing Filter class however it only works when you set the header before .doFilter() call. My issue is the header value is calculated after.
Also, same issue with implementing a HandlerInterceptorAdapter.

A: I think HTTP might be a bad choice for a streaming encryption server. The protocol is at its core REQUEST then RESPONSE and is not designed for the use case where you might start returning response before the request has finished.  There are exceptions for early returned error codes but support for this behavior looks spotty.
HTTP Response before Request


text:
Q: Swift: Using custom accessoryType for cell freezes UI and 99% CPU Usage I'm trying to use a custom accessory type (UIImage) for my tableview cell which has a expand/collapse functionality. When user taps a cell the row expands or collpases if parent is tapped again.
The imageview I'm using to set the accessory type is below:
var expandIcon : UIImageView?
expandIcon  = UIImageView(frame:CGRectMake(0, 0, 16, 16))
expandIcon!.image = UIImage(named:"expand")

Following code is when user taps a row which if its parent it should epxand or if its already expanded it will collapse.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellData = dataForCellAtRowIndex[indexPath.section]!.rows[indexPath.row]
    var cell:UITableViewCell!

    if isParentCell(indexPath.row) == true {
        cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        cell.textLabel?.text = "test" + String(indexPath.row)
        cell.detailTextLabel?.text = "detail"
        cell.backgroundColor = UIColor.whiteColor()
        cell.accessoryView = expandIcon

    }else{
        cell = tableView.dequeueReusableCellWithIdentifier("childCell", forIndexPath: indexPath)
        cell.backgroundColor = UIColor.lightGrayColor()
        cell.textLabel?.text = "child name"
        cell.detailTextLabel?.text = "child detail"
        cell.accessoryType = UITableViewCellAccessoryType.None
    }

    return cell
}

The bit that is causing the problem is cell.accessoryView = expandAccessory which causes the UI to freeze and cpu usage goes to 99% as reported by xcode. if i remove cell.accessoryView = expandIcon everything is fine! Why is this happening?

A: You should implement a function to return an expandIcon and then call it in place of expandIcon variable.
func expandImageView() -> UIImageView {
    let expandIcon  = UIImageView(frame:CGRectMake(0, 0, 16, 16))
    expandIcon.image = UIImage(named:"expand")
    return expandIcon
}

cell.accessoryView = expandImageView()

A: The fix for this as @rmaddy mentioned was the reuse of UIImage view which was causing the UI freeze. Creating a new UIImage for each cell fixed my problem so instead of:
if isParentCell(indexPath.row) == true {
    cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    cell.textLabel?.text = "test" + String(indexPath.row)
    cell.detailTextLabel?.text = "detail"
    cell.backgroundColor = UIColor.whiteColor()
    cell.accessoryView = expandIcon

}

i had to :
if isParentCell(indexPath.row) == true {
    cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    cell.textLabel?.text = "test" + String(indexPath.row)
    cell.detailTextLabel?.text = "detail"
    cell.backgroundColor = UIColor.whiteColor()

    //put the below two lines in a func and return a UIImage
    let expandIcon  = UIImageView(frame:CGRectMake(0, 0, 16, 16))
    expandIcon.image = UIImage(named:"expand")

    cell.accessoryView = expandIcon

}


text:
Q: SQL DMV linking Index Usage to Stored Procedure Usage I'm auditing & cleaning some SQL 2008 R2 Boxes.
I'm doing a lot of work with:
sys.dm_db_index_usage_stats (Index usage)

sys.dm_exec_procedure_stats (Procedure usage)

These DMVs provide a lot of good performance information.
What I need is a way of linking the results together. i.e. How do I figure out which Stored Procedures are using which indexes?
I've been shredding the XML in the plan cache, but this is very inefficient, does anybody have a better solution?

A: Use system reports.
In Management studio right click on server or specific database. Select Reports and then Standard reports and select Object execution statistics.
I'm sure you are able to catch queries (if it's necessary) with SQL Server Profiler.


text:
Q: XML parsing and display in JTabbedPane I am newbie to java I have parsed XML now I have to display it in respective JTabbedPane.  I have error on attribute object on start element method.
Where am I going wrong?
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

public class JTabbedPaneDemo extends JPanel {

     /*static String[] nameatt= {" sv_machineData "," Mould_data "," Core_1 "," Core_2 "};*/

    public JTabbedPaneDemo() {
    //  ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG");

        JTabbedPane jtbExample = new JTabbedPane();

        // Create First Tab.
        JPanel jplInnerPanel1 = createInnerPanel();
        jtbExample.addTab(" Sv_Machine_Data ", jplInnerPanel1);
        jplInnerPanel1.setLayout(new BorderLayout());
        JTable table1 = new JTable(5,3);
        JScrollPane tableContainer = new JScrollPane(table1);
        jplInnerPanel1.add(tableContainer,BorderLayout.CENTER);

        //jtbExample.setSelectedIndex(0);

        // Create Second Tab.
        JPanel jplInnerPanel2 = createInnerPanel();
        jtbExample.addTab(" Mould_data ", jplInnerPanel2);
        jplInnerPanel2.setLayout(new BorderLayout());
        JTable table2 = new JTable(5,3);
        JScrollPane tableContainer1 = new JScrollPane(table2);
        jplInnerPanel2.add(tableContainer1,BorderLayout.CENTER);

        // Create Third Tab.
        JPanel jplInnerPanel3 = createInnerPanel();
        jtbExample.addTab(" Core_1 ", jplInnerPanel3);
        jplInnerPanel3.setLayout(new BorderLayout());
        JTable table3 = new JTable(5,3);
        JScrollPane tableContainer3 = new JScrollPane(table3);
        jplInnerPanel3.add(tableContainer3,BorderLayout.CENTER);

        // Create Fourth Tab.
        JPanel jplInnerPanel4 = createInnerPanel();
        jtbExample.addTab(" Core_2 ", jplInnerPanel4);
        jplInnerPanel4.setLayout(new BorderLayout());
        JTable table4 = new JTable(5,3);
        JScrollPane tableContainer4 = new JScrollPane(table4);
        jplInnerPanel4.add(tableContainer4,BorderLayout.CENTER);

        // Add the Tabbed Pane to this panel.
        setLayout(new GridLayout(1, 1));
        add(jtbExample);
    }

    protected JPanel createInnerPanel() {
        JPanel jplPanel = new JPanel();
        JLabel jlbDisplay = new JLabel();
        jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
        jplPanel.setLayout(new GridLayout(1, 1));
        jplPanel.add(jlbDisplay);
        return jplPanel;
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame("TabbedPane Source Demo");
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        /*final JTabbedPaneDemo xm = new JTabbedPaneDemo();*/

        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

        boolean bfname = false;
        boolean blname = false;
        String nameAttribute;

        public void startElement(String uri, String localName,String qName, Attributes attributes)
        throws SAXException {

            if (qName.equalsIgnoreCase("TYP")) {
                bfname = true;
                }

            nameAttribute = attributes.getValue("Name");

            if (qName.equalsIgnoreCase("VALUE")){
                blname = true;
                }
        }
        public void characters(char ch[], int start, int length)
        throws SAXException {

            if (bfname) {
                System.out.println("Type : "+ new String(ch, start, length));
                String vtype = new String(ch, start, length);
                /*xm.textArea.append(vtype+"\n");*/
                bfname = false;
                }

            if (nameAttribute != null && !nameAttribute.equals("")) {
                System.out.println("Name : " + nameAttribute);
                /*vname+=nameAttribute+ ", " +"\n";
                xm.textArea_3.setText(vname);
                */}

            if (blname) {
                String vvalue = new String(ch, start, length);
                System.out.println("Value:" + Double.valueOf(vvalue));
                /*xm.textArea_1.append(Double.valueOf(vvalue)+"\n");*/
                blname = false;
                }
        }
        };

        saxParser.parse(new File("C:"path of xml file".xml"), handler);
        }
        catch (Exception e) {
        e.printStackTrace();
        }
        frame.getContentPane().add(new JTabbedPaneDemo(),BorderLayout.CENTER);
        frame.setSize(400, 500);
        frame.setVisible(true);
    }
}

Below is sample XML
<?xml version="1.0" encoding="UTF-8"?>
<HMI_Data Version="1.0" MaschinenNR.="XXXXXX" Date="21-10-2009">
   <VarGroup Name="VG_MachineData">
      <Variable Name="Mold1.sv_rMoldStroke">
         <Typ>REAL</Typ>
         <Value>6.000000e+02</Value>
      </Variable>
      <Variable Name="Core1.sv_rMaxSpeedFwd">
         <Typ>REAL</Typ>
         <Value>5.000000e+01</Value>
      </Variable>
      <Variable Name="Core1.sv_rMaxSpeedBwd">
         <Typ>REAL</Typ>
         <Value>5.000000e+01</Value>
      </Variable>
      <Variable Name="Core1.sv_rMaxPressureFwd">
         <Typ>REAL</Typ>
         <Value>1.450000e+02</Value>
      </Variable>
      <Variable Name="Core1.sv_rMaxPressureBwd">
         <Typ>REAL</Typ>
         <Value>1.450000e+02</Value>
      </Variable>

A: Around 20 seconds with the JavaDcos suggests that:
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

Should be:
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;  // import it!
import org.xml.sax.helpers.DefaultHandler;


text:
Q: Wordpress AMP plugin eror: The attribute 'type' may not appear in tag 'style amp-custom' Wordress uses AMP plugin. Currently getting error The attribute 'type' may not appear in tag 'style amp-custom'.
When opening up the page and visiting console, the error points to the style attribute type.

This section of code comes from the index page. How would I go about changing this? Where can I change the wordpress code? Is this a theme error and therefore would I need to contact the theme developer?

A: Here's an example
      <!doctype html>

        <meta charset="utf-8">
        <title>Hello, AMPs</title>
        <link rel="canonical" href="http://example.ampproject.org/article-metadata.html" />
        <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

Welcome to the mobile web


text:
Q: Function that returns three highest value in row in R I have two sets of data frames and I am trying to create a function which takes in a data frame and row name as an argument and returns the three highest value on the row (in a descending order) and the name of the column of three highest value.

    set.seed(0)
    df <- data.frame(A=c(3,2,1,4,5),B=c(1,6,3,8,4),C=c(2,1,4,8,9), D=c(4,1,2,4,6))
    row.names(df)<-c("R1","R2","R3","R4","R5")

    df2 <- data.frame(E=c(2,5,6,1,4),F=c(2,4,2,5,1),G=c(5,6,2,7,3),H=c(8,2,7,4,1))
    row.names(df2)<-c("R6","R7","R8","R9","R10")

    print(df)

       A B C D
    R1 3 1 2 4
    R2 2 6 1 1
    R3 1 3 4 2
    R4 4 8 8 4
    R5 5 4 9 6

    print(df2)

        E F G H
    R6  2 2 5 8
    R7  5 4 6 2
    R8  6 2 2 7
    R9  1 5 7 4
    R10 4 1 3 1

Here is an example of a result:
Let the function be maxthree. Now

    maxthree(df2, "R7")

    G E F
    6 5 4

Here is what I have done so far:

    maxthree <- function(data,row) {
      if(!row %in% rownames(data)) {
        print("Check value")
      } else {
        max_col <- which.max(data[row,])
        print(max_col)
      }
    }

This function will now return the maximum value in that row as well as the column name. However, I don't now how to add the second and the third highest values to the function.

A: maxthree = function(data, row) {
  data[row, order(unlist(data[row, ]), decreasing = TRUE)[1:3]]
}

maxthree(df2, "R7")
#    G E F
# R7 6 5 4

The result is a 1x3 data frame.

A: This should work great
maxthree <- function(data,roww){
    x <- data[roww,]
    x[order(x, decreasing = T)][1:3]
}

>  maxthree(df2, "R7")
   G E F
R7 6 5 4

A: Try this:
df <- data.frame(A=c(3,2,1,4,5),B=c(1,6,3,8,4),C=c(2,1,4,8,9), D=c(4,1,2,4,6))
row.names(df)<-c("R1","R2","R3","R4","R5")

df2 <- data.frame(E=c(2,5,6,1,4),F=c(2,4,2,5,1),G=c(5,6,2,7,3),H=c(8,2,7,4,1))
row.names(df2)<-c("R6","R7","R8","R9","R10")

maxthree <- function(data,row) {
  named_vec <- t(data)[,row]
  return(sort(named_vec, decreasing = T)[1:3])
}

maxthree(df2, "R7")

# G E F
# 6 5 4

This approach transposes your data frame "t()" to allow a straightforward subset of the row as a named vector. This allows sort to be used to order the values as desired.

A: You can use sort and [1:3]  to get the first 3 elements like:
maxthree <- function(data,row) {sort(data[row,], TRUE)[1:3]}
maxthree(df2, "R7")
#   G E F
#R7 6 5 4

In case the rowname should not be shown you can add unlist:
maxthree <- function(data,row) {head(unlist(sort(data[row,], TRUE)),3)}
maxthree(df2, "R7")
#G E F
#6 5 4

A: You can use the order function.
maxthree <- function(data, row_name) data[row_name, order(-data[row_name,])][, 1:3]
maxthree(df2, 'R7')
   G E F
R7 6 5 4


text:
Q: higher cpu usage in ubuntu 12.04 than windows 7 Hi I have a Intel Core i5 with 6GB of Ram using ubuntu 12.04 64bit.
I noticed that whenever I run chrome which is the faster browser for me in linux)  when I watch youtube, the CPU usage for Chrome is at least 13% and sometimes even 30% .
but in Windows 7 same thing (youtube on chrome)  rarely uses more than 6% of my CPU usage.
I also notice my laptop is so hot in ubuntu 12.04 and the fan is working all the time, while in windows the laptop is so silent and the fan doesnt make much noise all the time and not as warm as in linux.
is it like that for every one or is it just me?

A: Yes, flash is bad.
You can switch to HTML 5 Videos in Youtube: Go to the bottom -> "Try something new" and choose to be in the HTML 5 Beta.
Videos will work much faster because of better hardware acceleration and no flash

A: Flash in Windows probably uses hardware acceleration so the movie decoding is really being done by the GPU and not your processor. Under Linux, it's all processor unless you are fortunate enough to run a working Flash that lets your system use the GPU.
Try Google Chrome as it uses the pepper flash project and currently sits on Flash 11.3 which works well on my system for hardware accelerated videos on YouTube.

A: *

*Navigate to the Find Flash Player Version page.

*Verify that you are in the section titled "Find Flash Player version type and capabilities (Flash developers only)"

*Right click on your Player version and select "Settings"

*The Settings dialog will appear, change the tab at the bottom to display (if not already there) and uncheck (or if you'd like to enable, check) the "Enable hardware acceleration" checkbox.

*Close the dialog and restart your browser.


text:
Q: How to customise the Button on UIActionSheet? I want to change width & height, etc. of the button of UIActionSheet
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@**"Done"**,nil];

A: I would suggest against doing this.  The button sizes and shapes in a UIActionSheet are designed the way they are for accessibility reasons.  They are also consistent across all applications on the platform, so users are familiar with them.  From the iPhone Human Interface Guidelines:

Because users are accustomed to the
  appearance and behavior of these
  views, it's important to use them
  consistently and correctly in your
  application.

If you change these sizes, not only might you make your application less usable, but that may violate Apple's Human Interface Guidelines, leading to a rejection of your application when submitted.

A: You can create your own actionsheet analog.


text:
Q: Switch isn't working "as expected" with numbers I've researched this is a little bit. Still curious as to why switch doesnt work with number values. Or doesn't work "as expected".

let vw = window.innerWidth;

switch(vw) {
  case vw >= 1500:
    console.log('Large Desktop');
    break;
  case vw >= 1024 && vw <= 1499:
    console.log('Desktop');
    break;
  default:
    console.log('Mobile || Tablet');
    break;
}

I'm aware that I could simply use an if/else statement. Just personally like to use switch statements with conditionals that typically have more than 3 argument checks.
Thanks in advance.

A: It is working as expected: cases compare to the value you input to the switch statement. Window width is a number. So you're comparing a number to true/false.
Switch on true if you want to do what you're doing.


text:
Q: Core data multithreading issues I have implemented core data in Multithread environment, I have some doubt and issue related to it which I am listing down below:-

*

*Several blogs and SO answers are saying you should have single NSPersistentStoreCoordinator(PSC) but as per my understanding, 'PSC' should be equal to the number of ManagedObjectModel. Please correct me if I am wrong.

*As per doc, the ManagedObjectContext objects should be equal to the number of threads we are creating to perform the activity in a particular model. To my surprise, I have used a single ManagedObjectContext object from different threads and performing fetching action simultaneously without any crash, please find the code below:-
I am calling the function below from different threads and making sure only a single instance of MOC is created. Please clear all the above doubts I have
func fetchUserDetail(productId : Int) -> User_Details?  {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User_Details")
    do {
        fetchRequest.predicate = NSPredicate(format: "product_id == %d", productId)

        let results:[User_Details]? = try (singleinstancemanagedObjectContext.fetch(fetchRequest) as? [User_Details])

        if let results = results {
            ..... logic .....
        }
    } catch let error as NSError {
    }
    return nil

}

A: *

*An "NSPersistentStoreCoordinator" can only handle one NSManagedObjectModel. You are right here. But having multiple "NSPersistentStoreCoordinator" requires multiple "NSManagedObjectModel"s(.xcdatamodeld files). This case is very rare.

*Concurrency crashes are elusive by nature. They only happen when multiple threads access the same data at the same time with nano second precision. These are hard to debug bugs that usually occur in production when 100s of users using the app. The last thing you want to say to a user is we have lost all your data(got corrupted or crashed whatever). So you are better off listening to the documentation here. We did the same mistake of passing NSManagedObjects between different threads in one of our old apps and paid the price. It took long time to refactor the code. At last from Core Data Programming Guide link.

The NSPrivateQueueConcurrencyType configuration creates its own queue
  upon initialization and can be used only on that queue. Because the
  queue is private and internal to the NSManagedObjectContext instance,
  it can only be accessed through the performBlock: and the
  performBlockAndWait: methods.

Here is another from the same page,

NSManagedObject instances are not intended to be passed between
  queues. Doing so can result in corruption of the data and termination
  of the application. When it is necessary to hand off a managed object
  reference from one queue to another, it must be done through
  NSManagedObjectID instances.


text:
Q: how to use session in expressjs view file (.pug) i have tried to use session variable in expressJs view file(.pug) but its not directly used.
i was also tried locals but its clear on page reload or redirect
my code is below
userLogin(data.email,data.password).then(function(result) {
          if(result){
            req.session.login = true; //use in view file
            res.redirect('products');
          }else{
            res.render('login',{msg:'Invalid Creadential !'})
          }
      });

and tried code in .pug file
 if(login)
          li
            a(href='logout') Logout

A: You can use express-dynamic-helpers-patch, then you can create a dynamicHelper as follows :
require('express-dynamic-helpers-patch')(app);
app.dynamicHelpers({
session: function (req, res) {
    return req.session;
    }
});

then in your view you can acess session object directly :
if(session.login)
      li
        a(href='logout') Logout


text:
Q: Stack: How to depend on a package during development? There is a portion of my application that would be better if published to Hackage. I still don't know exactly what it will look like, so I need to make many changes to it while working on my application.
It's very easy to just create a module in my project and iterate there, but I would like to put it in its own project so it can have its own dependencies.
How can I have my project depend on this separate package during development? It should allow for quick iteration. Here's what I tried so far:
# stack.yaml
packages:
- '.'
- location: ../amqp-worker

# my-application.cabal
library
  build-depends:
      base >= 4.7 && < 5
    , amqp-worker

But I get an error when I build:
$ stack build
cra-reporting-0.1.0.0: build

--  While building package cra-reporting-0.1.0.0 using:
      /Users/seanhess/.stack/setup-exe-cache/x86_64-osx/setup-Simple-Cabal-1.24.0.0-ghc-8.0.1 --builddir=.stack-work/dist/x86_64-osx/Cabal-1.24.0.0 build lib:cra-reporting exe:cra-reporting-exe --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1
    Logs have been written to: /Users/seanhess/projects/simple/cra-reporting/.stack-work/logs/cra-reporting-0.1.0.0.log

    Preprocessing library cra-reporting-0.1.0.0...
    [8 of 8] Compiling Simple.DataX.Worker ( src/Simple/DataX/Worker.hs, .stack-work/dist/x86_64-osx/Cabal-1.24.0.0/build/Simple/DataX/Worker.o )

    /Users/seanhess/projects/simple/cra-reporting/src/Simple/DataX/Worker.hs:6:1: error:
        Failed to load interface for 'Network.Worker'
        Perhaps you meant
          Network.Socket (needs flag -package-key network-2.6.3.1)
          Network.Wreq (from wreq-0.4.1.0)
          Network.Socks5 (needs flag -package-key socks-0.5.5)
        Use -v to see a list of the files searched for.

The external package seems to build fine if I run stack build from within its project folder.
Both projects are targeting lts-7.3

A: The above example should work. I attempted this again from scratch and it works fine. The error was due to some kind of build artifact.
If it happened again I would delete .stack-work in the sub-project and rebuild.


text:
Q: Rotating a Bitmap around a point NOT center to bitmap I have a bitmap that I would like to rotate about a point on a canvas. The point I want to rotate it about is not the center of the bitmap. I am using a matrix. Here is an example of what I have.
    Bitmap image = ContentManager.getInstance().getImage(imageId);
    Matrix matrix = new Matrix();
    matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f);
    matrix.postRotate(rotationDegrees);
    matrix.postTranslate(x / scaleX, y / scaleY);
    matrix.postScale(scaleX, scaleY);
    paint.setAlpha(alpha);
    canvas.drawBitmap(image, matrix, paint);

I want to manipulate this code slightly to not rotate around the bitmap's center point but a different point. To illustrate more clearly I have created this picture:

.
I have tried everything I can think of from setting
    matrix.setTranslate(-image.getWidth()/2f, -image.getHeight()/2f);

to
    matrix.setTranslate(pivotPoint.x, pivotPoint.y);

and a lot of other stuff. The result is the bitmap is always way off from where I expected it. (eg. rotate it about the center of the screen 90 degrees would put the bitmap 90 degrees from where it was and consequently would be rotated.) The bitmap always seems to rotate about its center point and then ends up in a random spot on the screen.

A: When rotating an object, it will rotate around the origin (upper left corner). You'll want to first translate the bitmap so the pivot point becomes (0, 0), rotate the bitmap then translate back to it's original position.
you could try something like this:
matrix.setTranslate(-px, -py);
matrix.postRotate(rotationDegrees);
matrix.setTranslate(px, py);
// Then do other things.

A: After much messing around and find this very difficult or buggy, not sure which, found the easiest solution to this is to find the new center of the bitmap and drop the image there instead, seem more complicated but it works where plain rotation/translation wasn't.
  float angle;
  float radius;

  Bitmap wheelSelectBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
  Matrix matrix = new Matrix();

  Point pivotPoint = new Point();
  pivotPoint.set(pivotPoint.x, pivotPoint.y)
  Point newCenter = new Point();
  newCenter.set((int)(pivotPoint.x + (radius * Math.cos(angle)), (int)(pivotPoint.y - (radius * Math.sin(angle)));

  matrix.postTranslate(newCenter.x - (bitmap.getWidth()/2f), newCenter.y - (bitmap.getHeight()/2f));
  matrix.postRotate(angle, newCenter.x, newCenter.y);

  Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), null, true);
  canvas.drawBitmap(bitmap, matrix, null);

This might not be perfect but working this way solved the problem for me and stopped bitmaps flying around all over the shop. It also rotates clockwise by default unlike your diagram so just use -angle for counter-CW. Not sure what is going on here as this code definitely failed to get the desired effect for me:
 matrix.postTranslate(pivotPoint.x, pivotPoint.y);
 matrix.postRotate(angle);
 matrix.postTranslate(radius - (bitmap.getWidth()/2f), -bitmap.getHeight()/2f);

Cant see what is wrong with logic here ? But in my case the bitmap was not visible in the view here.


text:
Q: Check users in a security group in SQL Server In the Security/Users folder in my database, I have a bunch of security groups, include "MyApplication Users". I need to check if I am (or another user is) in this group, but I have no idea how to query for it or where I could see this information. I tried looking in the properties, but couldn't find anything. Any ideas?

A: To find the AD Group members in the Instance, we can use below query:
xp_logininfo 'DomainName\AD_GroupName', 'members'

By using this query, we can find the below states.
account name, type, privilege, mapped login name, permission path

A: Accepted answer from DeanG is the preferred solution for getting this info within SQL Server

You can use Active Directory tools for this. I like Active Directory Users and Computers that is part of the Remote Server Administration Tools. Follow the link to download and install the tools on Windows 7.
Once installed, you can search for a specific group name:

Then you can see group membership using the Members tab:

If you don't want to use the AD browser packaged with RSA tools, there are several others available.

A: You don't.
Instead you use the users and groups to grant/deny privileges, and let the engine enforce them appropiately. Attempting to roll your own security will get you nowhere fast. A banal example is when you will fail to honor the 'one deny trumps all grants' rule. And you will fail to navigate the intricacies of EXECUTE AS. Not to mention security based on module signatures.
For the record: users, roles and groups are exposed in the sys.database_principals catalog view. sys.fn_my_permissions will return the current context permissions on a specific securable.

A: Checking yourself or the current user:
SELECT IS_MEMBER('[group or role]')

A result of 1 = yes,0 = no, and null = the group or role queried is not valid.
To get a list of the users, try xp_logininfo if extended procs are enabled and the group in question is a windows group :
EXEC master..xp_logininfo
@acctname = '[group]',
@option = 'members'

A: For a quick view of which groups / roles the current user is a member of;
select
      [principal_id]
    , [name]
    , [type_desc]
    , is_member(name) as [is_member]
from [sys].[database_principals]
where [type] in ('R','G')
order by [is_member] desc,[type],[name]

A: The code that is provided on the Microsoft page here works for me, every time.
SELECT DP1.name AS DatabaseRoleName,
   isnull (DP2.name, 'No members') AS DatabaseUserName
 FROM sys.database_role_members AS DRM
 RIGHT OUTER JOIN sys.database_principals AS DP1
   ON DRM.role_principal_id = DP1.principal_id
 LEFT OUTER JOIN sys.database_principals AS DP2
   ON DRM.member_principal_id = DP2.principal_id
WHERE DP1.type = 'R'
ORDER BY DP1.name;

Please let me know if this works for you!


text:
Q: Angular function syncronization My question is how to execute 3 functions(declared in service) in order:
   function1();
   function2();
   function3();

All functions contain http commands(e.g. put or get). that's why if I use code above function 3 will be executed before function 2. I tried to chain functions with then but that didn't help either.

A: You need to return a promise and then use promise chaining, because your functions are async.
function1().then(function(response) {
   /* executes function2, if function1 return success */
   function2().then(function(response) {
      /* executes function3, if function2 return success */
      function3();
   }
}

In the angular docs (https://docs.angularjs.org/api/ng/service/$q) you can see how to return a promise. For the case you use the $http or $resource provider: They always return a promise which you can use for your purpose.


text:
Q: Size of text that wraps to multiple lines different from text that doesn't I'm setting up a Wordpress blog with both Facebook and native Wordpress comments: http://lucky-stars.ca/yum/hello-world. I'm trying to get the formatting of the Wordpress comments as close as possible to the Facebook ones. I'm almost there, but I've run into a strange problem.
On any first-level comment that wraps to display on multiple lines, it does not use the text size I've specified on the comment and comment author when viewed in iOS with a viewport size between 768px and 480px. Any comment that fits on one line (or has manual breaks that fit on one line) is fine, and when I look at it on my iPhone in portait orientation (<480px), the problem goes away.
This problem also appears underneath the comment form where it says "your email address will not be published..."
My font size specifications are on the div that contains all of my comments, #comments.
This is what I've tried so far:

*

*Clearing my cache.

*Adding !important to the font rule on #comments.

*Tried both ems and pixels for the font size.

*Adding the size specification to the specific problematic divs (.comment-author and .comment-content).

*Breaking down my font specifications into individual rules instead of shorthand.

*Checked that there are no font rules that would be overriding this under @media screen and (max-width: 768px).

*Adding zoom:1 to the #comments after I saw that Facebook's comments did this. This fixed the problem when I was using Chrome's User Agent and Device Metrics Overrides, but the problem persists on my iPhone.

I've tried googling the problem, but I'm not really sure what I'm looking for here since it's only a problem when the text wraps. And not just on text that wraps, but on the author's name as well, even though it's a separate div.
Any direction would be appreciated, I'm completely at a loss.

A: Adding this to my CSS fixed the problem:
html {
    -ms-text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;
}
Got this from https://github.com/necolas/normalize.css/blob/v2.1.2/normalize.css


text:
Q: Removing a JavaScript comment through commands? I am currently developing a website that relies heavily on large blocks of javascript for widgets. Some of these are demanding processes, such as running timers or clocks, so I only want these scripts to activate when their corresponding widget is activated. My proposed solution is to comment out each of these blocks of scripts, and "uncomment" them when the widget is active.
For example, if I have a countdown timer widget, I would like to have my code for the widget completely commented out until the user clicks the widget. When the user opens the widget, I would like the corresponding scripts to become "uncommented" and execute.
Is there any way I can programmatically add or remove comment marks to the Javascript code on the fly? I am looking for some method or command I could use; not something that requires me to physically alter the code.
I saw this in a Google I/O Conference Presentation, so I was just wondering if anyone knew how.

A: There is a better way to go about it. If you're worried about clogging the event loop: make sure widgets don't have access to the event loop but have to go through your framework to get to it. This allows you to 'sleep' a widget, stop all it's events.
Another thing to keep in mind that is that when widgets are removed you must also clean up any events they have scheduled or you will run into 'dead' code. All events must therefor be scheduled through your framework so you can clean them up if the widget is unloaded.

Code is read and loaded into the JavaScript engine, modifying the code after that point will do nothing.


text:
Q: Viewpager2 open selected page (from cardview) without fragment Quick question here. I have a cardview, and a viewpager2. Is it possible to open a selected page of the viewpager, in function of the item I clicked on the cardview, but without fragment ?
I think I should use getCount() in order to select which page I want to display, but how can I link it to the cardview adapter? (which I have the positions of items).
Thanks for your help.

A: To set the current item of Viewpager2 you can use the setCurrentItem (int item) or the setCurrentItem (int item,
boolean smoothScroll).
The second allows you to pass a boolean value to indicate whether to animate smoothly when changing the pages.


text:
Q: Use dependency from one project to another in the same solution Is it a way of using a dependency from a project to another while they are in the same solution? For example:
ComputerVisionProject (solution):
    1. ComputerVision.FaceRecognition
    2. ComputerVision.Core
    3 .ComputerVision.UI

In the first project: ComputerVision.FaceRecognition, I install a nugget, for example, "OpenCV" and I can use all the functions from it with "using OpenCV", but only in the ComputerVision.FaceRecognition project.
What I want is to use the same functions in the second project, ComputerVision.Core. but I don't want to install again the nugget, and seems that only "using OpenCV" doesn't work (even if I add the entire project as a reference to the second one)  Is it possible to make another type of reference or something like: "using ComputerVision.FaceRecognition.OpenCV" ?

A: Use a project reference.
https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019
To test; create a new solution with two projects within it.
Within one project, add a nuget package. Say, Newtonsoft.Json
Add a project reference from your second project to the first
Dependencies should now look like so;

Now within TestConsoleApp, you can add using statements to access the nuget package used in TestConsoleApp2.
eg;
using System;
using Newtonsoft.Json;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var output = JsonConvert.SerializeObject(new ExampleObject() { field = "value" });
            Console.WriteLine(output);
        }
    }

    public class ExampleObject
    {
        public string field;
    }

}

When run outputs {"field":"value"}


text:
Q: Is this the right approach for structuring codebase? We have a Java codebase that is currently one Web-based Netbeans project. As our organization and codebase grows it seems obvious that we should partition the various independent pieces of our system into individual jars. So one Jar library for the data access layer, one for a general lib, one for a specialized knowledge access, etc. Then we'd have a separate project for the web application, and could have one for a command line tools app, another web app eventually, etc.
What is the recommended practice for doing and managing this? Is it Maven? Can it all be effectively done with just Netbeans alone by simply creating individual projects and setting the dependecies of one project on the jar files of the others?

A: I'd agree with SteveG above on using Maven2 to help you modularise your code base, but I'd use Nexus as the local repository for Maven instead of Archiva. The guys at Sonatype also have an excellent (free html/pdf) book on how to use Maven, Nexus, and integrate it into IDEs.
Be careful on how you decide to partition up your projects, though. There's no sense in over-complicating your dependencies just for the sake of it.

A: I would create ant scripts to build the pieces and for deployment. Then you are not depending on your IDE for build/deployment.

A: I would definitely say check Maven(2) out.  It is very good for doing this sort of thing. You can define individual models and version then very easily.  Netbeans also does a decent job of integrating with.
Also I suggest you set up Archiva which will let you be dependent upon binaries of other artifacts that your company generates internally.  This also acts as a proxy and will keep a local copy of any external dependencies your projects might have so its very quick to get the new versions internally.

A: It sounds like your code is getting to the point where you're graduating from the WAR approach and have entered into the EAR level.
An EAR is just another archive that contains all the other JARs and WARs that get combined to create an application. There are four types of modules that can reside inside it, Web, EJB, Connectors and Utilities. Most people only use Web and Utilities so they go with using the WEB-INF/lib approach.
But if you're starting to get a lot of interdependencies what you do create an EAR project and make your web project a child of it. Each Utility JAR which is just straight Java code used by other modules also becomes a child of the EAR. Finally in each of your projects there should be a META-INF/manifest.mf file that just has the name of the JARs that JAR/WAR depends on.
I'm an eclipse guy and most of this gets taken care of for you in eclipse, but I'm sure netbeans has very similar functionality.
Now the only problem is that you have to use a full Java EE server to deploy an EAR so I don't think you can use Tomcat if that's what you're currently using.


text:
Q: Flask-MySQL ignore host parameter I'm trying to write a Flask miniapp to connect with a MySQL database. To connect with the database, I use flask-mysql, calling it as this way
from flask import Flask, render_template, redirect
from flaskext.mysql import MySQL

SECRET_KEY='5f352379324c22463451387a0aec5d2f'

app = Flask(__name__)
app.secret_key = SECRET_KEY

mydb = MySQL(app, prefix="mydb", host='172.17.0.2', user='testusr', password='test', db='testDB')

(...)

if __name__ == "__main__":
        app.run(host='0.0.0.0', port=5000)

But, when I run the application, it shows this error
pymysql.err.OperationalError: (1044, "Access denied for user 'testusr'@'%' to database 'testDB'")

If I run it from a Docker container, I get a similar error, replacing "%" with "localhost" (in this case, it's not able to connect, due to the database is out of the container)
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 99] Cannot assign requested address)")
172.17.0.1 - - [23/Jun/2021 18:00:29] "GET / HTTP/1.1" 500 -

I tried to initialize flask-mysql using other this way, with the same error
app.config['MYSQL_HOST'] = '172.17.0.2'
app.config['MYSQL_USER'] = 'testusr'
app.config['MYSQL_PASSWORD'] = 'test'
app.config['MYSQL_DB'] = 'testDB'

mydb = MySQL(app)

Where can be the error?

A: Solved changing the connector from flask-mysql to mysql-connector
import mysql.connector

SECRET_KEY='5f352379324c22463451387a0aec5d2f'

app = Flask(__name__)
app.secret_key = SECRET_KEY

mydb = mysql.connector.connect(
  host="172.17.0.2",
  user="testusr",
  password="test",
  database="testDB"
)


text:
Q: Django JsonResponse with safe=False to D3 Developing a project with Django which involves serving JSON data to templates for use in javascript using the D3 framework.
A pattern I am using quite a bit is to return a JsonResponse object from a Django view with an array of data.  As I start to link up apps in the project, I am also starting to use this idea to pass data between views in different apps. To get this working, I also need to set a safe flag as False. e.g.
def my_view(request):

    data = [{'foo':'bar'}, {'but':'should'}, {'i':'care?'}]

    return JsonResponse(data, safe=False)

This works fine and I think I want to be passing arrays because it makes life easier in D3.  But it perturbs me a bit to be using this flag. I am somewhat reassured by the description in the Django documentation, but cannot say I have much understanding of the risk.
django docs - jsonresponse
Any thoughts on how much of a security issue this potentially is, and what might be the best alternative approach if they are significant?

A: As you rightly point out, sending non-dict JSON objects was a concern for EMCAScript 3 and earlier according to the Django documentation. (For those interested, here are the details of how the attack was executed.)
However, EMCAScript 5 was released in 2009 and was fully supported in major browsers by 2013. The release of EMCAScript 5 and subsequent browser adoption fixed this vulnerability, and it is now safe to send non-dict options. So, safe=False should only be relevant if you plan to support browsers released before 2013.
If your website restricts browser support (for example) by only offering TLS version 1.2 and 1.3 - any browser that supports TLS 1.2 and later will not be vulnerable to the JSON issue with EMCAScript, because those browser version came after EMCAScript 5 was fully implemented in major browsers.
In summary, there is little to no concern to setting this safe flag to False in the JSONResponse class. This is because the only possible way the vulnerability could be exploited is through ancient browsers.


text:
Q: vBulletin plugin with cURL I've tried the following guide for including external files in a template using this manual.
I've created a plugin with this code below and included it in a template using the $includedphp variable:
ob_start();
include('http://foo.bar.com/external.php');
$includedphp = ob_get_contents();
ob_end_clean();

Afterwards I've found out that include() is disabled in the server configuration. My other option is to use cURL which is enabled:
$curl = curl_init( "http://foo.bar.com/external.php" );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
$includedphp = curl_exec( $curl );
curl_close( $curl );

It's not working. It just prints blank in my template. Hooks used: "global_start". vBulletin version: 3.8.

A: You can't use curl as a replacement of include.
How could include is disabled?
I see that you use http:// on your include code, what if you use non-http?
include(DIR.'/external.php');

Note: DIR constant contains vbulletin forum installation root on vb4, so i'm not sure for vb3.