text:
Q: Assign levels to nodes in multi-level sankey diagram where nodes may not have connections to the first level or the last level First, let me start by saying that I've read How to assign levels to nodes in multi-level sankey diagram?
It helps but doesn't fully solve the issue.
Also, in my example code below I use the networkD3 package but I don't need to. Any package is fine with me so long as I'm able to place certain nodes at certain levels in the diagram.
Problem:
I'm trying to draw a 3-level sankey diagram where each node is assigned to a "period" or level in the chart. The full chain of links would be something like Period 1-->Period 2-->Period 3. However, there may be cases where a Period 2 node is not connected to a Period 1 node (Period 2 --> Period 3) or where a Period 2 node is not connected to a Period 3 node (Period 1 --> Period 2).
I haven't figured out how to accomplish this on my own. The image below is what I'm trying to produce.

Below is some code to reproduce the problem I'm running into:
(Note: this is a simplified version. My actual data contains 150 nodes, 5 Periods and many hundreds of links.)
library(dplyr)
library(networkD3)

# Create link data
links <- data.frame(source = c("A","A","B","C","D","E","G"),
                    target = c("D","E","D","F","H","H","I"),
                    nlink = c(12,27,10,5,1,5,10)
                    )

# Create node data
nodes <- data.frame(
  name=c(as.character(links$source), as.character(links$target)) %>%
    unique()
)

# Assign periods to nodes
# I don't know how to actually use this to tell sankeyNetwork
# where to place the nodes but I'm including it here to help in problem solving
period <- data.frame(period = c("Period 1", "Period 1", "Period 1",
                                "Period 2", "Period 2", "Period 2", "Period 2",
                                "Period 3", "Period 3"))
nodes$nodeGroup <- period$period

# match to numbers, not names
links$IDsource <- match(links$source, nodes$name)-1
links$IDtarget <- match(links$target, nodes$name)-1

# Plot Sankey Network
p <- sankeyNetwork(
  Links = links,
  Nodes = nodes,
  Source = "IDsource",
  Target = "IDtarget",
  Value = "nlink",
  NodeID = "name",
  nodeWidth = 30,
  iterations = 5
)
p

You can see here that even though node "C" is a Period 1 node, it is placed with the Period 2 nodes. If I change the code to use "sinksRight = FALSE" as suggested in this thread: How to assign levels to nodes in multi-level sankey diagram? we get the following:
p <- sankeyNetwork(
  Links = links,
  Nodes = nodes,
  Source = "IDsource",
  Target = "IDtarget",
  Value = "nlink",
  NodeID = "name",
  nodeWidth = 30,
  sinksRight = FALSE,
  iterations = 5
)
p

Now you can see that the "C" node is with the other Period 1 nodes as it should be, but the "G" node is now over here too, when it's a Period 2 node and should be in-line with D, E, and F (while I should be in the Period 3 level in-line with H).
Is there a way for me to explicitly assign nodes to a specific level?


text:
Q: would the unity2D (c#) read useless "if" structures? I just want to know if my useless if-statements effect on my rendering time or not ? I am making an unity2D game and in update method I have used some if-statements that their conditions may go true once a minute but this method updates every frame.
void Update(){
for (long i = 0; i< 100000000000000; i++)
{
    if (i == 999)
    {
        "lots of functions"
    }
}
}

Does it ignore the rest of if when the condition is not true?
my question is if the condition of "if-statement" is not true, would the functions of "if-statement" effect on rendering ? Or will they be just ignored when their conditions are false?

A: The body of the if statement will not execute, and will be ignored, if the statement is false.
If you are so concerned with holding up execution with so many iterations, i advise you to use a while loop inside of an IEnumerator as so:
IEnumerator DoLoop(){
    long i = 0;

    while (i< 100000000000000)
    {
        if (i == 999)
        {
            "lots of functions"
        }

        i++;
        yield return null;
    }
}

This way, other things are allowed to be executed at the same time as your loop is running.

A: The condition (such as i == 999) will be evaluated every time the if statement is reached (that is, every frame), but the nested statements ("lots of functions") will only execute (and only take rendering time) when the condition is true. That's the whole point of an if statement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails show view of one model with form for adding one child - nested attributes vs seperate controller vs? I have a basic two tiered model structure: Articles -> Comments with one Article having many comments.
What is the best way to add a "Add a comment" form to the bottom of the Articles show page?
nested_attributes is overkill as I don't want to be able to edit all of the comments on the page, just to add one more.
Is the best way even with Rails 2.3 still to make a separate controller and embed a form_for pointing to the other controller into the Articles show view? If so, how do I get validation errors to return to the article display page?
I don't want to make a separate comment page/view...
thanks

A: Lay some code out SWR, and this will also help!
http://railscasts.com/episodes/196-nested-model-form-part-1


text:
Q: How to get Product Attribute Options by attribute code in Magento 2.0 I am trying to retrieve the list of dropdown attributes and check if the value exists (if it does i need to get the value and assign it to the product) and if it doesnt i will have to create it and get its value to assign it to the product.
$attribute = $this->objectManager->create('Magento\Eav\Model\Entity\Attribute');
$attributeId = $attribute->getIdByCode('catalog_product','manufacturer');
$model = $this->objectManager->create('Magento\Catalog\Model\ResourceModel\Eav\Attribute');
$model->load($attributeId);
print_r($model->getFrontendLabel());

A: <?php echo $_product->getResource()->getAttribute('movement')->getFrontend()->getValue($_product);?>

$_product is the object of Product
The above code returns attribute value of attribute name "movement".

A: Following Magento 2 guidelines, you should not use ObjectManager by yourself. Instead, you must use dependency injection. More info here
In your Block/Controller/Helper..., create a constructor and inject \Magento\Catalog\Api\ProductAttributeRepositoryInterface class. For example :
private \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository;

public function __construct(
    \Magento\Catalog\Api\ProductAttributeRepositoryInterface $productAttributeRepository
) {
    $this->productAttributeRepository = $productAttributeRepository;
}

Then, in your dedicated method, you want to call (PHPDoc added for clarity) :
/** @var \Magento\Eav\Api\Data\AttributeOptionInterface[] $manufacturerOptions */
$manufacturerOptions = $this->productAttributeRepository->get('manufacturer')->getOptions();

You can now get options values and labels this way :
foreach ($manufacturerOptions as $manufacturerOption) {
    $manufacturerOption->getValue();  // Value
    $manufacturerOption->getLabel();  // Label
}

A: Using API Service layer, for EAV Attribute of any entity type, Inject the service data member in your constructor as follow.
protected $eavAttributeRepository;
public function __construct(
    ...
    \Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepositoryInterface,
    ...
){
    ...
    $this->eavAttributeRepository = $eavAttributeRepositoryInterface;
    ...
}

And the you can get the attribute using this.
$attribute = $this->eavAttributeRepository->get('catalog_product', 'attribute_code_here');
// vardump($attribute->getData());

In order to get attribute option values array, use this.
$options = $attribute->getSource()->getAllOptions();

A: Try the following code

$attribute_code = "coffe_type";
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();

$eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product',$attribute_code );

$options = $attribute->getSource()->getAllOptions();
foreach($options as $option) {
    $optionsExists[] = array('label' => $option['label'], 'value'=> $option['value'] );
}

print_r($optionsExists);

A: Inject an instance of \Magento\Catalog\Model\Product\Attribute\Repository in your constructor (in a block, helper class or wherever):
/**
 * @var \Magento\Catalog\Model\Product\Attribute\Repository $_productAttributeRepository
 */
protected $_productAttributeRepository;

/**
 * ...
 * @param \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository
 * ...
 */
public function __construct(
    ...
    \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
    ...
) {
    ...
    $this->_productAttributeRepository = $productAttributeRepository;
    ...
}

Then create a method in your class to get the attribute by code:
/**
 * Get single product attribute data
 *
 * @return Magento\Catalog\Api\Data\ProductAttributeInterface
 */
public function getProductAttributeByCode($code)
{
    $attribute = $this->_productAttributeRepository->get($code);
    return $attribute;
}

You can then call this method like so, e.g. inside a .phtml file
$attrTest = $block->getProductAttributeByCode('test');

Then you can make calls on the attribute object, e.g.

*

*Get options: $attrTest->getOptions()

*Get frontend label for each store: $attrTest->getFrontendLabels()

*Debug the data array: echo '> ' . print_r($attrTest->debug(), true);

debug: Array (
      [attribute_id] => 274
      [entity_type_id] => 4
      [attribute_code] => product_manual_download_label
      [backend_type] => varchar
      [frontend_input] => text
      [frontend_label] => Product Manual Download Label
      [is_required] => 0
      [is_user_defined] => 1
      [default_value] => Product Manual Download
      [is_unique] => 0
      [is_global] => 0
      [is_visible] => 1
      [is_searchable] => 0
      [is_filterable] => 0
      [is_comparable] => 0
      [is_visible_on_front] => 0
      [is_html_allowed_on_front] => 1
      [is_used_for_price_rules] => 0
      [is_filterable_in_search] => 0
      [used_in_product_listing] => 0
      [used_for_sort_by] => 0
      [is_visible_in_advanced_search] => 0
      [position] => 0
      [is_wysiwyg_enabled] => 0
      [is_used_for_promo_rules] => 0
      [is_required_in_admin_store] => 0
      [is_used_in_grid] => 1
      [is_visible_in_grid] => 1
      [is_filterable_in_grid] => 1
      [search_weight] => 1 )

A: Below code helpful to find a particular attribute values. Like here color is on my attribute, with below code we can get what and all colors are mapped with this attribute.
$attributeId = Mage::getResourceModel('eav/entity_attribute')>getIdByCode('catalog_product','color');
$collection =Mage::getResourceModel('eav/entity_attribute_option_collection')>setPositionOrder('asc')->setAttributeFilter($attributeId)->setStoreFilter(0)->load();
print_r($collection->getData());


text:
Q: Why there are many authentication flows in OpenIddict? I am a newbie to .Net Core WebAPI authentication. I've figured out OpenIddict is one of the authentication service easy-to-use but before I start using it I noticed there are samples with different authentication flows in GitHub. I could not find any documentation around these authentication flows so the below questions come to mind.. Appreciate if someone can provide insights on the area.
GitHub url : https://github.com/openiddict/openiddict-core

*

*Why there are different flows.. which one to use? I am guessing each flow fits to different nature of application if so,
a. what are the pros and cons of each flow?
b. Is there any best practice or guidelines that helps to determine the right option (authentication flow) that fits in for that particular application?
Thanks in advance.

A:
Why there are different flows.. which one to use?

OpenIddict is an OAuth2/OpenID Connect server. As such, it implements all the classical core flows defined by these two specifications.
As you figured out, each flow has a different use case:

*

*The client credentials grant is used when a headless client application needs to access its own resources. No user is involved in this flow, which is basically a server-to-server scenario.

*The resource owner password credentials grant is the simplest OAuth2 flow: the client application sends a token request with the username and the password of the user and it gets back an access token. This flow is sometimes considered as a "legacy" flow and must not be used by third-party apps you don't manage yourself (because it's the only flow where the client knows the user credentials).

*The code flow is the most complex OAuth2/OpenID Connect flow that uses redirections and allows creating consent pages where the user can decide whether he wants to grant an access to the client application without ever sharing his credentials with the app.

*The implicit flow is a simplified code flow, made for browsers-based apps.
For more information, you can read this blog post: http://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-choosing-the-right-flows/.


text:
Q: Upgrading php binaries installed by Apple I am on Yosemite and I want to upgrade my PHP version (which comes with OSX by default). Right now I am on PHP 5.5.27 and I want to upgrade to PHP 5.6... So, by doing something like this:
curl -s http://php-osx.liip.ch/install.sh | bash -s 5.6

the current binaries wont be overwritten... From the docs:

php-osx doesn't overwrite the php binaries installed by Apple, but
  installs everything in /usr/local/php5. The new php binary is
  therefore in /usr/local/php5/bin/php.
You can also adjust your PATH do include that directory, eg. write
  into your ~/.profile file the following
export PATH=/usr/local/php5/bin:$PATH

But how would I just upgrade the current php installation ?

A: have a look at homebrew "The missing package manager for OS X".
you can then install php56 with brew
brew install php56


text:
Q: Python - deconstructor does not delete object instance I have the following problem, i am an amateur user of Python scripting. I have created the following  class
 roof_height = 3.5 #m
 E = 30000*(10^3) #kN/m^2

 class Brace():
     _registry = []

     def __init__(self,name,coord,b,d, h = roof_height):
          print('Brace created.')
          Brace._registry.append(self)
          self.name  = name
          self.coord = coord              # pass tuple in the form of (x,y)
          self.b     = b                  # //x global
          self.d     = d                  # //y global
          self.h     = h

      def __del__(self):
          print('Destructor called, Brace deleted.')
          Brace._registry.remove(self)

      def properties(self):
          print("properties of " + self.name + " calculated")
          As = self.b*self.d
          Iy = self.b*(self.d**3)*(1/12)
          Iz = (self.b**3)*(self.d)*(1/12)
          self.Iy =  Iy
          self.Iz =  Iz
          self.As =  As

    def stiffness(self):
        print("stiffnesses of " + self.name + " calculated")
        Kx = 12*E*self.Iy/self.h
        Ky = 12*E*self.Iz/self.h

        self.Kx = Kx
        self.Ky = Ky

I have created the _registry general property of the class so I can iterate through the objects, which works fine. The problems that I am facing are the following:
1. When I am creating an object the print out
 'Brace created'

is displayed, but when I am deleting it the message
 'Destructor called, Brace deleted.'

is not displayed while the object is deleted, also the _registry list remains the same without deleting the object. The length of the list obviously remains the same.

*How can I avoid creating the same instance twice with the same name, I mean how can I check for duplicate instances (same object name and attribute values)
Do I have to write a code for it or is there a builtin function that I can use?

A: 1: __del__() might not be getting called for a number of reasons to do with garbage collection. From the documentation:

Note del x doesn't directly call x.__del__() — the former decrements
  the reference count for x by one, and the latter is only called when
  x's reference count reaches zero. Some common situations that may
  prevent the reference count of an object from going to zero include:
  circular references between objects (e.g., a doubly-linked list or a
  tree data structure with parent and child pointers); a reference to
  the object on the stack frame of a function that caught an exception
  (the traceback stored in sys.exc_info()[2] keeps the stack frame
  alive); or a reference to the object on the stack frame that raised an
  unhandled exception in interactive mode (the traceback stored in
  sys.last_traceback keeps the stack frame alive). The first situation
  can only be remedied by explicitly breaking the cycles; the second can
  be resolved by freeing the reference to the traceback object when it
  is no longer useful, and the third can be resolved by storing None in
  sys.last_traceback. Circular references which are garbage are detected
  and cleaned up when the cyclic garbage collector is enabled (it's on
  by default). Refer to the documentation for the gc module for more
  information about this topic.

Rather than relying on the built-in memory management functionality, perhaps you could implement a bespoke function for freeing up resources once an object is no longer needed?
2: To avoid having two instances with the same name, use the factory pattern.


text:
Q: Unable to save the data from ionic to mongodb : MEAN stack I'm trying to post some data from ionic to MongoDB but it is not getting posted I mean is not recognizing the url in the routes page. But when I'm trying to post the data from the postman data is getting saved but not through the ionic.
let selected = {
      companyTitle : jobitem.company,
      jobTitle : jobitem.jobtitle,
      location : jobitem.location,
      date: appliedDate,
      id: userId
    }
    console.log(selected);
    return this.http.post('http://localhost:3000/api/jobApplied',selected,{headers: headers})

The above code is from the ionic ts file. The below code is from the routes.js js file
router.post('/jobApplied', function(req,res) {
  console.log('posting');
  appliedJobs.create({
    companyTitle: req.body.companyTitle,
    jobTitle: req.body.jobTitle,
    location: req.body.location,
    date: req.body.date,
    userId: req.body.id
  },function(err,list) {
    if (err) {
      console.log('err getting list '+ err);
    } else {
      //res.json(list);
      return res.json(list) }
  }
  );
});

I have used the same url in the postman

http://localhost:3000/api/jobApplied

but the data is not getting posted. What might be the problem & How can I solve it?


text:
Q: basic authentication server not working on jellybeans and kitkat I am using basic authentic for http connection in app. App is working finr correctly on devices with higher versions. I have also searched for solution and It did not worked for me.
Here is my code for connection
public static String executeHttpPost(Activity activity, String url,
                                     ArrayList<NameValuePair> postParameters) {
    String value = "{\"status\":false,\"message\":\"Server Timeout, connection problem, Please try later\"}";
    try {
        final String basicAuth = "Basic " + Base64.encodeToString(
                ("abc" + ":" + "abcd").getBytes(), Base64.NO_WRAP);
        networkConnection = new NetworkConnection();
        if (networkConnection.isOnline(activity)) {
            postParameters.add(new BasicNameValuePair("device_type","android"));
            HttpClient client = getNewHttpClient();
            HttpPost post = new HttpPost(url);

            try {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters, "UTF-8");

                post.setEntity(entity);

                post.setHeader("Authorization",basicAuth);
                post.setHeader("some-parameter","abc");
                org.apache.http.HttpResponse result = client.execute(post);
                value = EntityUtils.toString(result.getEntity());
            }catch (Exception e){}
            String s = "";
            for (NameValuePair param : postParameters) {
                s = s + param.getName() + " = " + param.getValue() + " ";
            }
            if (value != null) {
                WebUrl.ShowLog("From " + url +" parameters "+s
                        + " Response : " + value.trim());

                return value.trim();
            } else {

                return value;
            }
        } else {
            activity.startActivity(new Intent(activity, NoInternet.class));
            activity.finish();
            return "{\"status\":false,\"message\":\"\"}";

        }

    } catch (Exception e) {
        e.printStackTrace();

        return value;
    }
}

This is the only link I found, but it didn't work for me

A: You should use Google Volley for the connections with the server. There are many ways to get connect, but using "Google Volley" in Android development is so simple, reliable and as it comes as a dependency it gets bundled with your package. So never worry about compatibility over many old and many current and upcoming Android versions.
I have used it 5 years ago and it was working on all major platforms. Very easy to program.
Have a look:
final TextView mTextView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
    @Override
    public void onResponse(String response)
    {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener()
{
    @Override
    public void onErrorResponse(VolleyError error)
    {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

How simple is it.


text:
Q: COM Visible Assembly - Object method not accessible through its exposed interface method I implemented a .NET DLL with COM visibility (VB.NET):

Public Class Processer Implements IProcesser
    Public Sub processASpecificThing(ByVal param As String) _
        Implements IProcesser.processAThing
        ' [...]
    End Sub
End Class

Below the Interface definition. For some reasons I exposed a method with a different name in the interface.

Imports System.Runtime.InteropServices
Imports System.ComponentModel

<InterfaceType(ComInterfaceType.InterfaceIsDual)> _
Public Interface IProcesser
    Sub processAThing(ByVal param As String)
End Interface

The project is configured to set the Assembly as COM visible. If I understood correctly InterfaceIsDual let the Interface be visible at early binding as well as at late binding.
In a VB6 project, this works:

Dim aProcesser as IProcesser
Set aProcesser = New Processer
aProcesser.processAThing "param" ' Call by the *Interface* method name

In a VB6 project or an ASP classic VBScript page, this fails:

Dim aProcesser
Set aProcesser = CreateObject("ProcessLib.Processer")
' Call by the *Interface* method name
aProcesser.processAThing "param" ' [FAIL]
' Call by the *Interface* method name
aProcesser.processASpecificThing "param" ' [SUCCESS]

The failing line leads to the error message:

Object Doesn't Support this Property or Method

The real context of this question is an ASP classic page. I use a late binding to avoid adding a METADATA header in the ASP file (I believe it's the only way, but not tested yet).
Sounds like the interface is not accessible. Why does that problem occur and how could I make the interface accessible with ?


text:
Q: Account merge leaves behind empty network profile I recently merged two of my Stack Exchange accounts. This causes the user with the higher ID to be deleted on each site where I had accounts that got merged. Except it doesn't remove the network profile of the older account. Here's what my hallowed out network profile looks like. There's nothing there: no accounts or reputation or activity. Ideally, this page should redirect to my new post-merge network profile instead.
This behaviour has confused fans of mine who have bookmarked my network profile to be able to keep up with my Stack Exchange activity, network-wide: I learned about this issue when one of my fans expressed their confusion to me.


text:
Q: Issue with python netapp Lib I'm creating a volume on the  netapp Cdot Storage by ansible, there is netapps cdot module is available for ansible which is written in python, One of peice of the code is as below. Now when i'm  using this module to create my netapp vol as given in example below , its throwing an issue "the python NetApp-Lib module is required".
Could you guys any hints please..
#!/usr/bin/python

# (c) 2017, NetApp, Inc
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''

module: na_cdot_volume

short_description: Manage NetApp cDOT volumes
extends_documentation_fragment:
    - netapp.ontap
version_added: '2.3'
author: Sumit Kumar (sumit4@netapp.com)

description:
- Create or destroy volumes on NetApp cDOT

options:

  state:
    description:
    - Whether the specified volume should exist or not.
    required: true
    choices: ['present', 'absent']

  name:
    description:
    - The name of the lun to manage.
    required: true

  infinite:
    description:
    - Set True if the volume is an Infinite Volume.
    choices: ['True', 'False']
    default: 'False'

  online:
    description:
    - Whether the specified volume is online, or not.
    choices: ['True', 'False']
    default: 'True'

  aggregate_name:
    description:
    - The name of the aggregate the flexvol should exist on. Required when C(state=present).

  size:
    description:
    - The size of the volume in (size_unit). Required when C(state=present).

  size_unit:
    description:
    - The unit used to interpret the size parameter.
    choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
    default: 'gb'

  vserver:
    description:
    - Name of the vserver to use.
    required: true
    default: None

'''

EXAMPLES = """

    - name: Create FlexVol
      na_cdot_volume:
        state: present
        name: ansibleVolume
        infinite: False
        aggregate_name: aggr1
        size: 20
        size_unit: mb
        vserver: ansibleVServer
        hostname: "{{ netapp_hostname }}"
        username: "{{ netapp_username }}"
        password: "{{ netapp_password }}"

    - name: Make FlexVol offline
      na_cdot_volume:
        state: present
        name: ansibleVolume
        infinite: False
        online: False
        vserver: ansibleVServer
        hostname: "{{ netapp_hostname }}"
        username: "{{ netapp_username }}"
        password: "{{ netapp_password }}"

"""

RETURN = """

"""

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
import ansible.module_utils.netapp as netapp_utils

HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()

class NetAppCDOTVolume(object):

    def __init__(self):

        self._size_unit_map = dict(
            bytes=1,
            b=1,
            kb=1024,
            mb=1024 ** 2,
            gb=1024 ** 3,
            tb=1024 ** 4,
            pb=1024 ** 5,
            eb=1024 ** 6,
            zb=1024 ** 7,
            yb=1024 ** 8
        )

        self.argument_spec = netapp_utils.ontap_sf_host_argument_spec()
        self.argument_spec.update(dict(
            state=dict(required=True, choices=['present', 'absent']),
            name=dict(required=True, type='str'),
            is_infinite=dict(required=False, type='bool', default=False, aliases=['infinite']),
            is_online=dict(required=False, type='bool', default=True, aliases=['online']),
            size=dict(type='int'),
            size_unit=dict(default='gb',
                           choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb',
                                    'pb', 'eb', 'zb', 'yb'], type='str'),
            aggregate_name=dict(type='str'),
            vserver=dict(required=True, type='str', default=None),
        ))

        self.module = AnsibleModule(
            argument_spec=self.argument_spec,
            required_if=[
                ('state', 'present', ['aggregate_name', 'size'])
            ],
            supports_check_mode=True
        )

        p = self.module.params

        # set up state variables
        self.state = p['state']
        self.name = p['name']
        self.is_infinite = p['is_infinite']
        self.is_online = p['is_online']
        self.size_unit = p['size_unit']
        self.vserver = p['vserver']

        if p['size'] is not None:
            self.size = p['size'] * self._size_unit_map[self.size_unit]
        else:
            self.size = None
        self.aggregate_name = p['aggregate_name']

        if HAS_NETAPP_LIB is False:
            self.module.fail_json(msg="the python NetApp-Lib module is required")
        else:
            self.server = netapp_utils.setup_ontap_zapi(module=self.module, vserver=self.vserver)

    def get_volume(self):
        """
        Return details about the volume
        :param:
            name : Name of the volume

        :return: Details about the volume. None if not found.
        :rtype: dict
        """
        volume_info = netapp_utils.zapi.NaElement('volume-get-iter')
        volume_attributes = netapp_utils.zapi.NaElement('volume-attributes')
        volume_id_attributes = netapp_utils.zapi.NaElement('volume-id-attributes')
        volume_id_attributes.add_new_child('name', self.name)
        volume_attributes.add_child_elem(volume_id_attributes)

        query = netapp_utils.zapi.NaElement('query')
        query.add_child_elem(volume_attributes)

        volume_info.add_child_elem(query)

        result = self.server.invoke_successfully(volume_info, True)

        return_value = None

        if result.get_child_by_name('num-records') and \
                int(result.get_child_content('num-records')) >= 1:

            volume_attributes = result.get_child_by_name(
                'attributes-list').get_child_by_name(
                'volume-attributes')
            # Get volume's current size
            volume_space_attributes = volume_attributes.get_child_by_name(
                'volume-space-attributes')
            current_size = volume_space_attributes.get_child_content('size')

            # Get volume's state (online/offline)
            volume_state_attributes = volume_attributes.get_child_by_name(
                'volume-state-attributes')
            current_state = volume_state_attributes.get_child_content('state')
            is_online = None
            if current_state == "online":
                is_online = True
            elif current_state == "offline":
                is_online = False
            return_value = {
                'name': self.name,
                'size': current_size,
                'is_online': is_online,
            }

        return return_value

    def create_volume(self):
        volume_create = netapp_utils.zapi.NaElement.create_node_with_children(
            'volume-create', **{'volume': self.name,
                                'containing-aggr-name': self.aggregate_name,
                                'size': str(self.size)})

        try:
            self.server.invoke_successfully(volume_create,
                                            enable_tunneling=True)
        except netapp_utils.zapi.NaApiError:
            err = get_exception()
            self.module.fail_json(msg='Error provisioning volume %s of size %s' % (self.name, self.size),
                                  exception=str(err))

    def delete_volume(self):
        if self.is_infinite:
            volume_delete = netapp_utils.zapi.NaElement.create_node_with_children(
                'volume-destroy-async', **{'volume-name': self.name})
        else:
            volume_delete = netapp_utils.zapi.NaElement.create_node_with_children(
                'volume-destroy', **{'name': self.name, 'unmount-and-offline':
                    'true'})

        try:
            self.server.invoke_successfully(volume_delete,
                                            enable_tunneling=True)
        except netapp_utils.zapi.NaApiError:
            err = get_exception()
            self.module.fail_json(msg='Error deleting volume %s' % self.name,
                                  exception=str(err))

    def rename_volume(self):
        """
        Rename the volume.

        Note: 'is_infinite' needs to be set to True in order to rename an
        Infinite Volume.
        """
        if self.is_infinite:
            volume_rename = netapp_utils.zapi.NaElement.create_node_with_children(
                'volume-rename-async',
                **{'volume-name': self.name, 'new-volume-name': str(
                    self.name)})
        else:
            volume_rename = netapp_utils.zapi.NaElement.create_node_with_children(
                'volume-rename', **{'volume': self.name, 'new-volume-name': str(
                    self.name)})
        try:
            self.server.invoke_successfully(volume_rename,
                                            enable_tunneling=True)
        except netapp_utils.zapi.NaApiError:
            err = get_exception()
            self.module.fail_json(msg='Error renaming volume %s' % self.name,
                                  exception=str(err))

    def resize_volume(self):
        """
        Re-size the volume.

        Note: 'is_infinite' needs to be set to True in order to rename an
        Infinite Volume.
        """
        if self.is_infinite:
            volume_resize = netapp_utils.zapi.NaElement.create_node_with_children(
                'volume-size-async',
                **{'volume-name': self.name, 'new-size': str(
                    self.size)})
        else:
            volume_resize = netapp_utils.zapi.NaElement.create_node_with_children(
                'volume-size', **{'volume': self.name, 'new-size': str(
                    self.size)})
        try:
            self.server.invoke_successfully(volume_resize,
                                            enable_tunneling=True)
        except netapp_utils.zapi.NaApiError:
            err = get_exception()
            self.module.fail_json(msg='Error re-sizing volume %s' % self.name,
                                  exception=str(err))

    def change_volume_state(self):
        """
        Change volume's state (offline/online).

        Note: 'is_infinite' needs to be set to True in order to change the
        state of an Infinite Volume.
        """
        state_requested = None
        if self.is_online:
            # Requested state is 'online'.
            state_requested = "online"
            if self.is_infinite:
                volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
                    'volume-online-async',
                    **{'volume-name': self.name})
            else:
                volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
                    'volume-online',
                    **{'name': self.name})
        else:
            # Requested state is 'offline'.
            state_requested = "offline"
            if self.is_infinite:
                volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
                    'volume-offline-async',
                    **{'volume-name': self.name})
            else:
                volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
                    'volume-offline',
                    **{'name': self.name})
        try:
            self.server.invoke_successfully(volume_change_state,
                                            enable_tunneling=True)
        except netapp_utils.zapi.NaApiError:
            err = get_exception()
            self.module.fail_json(msg='Error changing the state of volume %s to %s' % (self.name, state_requested),
                                  exception=str(err))

    def apply(self):
        changed = False
        volume_exists = False
        rename_volume = False
        resize_volume = False
        volume_detail = self.get_volume()

        if volume_detail:
            volume_exists = True

            if self.state == 'absent':
                changed = True

            elif self.state == 'present':
                if str(volume_detail['size']) != str(self.size):
                    resize_volume = True
                    changed = True
                if (volume_detail['is_online'] is not None) and (volume_detail['is_online'] != self.is_online):
                    changed = True
                    if self.is_online is False:
                        # Volume is online, but requested state is offline
                        pass
                    else:
                        # Volume is offline but requested state is online
                        pass

        else:
            if self.state == 'present':
                changed = True

        if changed:
            if self.module.check_mode:
                pass
            else:
                if self.state == 'present':
                    if not volume_exists:
                        self.create_volume()

                    else:
                        if resize_volume:
                            self.resize_volume()
                        if volume_detail['is_online'] is not \
                                None and volume_detail['is_online'] != \
                                self.is_online:
                            self.change_volume_state()
                        # Ensure re-naming is the last change made.
                        if rename_volume:
                            self.rename_volume()

                elif self.state == 'absent':
                    self.delete_volume()

        self.module.exit_json(changed=changed)

def main():
    v = NetAppCDOTVolume()
    v.apply()

if __name__ == '__main__':
    main()

I'm using the below yaml code with ansible which is using the one of the python module as above.

# cat storage.yml
- name: Sample Playbook
  hosts: test-cls-mgt
  connection: local
  vars:
   netapp_hostname: test-cls-mgt
   netapp_username: admin
   netapp_password: admin123
  tasks:
  - na_cdot_volume:
     state: present
     name: ansibleVolume
     infinite: False
     aggregate_name: aggr1
     size: 20
     size_unit: mb
     vserver: vs0
     hostname: "{{ netapp_hostname }}"
     username: "{{ netapp_username }}"
     password: "{{ netapp_password }}"

# ansible-playbook storage.yml

PLAY [Sample Playbook] ***************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************
ok: [test-cls-mgt]

TASK [Volume Manager] ****************************************************************************************************************************************
fatal: [test-cls-mgt]: FAILED! => {"changed": false, "failed": true, "msg": "the python NetApp-Lib module is required"}
        to retry, use: --limit @/root/project/kk.retry

PLAY RECAP ***************************************************************************************************************************************************
test-cls-mgt            : ok=1    changed=0    unreachable=0    failed=1

A: I think you may want to try to install netapp-lib Python package on your Ansible control host.
For example with this command: pip install netapp-lib.


text: Q: SiS 671/771 and Lubuntu 20.04 LTS I have installed Lubuntu 20.04 LTS on a Asus K50C, that has a Silicon Integrated Systems 671/771 Graphics Adapter. It can not boot successfully without setting through GRUB nomodeset or GRUB_GFXMODE=1024x768. Also the maximum supported resolution (checked with videoinfo on Grub's command line) is 1024x768, while the laptop supports up to 1366x768. As I have not found a valid procedure, how is it possible to install proper drivers for the SiS 671/771 on Lubuntu 20.04?


text:
Q: Как грамотно сделать редирект через файл hosts? Здравствуйте коллеги!
Сотрудники моего предприятия зависают во вконтакте, башорге и прочих гейпорно сайтах. Просто перекрыть доступ через hosts - мне кажется не интересным. Я хочу чтобы их перенаправляло на stackoverflow. В теории, вроде писать нужно так (в файле hosts):
151.101.1.69   vk.com
151.101.1.69   *.vk.*

К моему сожалению, этот код просто уныло перекрывает доступ к сайту. (Я сие тестировал на разных айпишниках дома и на работе, от системы ничего не зависит).
Вопрос: Как правильно отредиректить юзера черех хост?

A: Вообще проблему можно решить через сервис UserGate, а если хочется чего-то поинтереснее то arp spoofing через, например,  ettercap
sudo nano etc/ettercap/etter.dns

vk.com      A   ru.stackoverflow.com

предварительно добавив все айпишники в таргет.


text:
Q: Performance Issue with ListControl and Observable Dictionary WPF I have an itemsControl bound to an observable dictionary, showing both the Key and Value in two textboxes,
It takes about 15 seconds for the usercontrol to load.
I tried virtualizing stackpanels and switching it to either a listbox or using a regular dictionary, and the lag still occurs
Any ideas what might be causing this, and how I can get it to load faster?
 public partial class WordsView : UserControl, INotifyPropertyChanged
    {
        public WordsView()
        {
            InitializeComponent();

            Dictionarylist.ItemsSource = curDic;
        }

        private ObservableDictionary<string,int> cur_dic = new ObservableDictionary<string, int>(App.PredDic);
        public ObservableDictionary<string, int> curDic
        {
            get { return cur_dic; }
            set
            {
                SetField(ref cur_dic, value, "curDic");

            }
        }
}
}

and my xaml
<UserControl x:Class="Ez.Management.WordsView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Ez.Management"
              DataContext="{Binding RelativeSource={RelativeSource Self}}"
              xmlns:properties="clr-namespace:Ez.Properties"
             xmlns:main ="clr-namespace:Ez"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
       <StackPanel>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <GroupBox Grid.Row="1" Header="Words">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>

                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <ItemsControl x:Name="Dictionarylist" ItemsSource="{Binding curDic}" VirtualizingStackPanel.IsVirtualizing="True"
    ScrollViewer.CanContentScroll="True">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <VirtualizingStackPanel></VirtualizingStackPanel>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Grid Margin="3">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="3*"></ColumnDefinition>
                                            <ColumnDefinition Width="1*"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <TextBlock Text="{Binding Key}" Grid.Column="0" />
                                        <TextBlock Text="{Binding Value}" Grid.Column="1"/>
                                    </Grid>
                            </DataTemplate>
                            </ItemsControl.ItemTemplate>

                    </ItemsControl>

                </Grid>
            </GroupBox>
        </Grid>
    </StackPanel>

</UserControl>

A: ScrollViewer.CanContentScroll is taking time... Try setting it to False. Like,
ScrollViewer.CanContentScroll="False"


text:
Q: App crashes after user logs in with Facebook I got my app onto the App Store.  Everything was working fine on my end, and apparently on the reviewers end.
After the app went live, some users reported crashing immediately after they log in with Facebook.  Here's the code for where I think it's crashing (run right after users log in with Facebook):
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

protocol getUserDataDelegate {
    func gotData()
}

public var userEmailForMixpanel = ""
public var userNameForInvites = ""

class GetUserData: NSObject {

var facebookid:String = ""
var userEmail:String = ""
var userFirstName:String = ""
var userLastName: String = ""
var userGender:String = ""
var userBirthday:String = ""
var delegate = getUserDataDelegate?()

func returnUserData() {
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath:  "me", parameters: ["fields": "id, email, first_name, last_name, gender, birthday"])
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            print("Error: \(error)")
        }
        else
        {
            self.facebookid = (result.valueForKey("id") as? String)!
            self.userEmail = (result.valueForKey("email") as? String)!
            self.userFirstName = (result.valueForKey("first_name") as? String)!
            self.userLastName = (result.valueForKey("last_name") as? String)!
            self.userGender = (result.valueForKey("gender") as? String)!
            //self.userBirthday = (result.valueForKey("birthday") as? String)!

            userEmailForMixpanel = self.userEmail
            userNameForInvites = self.userFirstName

            NSUserDefaults.standardUserDefaults().setValue(userEmailForMixpanel, forKey: "userEmail")
            NSUserDefaults.standardUserDefaults().setValue(userNameForInvites, forKey: "userName")
            NSUserDefaults.standardUserDefaults().synchronize()

            Mixpanel.sharedInstanceWithToken("abdc")
            let mixpanel = Mixpanel.sharedInstance()
            mixpanel.registerSuperProperties(["Gender":self.userGender])

            print(self.facebookid)
            print(self.userEmail)
            print(self.userFirstName)
            print(self.userLastName)
            print(self.userGender)
            //print(self.userBirthday)

            self.checkIfUserExists()
        }
    })
}

func checkIfUserExists() {

    showTutorial = true

    let url:NSURL = NSURL(string: "url")!

    let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        let userTokenDataDictionary:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

        if userTokenDataDictionary ["token"] != nil {
            userAccessToken = (userTokenDataDictionary["token"] as? String)!
            NSUserDefaults.standardUserDefaults().setValue(userAccessToken, forKey: "userAccessToken")
            NSUserDefaults.standardUserDefaults().synchronize()
            print("Token for Existing User:\(userAccessToken)")
            self.finishedGettingData()
        }

        if userTokenDataDictionary ["error"] != nil {
            userAccessToken = (userTokenDataDictionary["error"] as? String)!
            print(userAccessToken)
            print("User needs to be created")
            self.createNewUserFromFacebook()
        }
    }
    task.resume()
}

func createNewUserFromFacebook() {

    let url:NSURL = NSURL(string: "url")!

    print(url)

    let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        let userTokenDataDictionary:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

        if userTokenDataDictionary ["token"] != nil {
            userAccessToken = (userTokenDataDictionary["token"] as? String)!
            NSUserDefaults.standardUserDefaults().setValue(userAccessToken, forKey: "userAccessToken")
            NSUserDefaults.standardUserDefaults().synchronize()
        }

        if userTokenDataDictionary ["error"] != nil {
            userAccessToken = (userTokenDataDictionary["error"] as? String)!
            print(userAccessToken)
        }

        print("Token for New User:\(userAccessToken)")
        self.finishedGettingData()
    }
    task.resume()
}

func checkIfUserHasUsedListenerApp() {

    let accessToken = NSUserDefaults.standardUserDefaults().stringForKey("userAccessToken")!

    let url:NSURL = NSURL(string: "url")!

    print(url)

    let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        let adDataDict:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

        if adDataDict ["used_ListenerApp"] != nil {
            let responseCode = adDataDict.valueForKey("used_ListenerApp") as! Bool
            print(responseCode)
            if responseCode == false {
                Mixpanel.sharedInstanceWithToken("abc")
                let mixpanel = Mixpanel.sharedInstance()
                mixpanel.track("New User Signed Up", properties: ["distinct_id":userEmailForMixpanel])
            }
            if responseCode == true {
                return
            }
        }
    }
    task.resume()
}

func finishedGettingData() {
    self.checkIfUserHasUsedListenerApp()

    Mixpanel.sharedInstanceWithToken("abc")
    let mixpanel = Mixpanel.sharedInstance()
    mixpanel.track("User Logged In", properties: ["distinct_id":userEmailForMixpanel])

    if let actualdelegate = self.delegate {
        actualdelegate.gotData()
    }
  }
}

It's only crashing for some users, not all.  I even tried creating a loop that generates a bunch of user data to run it through this code, and I couldn't replicate the crash.
Any advice would be appreciated a lot.
UPDATE
It looks like it has to do with Facebook not returning an email address.  I'll keep looking though.

A: I figured it out.  Part of the problem was that Facebook wasn't returning an email address for some users, so I checked for that and if it didn't return an email, I created one with their Facebook ID to get them through the login process (fbid@facebook.mywebsite.com).
Another part of the problem was that some users had logged into my website using an email address that was also assigned to their Facebook account, and tried logging in with Facebook on the app.  I fixed this by having it merge their Facebook info with their existing account during the authorization process if an existing account is found.


text:
Q: oracle 11g beginner - how to display data from two tables Complete beginner to Oracle 11g here.
If I have two tables, with some overlapping attributes but no relation, how do I display all the data in one table?
Example:
TABLE A has a PK, a fname, lname.
TABLE B has a PK, a fname, lname, phone.

I'd like to display the contents of TABLE A and TABLE B in one table.
I thought I could use a UNION, but you have to have the same number of columns; and since TABLE B has 3 columns, I get an error: ORA-01789: query block has incorrect number of result columns.

A: You could insert a "fake" column into the select for TableA so that two two sets line up:
select PK, fname, lname, null as phone from TableA
union all
select PK, fname, lname, phone from TableB

This would effectively merge the two tables.


text:
Q: Giving remote access to files for only a single directory on a Linux server I need to give a user named "Bert" access to one directory (/var/www/application/thisDirectory/) on my Linux server.
Initially, I tried to use FTP (actually SSH).
My first thought was to chroot Bert and make his home /var/www/application/thisDirectory/.  Problem is this requires /var/www/application/ to be owned and only available to root which is not acceptable.
I then changed Bert's home directory to /home/Bert/.  Next, I put a symbolic link in Bert's home directory and pointed to /var/www/application/thisDirectory, but I don't believe this was permitted because Bert was chroot'd and is considered a security risk, and I couldn't get it to work.  Any thoughts how it can work?
Next, leaving Bert's home directory as /home/Bert/, I moved /var/www/application/thisDirectory to /home/Bert/thisDirectory/, and added symbolic link /var/www/application/thisDirectory/ to point to /home/Bert/thisDirectory/.  While this technically worked, it caused havoc with my Git version control, and I switched back.
If I can't get this working, I suppose I could look into Samba, but would rather not.
Thank you

A: I used this way and i can tell it works,
in your /etc/ssh/sshd_config, after the change reload the sshd service
Match User bert
ChrootDirectory /home/%u
ForceCommand internal-sftp

add the user
useradd -m -s /bin/false bert
passwd bert

permission for sftp
chown root:root /home/bert

create the directory for bert user under my the root of my webserver:
mkdir /srv/www/htdocs/bertdir
chown bert:wwwrun /srv/www/htdocs/bertdir

Create the mountpoint under home of bert user for mount the directory:
mkdir /home/bert/www

Now we mount the directory
mount --bind /srv/www/htdocs/bertdir/ /home/bert/www/

Now i used my sftp service:
sftp> ls
bin          public_html  www

Now i upload the /etc/passwd
sftp> put /etc/passwd
Uploading /etc/passwd to /www/passwd


text:
Q: QGIS changing canvas CRS defaults to imported layer I am having trouble setting the mapCanvas CRS in QGIS 3.0 using Python. I am effectively trying to replicate what happens when you change the CRS by clicking on the bottom-right corner of the Canvas and selecting a CRS.
When I set the CRS using iface.mapCanvas().setDestinationCrs(crs) the CRS changes. However when I import a layer, the CRS changes to the layer's CRS.
For instance, in the code below:

*

*Open a new project.

*Set the CRS to 4326.

*Import Google Satellite image with the CRS 3857.

*Set the CRS to 4326 again.

*QGIS shows a CRS of 3857.

When I run the same code again but add a print statement between adding the layer and setting the CRS the second time, the code works. I am not sure why this works.
from qgis.core import (
    QgsCoordinateReferenceSystem,
    QgsRasterLayer,
    QgsProject
    )
from qgis.utils import iface

def get_google_layer():
    google_uri = "type=xyz&url=https://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D"
    return QgsRasterLayer(google_uri, 'Google', 'wms')

def change_map_canvas():
    iface.newProject(False)
    crs = QgsCoordinateReferenceSystem(4326)

    iface.mapCanvas().setDestinationCrs(crs)
    iface.mapCanvas().refresh()
    assert iface.mapCanvas().mapSettings().destinationCrs() == crs

    l = get_google_layer()
    QgsProject.instance().addMapLayer(l)

    #print("Here")

    iface.mapCanvas().setDestinationCrs(crs)
    assert iface.mapCanvas().mapSettings().destinationCrs() == crs

A: By further debugging I was able to find the root of the problem and solve it.
The CRS would not change until after the entire python method change_map_canvas(), but the CRS would change correctly if I added the Print statement halfway through. This led me to think that the ActiveWindow or Application was not refreshing properly. The function would work correctly if the program had already been running, just not from start up.
By adding QApplication.instance().processEvents() after adding the map layer, the script works as expected. The full simplified code is below:
from PyQt5.QtWidgets import (
    QApplication
    )

from qgis.core import (
    QgsCoordinateReferenceSystem,
    QgsRasterLayer,
    QgsProject
    )
from qgis.utils import iface

def get_google_layer():
    iface.newProject(False)
    google_uri = "type=xyz&url=https://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D"
    return QgsRasterLayer(google_uri, 'Google', 'wms')

def change_map_canvas():
    iface.newProject(False)
    crs = QgsCoordinateReferenceSystem(4326)

    l = get_google_layer()
    QgsProject.instance().addMapLayer(l)
    QApplication.instance().processEvents()

    QgsProject.instance().setCrs(crs)


text:
Q: JPQL create Query Throws parsing exception The following query fails when I use createQuery
select MAX(kcc.order) From KPIConfiguration kcc join EnumerationValue ev on kcc.level = ev.enumerationValueId join EnumerationValue ev1 on kcc.dataSource = ev1.enumerationValueId where ev1.key = :dataSource

with the following exception

Exception: "Encountered "join EnumerationValue ev" at character 49,
but expected: [".", "FETCH", "INNER", "JOIN", "LEFT", ]."
while parsing JPQL "select MAX(kcc.order) From KPIConfiguration kcc
join EnumerationValue ev on kcc.level = ev.enumerationValueId join
EnumerationValue ev1 on kcc.dataSource = ev1.enumerationValueId where
ev1.key = :dataSource"

but when I use createNativeQuery as follows, it works.
select MAX(kcc.ORDERS) From KPI_CHECKLIST_CONF kcc join ENUMERATION_VALUE ev on kcc.LEVELS = ev.ENUMERATION_VALUE_ID join ENUMERATION_VALUE ev1 on kcc.DATA_SOURCE = ev1.ENUMERATION_VALUE_ID where ev1.ENUMERATION_KEY = ?1

I couldn't understand the reason. What am I missing?


text:
Q: TomEE startup error: Cannot create unique file, please set java.io.tmpdir to a writable folder or create work folder While starting up my application from within IntelliJ 14 the app server TomEE 7.0.62 gives following error message:
cannot create unique file, please set java.io.tmpdir to a writable folder or create work folder
at org.apache.openejb.assembler.DeployerEjb.<clinit>(DeployerEjb.java:109)

System:
OSX, IntelliJ 14, TomEE-Plume 7.0.62 (homebrew), Java 8 (homebrew cask)
Java version:
/usr/libexec/java_home -V
Matching Java Virtual Machines (1):
1.8.0_60, x86_64:   "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home

Deployment: The basic Hello World sample app from Vaadin Framework 7
Infos:

*

*TomEE startup over Terminal with startup.sh works ok, default tomcat welcome screen is shown on localhost:8080

*Tried to add JVM option to set java.io.tmpdir to a different directory with chmod 777 privileges. VM options: -Djava.io.tmpdir=<new temp dir>

*Tried to export env variable with export _JAVA_OPTIONS=-Djava.io.tmpdir=<new temp dir>

*With Tomcat 8 hello world app works ok

Full error log:
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.openejb.util.Classes.forName(Classes.java:64)
at org.apache.openejb.config.rules.ValidationBase.loadClass(ValidationBase.java:151)
at org.apache.openejb.config.rules.CheckMethods.check_unusedCreateMethods(CheckMethods.java:318)
at org.apache.openejb.config.rules.CheckMethods.validate(CheckMethods.java:55)
at org.apache.openejb.config.rules.ValidationBase.validate(ValidationBase.java:50)
at org.apache.openejb.config.AppValidator.validate(AppValidator.java:101)
at org.apache.openejb.config.ValidateModules.deploy(ValidateModules.java:38)
at org.apache.openejb.config.ConfigurationFactory$Chain.deploy(ConfigurationFactory.java:403)
at org.apache.openejb.config.ConfigurationFactory.configureApplication(ConfigurationFactory.java:971)
at org.apache.openejb.config.ConfigurationFactory.getOpenEjbConfiguration(ConfigurationFactory.java:526)
at org.apache.openejb.config.ConfigurationFactory.getOpenEjbConfiguration(ConfigurationFactory.java:591)
at org.apache.openejb.assembler.classic.Assembler.getOpenEjbConfiguration(Assembler.java:459)
at org.apache.openejb.assembler.classic.Assembler.build(Assembler.java:438)
at org.apache.openejb.OpenEJB$Instance.<init>(OpenEJB.java:150)
at org.apache.openejb.OpenEJB.init(OpenEJB.java:298)
at org.apache.tomee.catalina.TomcatLoader.initialize(TomcatLoader.java:256)
at org.apache.tomee.catalina.ServerListener.install(ServerListener.java:168)
at org.apache.tomee.catalina.ServerListener.lifecycleEvent(ServerListener.java:55)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)
at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:110)
at org.apache.catalina.startup.Catalina.load(Catalina.java:638)
at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)

Caused by: org.apache.openejb.OpenEJBRuntimeException: cannot create     unique file, please set java.io.tmpdir to a writable folder or create work folder
at org.apache.openejb.assembler.DeployerEjb.<clinit>(DeployerEjb.java:109)
... 32 more

Thank you all..

A: you can add openejb.system.apps=false in conf/system.properties or just export CATALINA_TMPDIR to a "new tmp dir value"


text:
Q: Default CListCtrl data is coming sorted I am reading data from file line by line and putting the tokens of each line in a vector tmpstrArr.Then adding the tokens for each row in CListCtrl but CListCtrl is showing sorted data in descending order.I am confused because while debugging elements are going in correct order same as available in the file.I want my CListCtrl data in original form as in the file and not in sorted form.Also i have checked properties window of the CListCtrl where sort=None is selected.
LVITEM lvi;
CString strItem;

m_listctrl.InsertColumn(0, _T("col 1"), LVCFMT_LEFT, 100);
m_listctrl.InsertColumn(1, _T("col 2"), LVCFMT_LEFT, 100);

for(int i=0;i<tmpstrArr.size();i++)
{
    strItem=tmpstrArr.at(i).c_str();
    lvi.iItem = 0;
    lvi.iSubItem = i;
    lvi.pszText = (LPTSTR)(LPCTSTR)(strItem);
    //lvi.iImage = i%8;// There are 8 images in the image list
    if(i==0)
    {
        lvi.mask =  LVIF_IMAGE | LVIF_TEXT;
        m_listctrl.InsertItem(&lvi);
    }
    else
        m_listctrl.SetItem(&lvi);
}

A: You are adding each item with item position 0. So the last item you just inserted is always the first in the list.
See docs.
If you want to get the same order like in the array, you need to add the item with
 lvi.iItem = m_listCtrl.GetItemCount();
 // or use INT_MAX (see docu)
 lvi.iItem = INT_MAX;


text:
Q: Python 3.5: from multiprocessing import Pool ImportError: cannot import name 'Pool' from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

I use this example about multiprocessing in Python Documentation but I always get an error:
    from multiprocessing import Pool
ImportError: cannot import name 'Pool'

I searched a lot but cannot find out the reason. Please help me. Thank you :)


text:
Q: VehicleBody Node on airplanes? Godot I am trying to make a 3D game in Godot with cars, airplanes etc. The thing is: I wanted to use a RigidBody node, but VehicleBody poped up. Should I use RigidBody or VehicleBody on an airplane?
Thanks in advance!

A: The node VehicleBody is not intended for airplanes. I suggest against using it for that, the reason is that it contains logic regarding whether or not the wheels are in contact with the ground.
To be clear, that does not mean you need VehicleBody to make cars, just that it will save you some work.

I'm going to recommend Godot Recipes Simplified Airplane Controller. Which, by the way, is based on KinematicBody instead of RigidBody.


text:
Q: Is it unPythonic to ask the package's user to extend a class, but the user cannot instantiate it? I'm writing the Python bindings of a C library which allows the user to create custom "classes" in C and instantiate them through another object, something like:
my_class = create_class(init_callback, finalize_callback, ...);
instance1 = manager_create_object(some_manager, my_class, ...);
instance2 = manager_create_object(some_manager, my_class, ...);

Unfortunately, the C language is not object-oriented, so this library uses the concept within the limits of what the language offers.
In Python, for a user to define its own class, I'd like to use the concept of a Python class:
class MyClass(package.BaseClass):
    def __init__(self, ...):
        ...

    def _finalize(self, ...):
        ...

instance1 = some_manager.create_object(MyClass, ...)
instance2 = some_manager.create_object(MyClass, ...)

I cannot instantiate the object directly with MyClass() because it needs said manager (see manager_create_object() above).
Is it weird/unPythonic to ask the user to extend the package's class (package.BaseClass in this example) without being able to instantiate the derived class (MyClass) directly with MyClass()? This is mostly for a plugin interface, where we would need the user to define one or more classes in a Python module file.

A: It's not unusual to insist that the user (client side) supply a local implementation of certain capabilities, especially if you can supply examples and/or templates for the needed support.  Many suppliers do this, as they cannot cover all of the implementations.
However, make sure that you give a wide variety of examples.  You want to make it easy for your users.  Better yet, deliver files that constitute working implementations for several popular environments.


text:
Q: IIS reverse proxy using regular proxy I use an IIS as reverse proxy. However, the target page can only be reached via a "regular" proxy.
Currently I always get a bad gateway error. My guess is that the rewrite module of the IIS does not consider the proxy settings of the system and therefore does not get a connection to the target page.
Do I have to define own proxy settings for the rewrite module? Or is it even possible to use a reverse proxy behind a normal proxy with the IIS?

A: According to your description, I suggest you could try to add the proxy setting in the applicatiohost.config file.
This will make all the request to use the proxy to send to another server.
More details, you could refer to below setting:
Related article: https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/network/defaultproxy-element-network-settings
Applicationhost.config file path:
C:\Windows\System32\inetsrv\config\

Setting example:
<system.net>
    <defaultProxy>
      <proxy
        proxyaddress="http://10.0.2.231:42"
        bypassonlocal="true"
      />
    </defaultProxy>
</system.net>


text:
Q: Passing environment variables from one module to another in Angular 7 I am working on project that has Two Apps(App A, App B). There are around 100 components used by both apps. So I have created an Angular Library and organised those components in Modules. Everything works fine. I am stuck when i need to pass environment to the modules in the library.
@NgModule({
 imports:[
 LibModule2, // need to pass environment from LibModule1
 LibModule3,
]
})
export class LibModule1{
  export function forRoot(environment):ModuleWithProviders{
   return {
       ngModule:LibModule1,
       providers:[
        {provider:ENV, useValue:environment}
       ]
   }
 }
}

//App1

@NgModule({
  imports:[
   LibModule1.forRoot(environment)
  ]
})
export class AppModule(){}

I only need LibModule1 in the Apps. But need to pass environment to LibModule2, LibModule3 as well. how can I do this? Am i approaching it in a wrong way?

A: I have such a problem for a while and best solution i found is this:
Add a static Class to Your Library Modules:
export class Lib1Module {
  static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: Lib1Module,
      providers: [{provide: 'config', useValue: config}]
    };
  }
}

export class Lib2Module {
  static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: Lib2Module,
      providers: [{provide: 'config', useValue: config}]
    };
  }
}

Then pass environment from app.module to your Lib1Module & Lib2Module Like this:
imports:[
    CommonModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    HttpClientModule,
    RouterModule,
    BrowserModule,
    FormsModule,
    GigLib1Module.forRoot(environment),
    GigLib2Module.forRoot(environment)
]

Now, environment file injected into your library.
How to use it:
environment :any
constructor(@Inject('config') config)
{
     if (config) {
     this.environment = config;
   }
}

Now Environment can be changed from Main Project easily.


text:
Q: How to convert an list generated from another class I have made this class that generates an ArrayList() of random integers:
import java.util.*;

public class RandomListGenerator {
    public static void main(String[] args){
        // Ask for an integer as user input.
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter an integer between 1 and 10: ");
        int inp = input.nextInt();

        List<Integer> arr = genRandArrOfInts(inp);
        System.out.println("Generated a list of random integers: "+arr);
    }

    public static List<Integer> genRandArrOfInts(int n) {
        ArrayList<Integer> list = new ArrayList<>(n); // Create new ArrayList() of length n
        Random r = new Random();
        for (int i = 0; i < n; i++) {
            list.add(r.nextInt(10 + 10) - 10); // We get random ints in range max = 10 and min = -10
        }
        return list;
    }
}

When I run this class by itself, it works fine, and I get this output:
Please enter an integer between 1 and 10:
10
Generated a list of random integers: [0, -1, -3, -8, -9, 1, 3, 0, 8, -1]

But when I tried to use it in another class and print it like so:
public class Lab2Array {
    public static void main(String[] args){
        randomListGenerator list = new randomListGenerator();
        System.out.println("Generated this list of random integers: "+list);
    }
}

The output I got was:
Generated this list of random integers: randomListGenerator@15aeb7ab

How do I convert this so that I get the ArrayList<Integer>? I need to use the generator in other classes as well so I wanted to make it as it's own class instead of inside the lab2Array-class

A: Call the method that actually returns the list of ints that you want.
Also, no need to instantiate an object. Your method is static, so it can be called without an object.
public class Lab2Array {
    public static void main(String[] args){
        System.out.println("Generated this list of random integers: "+ RandomListGenerator.genRandArrOfInts(10));
    }
}


text:
Q: Sending a large number of mails causing problems on CentOS 6 / Plesk 10 I have a VPS running CentOS 6. When the system tries to send daily newsletter, after some time (e.g. after sending about 2000 emails), I get error "Unable to send mail" and the system memory goes really high. Till this moment, the mails are delivered normally.
The rest symptoms are:

*

*I cannot see anything on /var/log/maillog (File seems not to be written)

*All files on /var/spool/mail have 0 bytes size.

*From time to time on httpd log I get errors like: /usr/sbin/sendmail: error while loading shared libraries: libc.so.6: cannot open shared object file: Error 23
"Activate mail service on domain" setting in Plesk is deactivated.
Any idea on what's going wrong here?

A: postfix (version 2.2 up) does rate limiting with directives in /etc/postfix/main.cf:
smtpd_client_message_rate_limit=1000
anvil_rate_time_unit = 60s

which means a client can only send 1000 mails in 60 seconds.
There are also other systems that can limit message sending as addons to postfix (sqlgrey is an example), they usually inject in /etc/postfix/master.cf or main.cf smtpd_client_restrictions (although not limited to those).
However, from your description, I think that is the least of your problems. You seem to have a wrong or broken version/package installed. (wrong libc, wrong permissions, perhaps wrong file paths).


text:
Q: Accessing Binding from Type Converter? I've spent a fair bit of time trying a number of different ways to solve an issue I'm having, to no avail, so I'm hoping someone here can help.
I have a Text Box element with Two-Way binding, which utilises a Type Converter to convert the value from a string to a custom Data type, say, MyCustomType. This is working fine, however due to a change in my project's requirements, I now need to perform extra processing prior to the conversion taking place.
In order to perform this extra processing, however, I need to be able to access the "source" text box, or the binding context. Neither of which I have been able to access.
Is there any way to access the source text box, from a Type Converter's ConvertFrom() method?
I have tried to use the ITypeDescriptorContext parameter passed (by WPF) to the ConvertFrom() method, however most of the properties therein are null.
i.e.
public class MyCustomTypeConverter : TypeConverter
{
   ...
   public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
   {
      // Context is
      return new MyCustomType(value);
   }
   ...
}

I have also tried using a MultiValueConverter, and avoiding the Type converter entirely, however this led to a LOT of extra code, and didn't really help. I would prefer to avoid going down this route, as a Type Converter is much more elegant.
Any advice/assistance would be greatly appreciated! :)

A: EDIT: I ended up changing the way that validation is performed (using INotifyDataError instead of validating on exceptions), and ended up re-writing the ConvertFrom() method in my Type Converter, such that I wouldn't need to access the TypeDescriptor's context anymore.
I wouldn't recommend using the context from the ConvertFrom() method, as it (being a private property) isn't guaranteed that the property will exist in the future (though I haven't read anything to support this, it is best to assume that private properties can be removed/renamed without notification from the MS development team), and it isn't set when setting a property's value programmatically, like so:
TypeConverter converter = TypeDescriptor.GetConverter(typeof(MyCustomType));
converter.ConvertFrom(mySourceValue);

If you're reading this and really need to access the context parameter, you can do so using my method below, at your own risk.

I was able to solve this by interrogating the ValueConverterContext class, and accessing the private _targetElement field, like this:
var sourceTextBox = context.GetType().GetField("_targetElement", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(context)

Thanks for your help nonetheless. :)
edit: To access the Bindings for this TextBox, you can simply cast sourceTextBox as TextBox and then:
var BindingExpression = sourceTextBox.GetBindingExpression(TextBox.TextProperty);


text:
Q: Magento how to get search product always come on first in result I want to get search product come always first position on result.
for ex.
My search product is Chocolate Rabbit Father Set but it is coming at 8th position.
before this some products are coming like Chocolate Rabbit Grandparents, Chocolate Rabbit Baby, Milk Rabbit Baby so more...
is there any suggestion how to come search product will always come on first position.
Thanks


text:
Q: Kotlin equivalent of Swift Expectations/Promises I am trying to write some UnitTests for my native mobile applications, but have ran into a roadblock in my Android Tests. Specifically, I am struggling to find an example of Kotlin's version of Swift's Expectations/Promises..
I've found examples of Kotlin Promises, but they seem to be way more complicated than needed...
For example, here is a test for the login API function in my iOS project:
func testLogin() {

    /// Prepare for login
    if CURRENT_USER != nil {
        logout()
    }

    /// Login
    let promise = expectation(description: "User is logged in.")

    // 1. Given
    var isSuccess: Bool = false

    // 2. When
    User.login(username: maleUsername, password: malePassword, success: {
        isSuccess = true
        promise.fulfill()
    }) { (_, agreeToTerms) in
        XCTFail()
    }
    wait(for: [promise], timeout: maxTimeOut)

    // 3. Then
    XCTAssertNotNil(CURRENT_USER)
    XCTAssertTrue(isSuccess)

    /// Logout
    logout()
}

This is pretty simple to me. I have an asynchronous method login that has two possible completion blocks: success and failure; and I need to wait for one of them to complete before evaluating. To do this, I create a promise before the call, then I fulfill the promise in the two completion blocks, and I wait for the promise to fulfill before running my assertions.
Now in Kotlin, I have a similar test:
private val loginFragment = LoginFragment()

@Test
fun loginTest() {

    val username = ""
    val password = ""

    // TODO: Create Promise

    loginFragment.loginViewModel
            .login(username, password)
            .observe(loginFragment, Observer {
                loginFragment.activity?.onResult(it?.result,

                        onSuccess = {
                            // TODO: Fill Promise
                        },
                        onValidationError = {
                            // TODO: Fail Test
                        })
            })

    // TODO: Assertions

}

But I can't find an equivalent of swift's promises..
Does one exist in Kotlin? If not, how would I implement a version of my Swift's testLogin method in Kotlin?

A: You can use Kotlin coroutines, for example:
@Test
fun loginTest() {
    val result = runBlocking {
        val loginResult = login()
        loginResult
    }
    if (result == "Success") {
        // do your work when Success
    } else {
        // do your work when Error
    }
}
suspend fun login(): String = suspendCoroutine { continuation ->
    val username = ""
    val password = ""
    loginFragment.loginViewModel
    .login(username, password)
    .observe(loginFragment, Observer {
        loginFragment.activity?.onResult(it?.result,

                    onSuccess = {
                        continuation.resume("Success")
                    },
                    onValidationError = {
                        continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

                    })
    })
}

To use coroutines you need to add next lines to app's build.gradle file dependencies:

final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"

Hope it will help.

A: I found this Kotlin Promise lib closer to Swift Promises.
Using this library your test would like.
@Test
fun loginTest() {
    val username = ""
    val password = ""

    Promise<Boolean, Exception> { promise ->
        loginFragment.loginViewModel
            .login(username, password)
            .observe(loginFragment, Observer {
                loginFragment.activity?.onResult(it?.result,

                    onSuccess = {
                        promise.resolve(true)
                    },
                    onValidationError = {
                        promise.reject(Exception("Login error"))
                    })
            })
    }.whenComplete {
        when (it) {
            is Promise.Result.Success -> {
                assert(it.value)
            }
        }
    }
}

A: I wrote in 20 minutes an implementation that looks like swift's expectation, but he is not sophisticated, use only for simple cases it does the work well.
typealias XCTestExceptionHandler = (KTTestException?) -> Unit

fun TestCase.expectation(description: String): KTTestExpectation {
    return KTTestExpectation(description)
}

fun TestCase.waitFor(expectation: KTTestExpectation, timeout: Long, handler: XCTestExceptionHandler) {
    expectation.handler = handler

    Thread.sleep(timeout)
    expectation.timedOut()
}

class KTTestExpectation(private val description: String) {
    private var isFulfilled = false
    var handler: XCTestExceptionHandler? = null

    fun fulfill() {
        Handler(Looper.getMainLooper()).postDelayed({
            invokeHandlerWith(null)
        }, 2)
    }

    fun timedOut() {
        invokeHandlerWith(KTTestException("Timed out: $description"))
    }

    private fun invokeHandlerWith(error: KTTestException?) {
        if (isFulfilled) return
        isFulfilled = true
        handler?.invoke(error)
        error?.let { Assert.fail("Timed out: $description") }
    }
}

class KTTestException(message:String): Exception(message)

Using:
    fun testExpectation() {
        var nb = 0
        val expectation = expectation("Test")

        MyAsyncFunc {
            nb = 5
            expectation.fulfill()
        }

        waitFor(expectation, 1000) { error ->
            assertEquals(5, nb)
        }
    }

If anyone has the courage to convert the original code to Kotlin Here are the links:
https://github.com/apple/swift-corelibs-xctest/blob/main/Sources/XCTest/Public/Asynchronous/XCTWaiter.swift
https://github.com/apple/swift-corelibs-xctest/blob/main/Sources/XCTest/Public/Asynchronous/XCTestExpectation.swift


text:
Q: How to download `CameraClipPreview` from previewUrl I have set up pub/sub event subscriptions and I am now getting event messages into my GCP Console.
My nest doorbell comes with a preview URL when certain events are triggered, here is the payload:
{
  "eventId" : "7feb3438-1dbf-4e32-849a-805d5887c48f",
  "timestamp" : "2019-01-01T00:00:01Z",
  "resourceUpdate" : {
    "name" : "enterprises/project-id/devices/device-id",
    "events" : {
      "sdm.devices.events.CameraClipPreview.ClipPreview" : {
        "eventSessionId" : "CjY5Y3VKaTZwR3o4Y19YbTVfMF...",
        "previewUrl" : "https://previewUrl/..."
      }
    }
  }
  "userId" : "AVPHwEuBfnPOnTqzVFT4IONX2Qqhu9EJ4ubO-bNnQ-yi",
  "resourceGroup" : [
    "enterprises/project-id/devices/device-id"
  ]
}

The previewUrl comes in fine, and looks something like https://nest-camera-frontend.googleapis.com/frontend/encrypted/clippreview/AhHSDAh687gOY88G8yg8-YGgyG788786gfFtOLyGgVvdYDgdGDgdPDdpD9d9D-5IX
However when I paste this into the browser I get the 401 Bad request Google page.
Is the previewURL not meant to be accessed in a browser? How do I access/download the preview video?

A: I believe you have to download it first, can you try this, replacing {access-token} with your OAuth access token?
curl -H 'Authorization: Bearer {access-token}' https://nest-camera-frontend.googleapis.com/frontend/encrypted/clippreview/AhHSDAh687gOY88G8yg8-YGgyG788786gfFtOLyGgVvdYDgdGDgdPDdpD9d9D-5IX


text:
Q: Dropdown List is Refusing to Bind Records Correctly I am trying to populate my dropdownlist but I am getting the following error

ArgumentNullException: Value cannot be null. (Parameter 'items')

In my View Controller I am using the following:
return View(await _context.MISobject.Include(C => C.StafMemeberdsOCM1).Include(C => C.StafMemeberdsOCM2).Include(c => c.MISPrioritys).ToListAsync());

And in my Class I have the following properties:
public int? Priority { get; set; }
[ForeignKey("Priority")]
public virtual MISPriority MISPrioritys { get; set; }
public IEnumerable<MISPriority> MISPriorityList { get; set; }

Obviously the reason the error is because MISPriorityList  is empty it does not know about the data so how do I fetch the records correctly to ensure the items appear in the drop down list. As you can see from screen shot below there is data in the MISPrioritys table.

A: Add MISPriority  to MISobject.
var mISobject = await _context.MISobject.Include(C => C.StafMemeberdsOCM1).Include(C => C.StafMemeberdsOCM2).Include(c => c.MISPrioritys).ToListAsync();

var mISPriorityList = _context.MISPriority.ToList();

mISobject.MISPriorityList = mISPriorityList;

return View(mISobject);


text:
Q: Disable highlight of selected element I am trying to disable the highlight of selected elements.
This is what it currently looks like:

Here is what I am trying to achieve:

The only way for there to be no blue glow is to click where there isn't an image button, but even then it reappears every time on the first button when I click the extension icon.
I came across the question Remove Safari/Chrome textinput/textarea glow earlier on StackOverflow, but the CSS properties -webkit-appearance, outline, outline-color, and outline-style did not fix anything.
I have a GitHub repository at https://github.com/Usernamer/EmojiChrome.

A: This glow is the highlight of the focused input element.
You need a CSS rule for the :focus pseudo-selector (inline for example, but best contained in a separate file)
<style>
  input:focus { outline: none; }
</style>


text:
Q: how to design full text search algorithm where keyword quantity is huge (like Google Alerts)? I am building something very similar to Google Alerts. If you don't know what it is, consider the following scenario,

*

*Thousands of new textual articles, blog posts influx everyday

*Each user has a list of favorite "keywords" that he'd like to subscribe to

*There are million users with million keywords

*We scan every article/blog post looking for every keyword

*Notify each user if a specific keyword matches.

For one keyword, doing a basic full text search against thousands of articles is easy, but how do make a full text search effectively with million keywords?
Since I don't have a strong CS backtround, the only idea I came of is compiling all keywords into regex, or automata, will this work well? (Like Google's re2)
I think I am missiong some thing important here. Like compiling those keywords into some advanced data structure. Since many keywords are alike (e.g. plural form, simple AND, NOT logic, etc). Are there any prior theory I need to know before head into this?
All suggestions are welcome, thanks in advance!

A: I can think of the following: (1) Make sure each search query is really fast. Millisecond performance is very important. (2) Group multiple queries with the same keywords and do a single query for each group.
Since different queries are using different keywords and AND/OR operations, I don't see other ways to group them.


text:
Q: Slide animation custom alert activity I have custom alert dialog as activity and I want to animate when the view appear and when exit, the first one works (when appear) but the second one doesn't work, I don't know how animate when exit (click outside) if someone can help me thank you in advance
public class CustomAlertActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(200, 255, 0, 0)));

        ...

        overridePendingTransition(R.anim.slide_out_down, R.anim.slide_in_out_up);
    }

}

slide_out_down.xml
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator" >
    <translate
        android:fromYDelta="-100%p"
        android:toYDelta="0"
        android:duration="1000" />"
    />
</set>

slide_in_out_up.xml
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_interpolator" >
    <translate
        android:fromYDelta="0"
        android:toYDelta="-100%p"
        android:duration="1000" />"
    />
</set>

manifest.xml
<activity android:name=".CustomAlertActivity"
            android:theme="@android:style/Theme.Dialog"/>

Custom alert activity
I also try this on MainActivity.class
  public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, CustomAlertActivity.class);
                ActivityOptions options =
                        ActivityOptions.makeCustomAnimation(MainActivity.this, R.anim.slide_out_down, R.anim.slide_in_out_up);
                startActivity(intent, options.toBundle());
 }

Solution:
public class CustomAlertActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(200, 255, 0, 0)));

            ...

        getWindow().getAttributes().windowAnimations = R.style.CustomDialog;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_out_down, R.anim.slide_in_out_up);
    }

}

styles.xml
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowEnterAnimation">@anim/slide_out_down</item>
        <item name="android:windowExitAnimation">@anim/slide_in_up</item>
    </style>

A: Add new style in styles.xml like this :
<style name="DialogTheme">
    <item name="android:windowEnterAnimation">@anim/slide_out_down</item>
    <item name="android:windowExitAnimation">@anim/slide_in_out_up</item>
</style>

Then Call Animation on click Like This :
int style = R.style.DialogTheme
dialog.getWindow().getAttributes().windowAnimations = style;

Hope So it will work if not please feel free to ask .

A: You need to override finish of your activity and call the same method:
@Override
public void finish() {
    super.finish();
    overridePendingTransition(R.anim.slide_out_down, R.anim.slide_in_out_up);
}