text:
Q: Panel positioning with the Firefox Add-on SDK I am trying to make some headway positioning my panel in an Add-on make with the new SDK.
I see that the documentation shows only one way to control the position of a panel, and that is by passing an anchor when you show() it:

show(anchor)
Displays the panel. [ anchor : handle ]
A handle to a DOM node in a page to which the panel should appear to
  be anchored. If not given, the panel is centered inside the most
  recent browser window. Note that it is not currently possible to
  anchor panels in this way using only the high level APIs.

Ideally, I'd like the anchor to be the widget that the panel appears anchored to when that widget is clicked, but the widget is not a DOM node in a page so I guess not...
I can probably work around this, but I can't even find a working example of how to anchor the panel to a DOM node. When I pass back a DOM node in a contentScript through port like this:
lib/main.js
  var scraper = pageMod.PageMod({
    include: ['*'],
    contentScriptWhen: 'ready',
    contentScriptFile: [data.url('jquery-1.6.2.min.js'), data.url('scraper.js')],
    onAttach: function(worker){
      worker.port.on('pageLoaded', function(page){
        widget.panel.show(page.anchor);
      });
    }

data/scraper.js
$('body').append('

.

');

var anchor = $('#anchor-to-me').get();
self.port.emit('pageLoaded', { anchor : anchor  });

I get the following console error:
error: An exception occurred.
Traceback (most recent call last):
  File "resource://jid1-wuvxefqtmptsnw-at-jetpack-addon-kit-lib/panel.js", line 147, in show
    let document = getWindow(anchor).document;
  File "resource://jid1-wuvxefqtmptsnw-at-jetpack-addon-kit-lib/panel.js", line 345, in getWindow
    let anchorWindow = anchor.ownerDocument.defaultView.top;
TypeError: anchor.ownerDocument is undefined

Any info to help me successfully anchor to a DOM element, or find some other way to position the panel would be great.
Thanks.

A: const panel = require("panel").Panel({
  width: 240,
  height: 320,
  contentURL: data.url("foo.html"),
  contentScriptFile: [data.url("jquery-1.4.4.min.js"),
                      data.url("panel.js")]
});

const widget = widgets.Widget({
  id: "some-id",
  label: "Some label",
  contentURL: data.url("icon.png"),
  //panel: panel,
  onClick: function(view) { /* cool stuff */
     view.panel = panel;
  }
});

Instead of using mainPanel.show(),  use view.panel = mainPanel;. It will solve the problem bcz I did the same.

A: When you define your widget, you can add a panel property that is the instance of your panel:

[ panel : Panel ]
An optional panel to open when the user clicks on the widget. Note: If
  you also register a "click" listener, it will be called instead of the
  panel being opened. However, you can show the panel from the listener
  by calling this.panel.show().

Here's an example ( unfortunately there isn't an example of this in the docs ):
const panel = require("panel").Panel({
  width: 240,
  height: 320,
  contentURL: data.url("foo.html"),
  contentScriptFile: [data.url("jquery-1.4.4.min.js"),
                      data.url("panel.js")]
});

const widget = widgets.Widget({
  id: "some-id",
  label: "Some label",
  contentURL: data.url("icon.png"),
  panel: panel,
  onClick: function() { /* cool stuff */ }
});


text:
Q: Workbooks.Open (URL) + Cell Value Workbooks.Open ("www.google.com" & ThisWorkbook("Summary").Range("C3") & ".xls")

I am trying to open a link that depends on what is posted in a cell. So the document might be named "File1" or "File2" and I would like the user to type that into cell C3 and click a button that downloads that file. The formula I have wont support concatenation with cells. Any other options?
Thanks!

A: Answered my own question by defining the cell path...so i put:
Set userID = Worksheets("Summary").Range("C3")
and in the URL I put
Workbooks.Open ("www.google.com" & userID & ".xls")

redpajama_set_name: RedPajamaStackExchange


text:
Q: $L^{1}(\mathbb R) \cap L^{2}(\mathbb R) \cap C_{0}(\mathbb R)\subset H_{1}(\mathbb R)$? Put, $C_{0} (\mathbb R)=\{f:\mathbb R \to \mathbb C: f \text { is continuous on} \ \mathbb R \  \text  {and } \lim_{|x|\to \pm \infty}f(x)=0 \}$(= Continuous functions on $\mathbb R$ vanishing at $\infty$)  and  $A:= L^{1}(\mathbb R) \cap L^{2}(\mathbb R) \cap C_{0}(\mathbb R).$

My Question: Given $|f|\in A$. Can we always expect $|f|\in H_{1}(\mathbb R)=\{ f\in \mathcal{S'}(\mathbb R): (1+|\xi|^{2})^{1/2}\hat{f}\in L^{2}(\mathbb R) \}$ (Sobolev spaces), Or, we we can  produce a counter example ?

Thanks,

A: No. A simple family of counter examples come from the Sobolev embeddings. Since
$$
W^{1,2}(\mathbb{R})\hookrightarrow C^{0,\frac{1}{2}}(\mathbb{R}),
$$
your identity would imply that continuous functions are always Hölder continuous.


text:
Q: Law of Demeter - Data objects I'm trying to follow the Law Of Demeter ( see http://en.wikipedia.org/wiki/Law_of_Demeter , http://misko.hevery.com/code-reviewers-guide/flaw-digging-into-collaborators/ ) as I can see the benefits, however I've become a little stuck when it comes to domain objects.
Domain objects do naturally have a chain and sometimes it's necessary to display the information about the entire chain.
For instance, a shopping basket:
Each order contains a user, delivery info and a list of items
Each order item contains a product and quantity
Each product has a name and price.
Each user contains a name and address
The code which displays the order information has to use all the information about the order, users and products.
Surely it's better and more reusable to get this information through the order object e.g. "order.user.address.city" than for some code higher up to do queries for all the objects I listed above then pass them into the code separately?
Any comments/suggestions/tips are welcome!

A: I think, when chaining is used to access some property, it is done in two (or at least two) different situation. One is the case that you have mentioned, for example, in your presentation module, you have an Order object and you would like to just display the owner's/user's address, or details like city. In that case, I think it is of not much problem if you do so. Why? Because you are not performing any business logic on the accessed property, which can (potentially) cause tight coupling.
But, things are different if you use such chaining for the purpose of performing some logic on the accessed property. For example, if you have,
String city = order.user.address.city;
...
order.user.address.city = "New York";

This is problematic. Because, this logic is/should more appropriately be performed in a module closer to the target attribute - city. Like, in a place where the Address object is constructed in the first place, or if not that, at least when the User object is constructed (if say User is the entity and address the value type). But, if it goes farther than that, the farther it goes, the more illogical and problematic it becomes. Because there are too many intermediaries are involved between the source and the target.
Thus, according to the the Law of Demeter, if you are performing some logic on the "city" attribute in a class, say OrderAssmebler, which accesses the city attribute in a chain like order.user.address.city, then you should think of moving this logic to a place/module closer to the target.

A: One problem with using chained references, such as order.user.address.city, is that higher-order dependencies get "baked into" the structure of code outside the class.
Ideally, in cases when you refactor your class, your "forced changes" should be limited to the methods of the class being refactored. When you have multiple chained references in the client code, refactoring drives you to make changes in other places of your code.
Consider an example: suppose that you'd like to replace User with an OrderPlacingParty, an abstraction encapsulating users, companies, and electronic agents that can place an order. This refactoring immediately presents multiple problems:

*

*The User property will be called something else, and it will have a different type

*The new property may not have an address that has city in cases when the order is placed by an electronic agent

*The human User associated with the order (suppose that your system needs one for legal reasons) may be related to the order indirectly, - for example, by being a designated go-to person in the definition of the OrderPlacingParty.

A solution to these problems would be to pass the order presentation logic everything that it needs directly, rather than having it "understand" the structure of the objects passed in. This way you would be able to localize the changes to the code being refactored, without spreading the changes to other code that is potentially stable.
interface OrderPresenter {
    void present(Order order, User user, Address address);
}
interface Address {
    ...
}
class PhysicalAddress implements Address {
    public String getStreetNumber();
    public String getCity();
    public String getState();
    public String getCountry();
}
class ElectronicAddress implements Address {
    public URL getUrl();
}
interface OrderPlacingParty {
    Address getAddress();
}
interface Order {
    OrderPlacingParty getParty();
}
class User implements OrderPlacingParty {
}
class Company implements OrderPlacingParty {
    public User getResponsibleUser();
}
class ElectronicAgent implements OrderPlacingParty {
    public User getResponsibleUser();
}

A: You're correct and you'll most likely model your value objects something like this
class Order {
    User user;
}

class User {
    Address shippingAddress;
    Address deliveryAddress;
}

class Address {
    String city;
    ...
}

When you start considering how you will persist this data to a database (e.g. ORM) do you start thinking about performance. Think eager vs lazy loading trade offs.

A: Generally speaking I adhere to the Law of Demeter since it helps to keep changes in a reduced scope, so that a new requirement or a bug fix doesn't spread all over your system. There are other design guidelines that help in this direction, e.g. the ones listed in this article. Having said that, I consider the Law of Demeter (as well as Design Patterns and other similar stuff) as helpful design guidelines that have their trade-offs and that you can break them if you judge it is ok to do so. For example I generally don't test private methods, mainly because it creates fragile tests. However, in some very particular cases I did test an object private method because I considered it to be very important in my app, knowing that that particular test will be subject to changes if the implementation of the object changed. Of course in those cases you have to be extra careful and leave more documentation for other developers explaining why you are doing that. But, in the end, you have to use your good judgement :).
Now, back to the original question. As far as I understand your problem here is writing the (web?) GUI for an object that is the root of a graph of objects that can be accessed through message chains. For that case I would modularize the GUI in a similar way that you created your model, by assigning a view component for each object of your model. As a result you would have classes like OrderView, AddressView, etc that know how to create the HTML for their respective models. You can then compose those views to create your final layout, either by delegating the responsibility to them (e.g. the OrderView creates the AddressView) or by having a Mediator that takes care of composing them and linking them to your model. As an example of the first approach you could have something like this (I'll use PHP for the example, I don't know which language you are using):
class ShoppingBasket
{
  protected $orders;
  protected $id;

  public function getOrders(){...}
  public function getId(){...}
}

class Order
{
  protected $user;

  public function getUser(){...}
}

class User
{
  protected $address;

  public function getAddress(){...}
}

and then the views:
class ShoppingBasketView
{
  protected $basket;
  protected $orderViews;

  public function __construct($basket)
  {
     $this->basket = $basket;
     $this->orederViews = array();
     foreach ($basket->getOrders() as $order)
     {
        $this->orederViews[] = new OrderView($order);
     }
  }

  public function render()
  {
     $contents = $this->renderBasketDetails();
     $contents .= $this->renderOrders();
     return $contents;
  }

  protected function renderBasketDetails()
  {
     //Return the HTML representing the basket details
     return '
Shopping basket (id=' . $this->basket->getId() .')
';
  }

  protected function renderOrders()
  {
     $contents = '
';
     foreach ($this->orderViews as $orderView)
     {
        $contents .= orderViews->render();
     }
     $contents .= '
';
     return $contents;
  }
}

class OrderView
{
//The same basic pattern; store your domain model object
//and create the related sub-views

  public function render()
  {
     $contents = $this->renderOrderDetails();
     $contents .= $this->renderSubViews();
     return $contents;
  }

  protected function renderOrderDetails()
  {
     //Return the HTML representing the order details
  }

  protected function renderOrders()
  {
     //Return the HTML representing the subviews by
     //forwarding the render() message
  }
}

and in your view.php you would do something like:
$basket = //Get the basket based on the session credentials
$view = new ShoppingBasketView($basket);
echo $view->render();

This approach is based on a component model, where the views are treated as composable components. In this schema you respect the object's boundaries and each view has a single responsibility.
Edit (Added based on the OP comment)
I'll assume that there is no way of organizing the views in subviews and that you need to render the basket id, order date and user name in a single line. As I said in the comment, for that case I would make sure that the "bad" access is performed in a single, well documented place, leaving the view unaware of this.
class MixedView
{
  protected $basketId;
  protected $orderDate;
  protected $userName;

  public function __construct($basketId, $orderDate, $userName)
  {
    //Set internal state
  }

  public function render()
  {
    return '
' . $this->userName . "'s basket (" . $this->basketId . ")
 " .
           '
Last order placed on: ' . $this->orderDate. '
';
  }
}

class ViewBuilder
{
  protected $basket;

  public function __construct($basket)
  {
    $this->basket = $basket;
  }

  public function getView()
  {
     $basketId = $this->basket->getID();
     $orderDate = $this->basket->getLastOrder()->getDate();
     $userName = $this->basket->getUser()->getName();
     return new MixedView($basketId, $orderDate, $userName);
  }
}

If later on you rearrange your domain model and your ShoppingBasket class can't implement the getUser() message anymore then you will have to change a single point in your application, avoid having that change spread all over your system.
HTH

A: The Law Of Demeter is about calling methods, not accessing properties/fields. I know technically properties are methods, but logically they're meant to be data. So, your example of order.user.address.city seems fine to me.
This article is interesting further reading: http://haacked.com/archive/2009/07/13/law-of-demeter-dot-counting.aspx


text:
Q: Having trouble resizing image in div Sorry this might be a simple question (I'm just a beginner). I'm having some difficulty resizing my pictures inside my divs.  please see my below code and give me any needed feedback. Thank you.
Here is my code:

    <title>Fruit!</title>

 The Stawberry

 The Blueberry

 The Banana

A: I think someone already posted the same question.
Here is the link: Resize an image to fit in div

A: You should try changing the width and height properties to whatever you like them at, for example:
    #myImg {
        width: 100px;
        height: 100px;
    }

I hope this has helped!

A: Use css height and width.  You can look it up on w3schools for more reference.  I've also included code on how to center it.  Seems like you'd want to do that.
 img {
    width: 40px;
    height: 40px;
  // Below code will center it
    display: block;
    margin-left: auto:
    margin-right: auto;
   }


text:
Q: Format These Dates And Get Time Passed I have a Python list of dates and I'm using min and max to find the most recent and the oldest (first, is that the best method?), but also I need to format the dates into something where I can figure out the current time and subtract the oldest date in the list so I can say something like "In the last 27 minutes..." where I can state how many days, hours, or minutes have past since the oldest. Here is my list (the dates change obviously depending on what I'm pulling) so you can see the current format. How do I get the info I need?
[u'Sun Oct 06 18:00:55 +0000 2013', u'Sun Oct 06 17:57:41 +0000 2013', u'Sun Oct 06 17:55:44 +0000 2013', u'Sun Oct 06 17:54:10 +0000 2013', u'Sun Oct 06 17:35:58 +0000 2013', u'Sun Oct 06 17:35:58 +0000 2013', u'Sun Oct 06 17:35:25 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:30:35 +0000 2013', u'Sun Oct 06 17:25:28 +0000 2013', u'Sun Oct 06 17:24:04 +0000 2013', u'Sun Oct 06 17:24:04 +0000 2013', u'Sun Oct 06 17:22:08 +0000 2013', u'Sun Oct 06 17:22:08 +0000 2013', u'Sun Oct 06 17:21:00 +0000 2013', u'Sun Oct 06 17:18:49 +0000 2013', u'Sun Oct 06 17:18:49 +0000 2013', u'Sun Oct 06 17:15:29 +0000 2013', u'Sun Oct 06 17:15:29 +0000 2013', u'Sun Oct 06 17:13:35 +0000 2013', u'Sun Oct 06 17:12:18 +0000 2013', u'Sun Oct 06 17:12:00 +0000 2013', u'Sun Oct 06 17:07:34 +0000 2013', u'Sun Oct 06 17:03:59 +0000 2013']

A: your question can be divided into three pieces:
A)
how to read string formated dates
B)
how to sort list of dates in python
C)
how to calculate the difference between two dates

A: You won't get the oldest and newest date/time entries from your list with the entries by using min and max - "Fri" will come before "Mon", for example. So you'll want to put things into a data structure that represents date/time stamps properly.
Fortunately, Python's datetime module comes with a method to convert lots of date/time stamp strings into a proper representation - datetime.datetime.strptime. See the guide for how to use it.
Once that's done you can use min and max and then timedelta to compute the difference.
from datetime import datetime

# Start with the initial list
A = [u'Sun Oct 06 18:00:55 +0000 2013', u'Sun Oct 06 17:57:41 +0000 2013', u'Sun Oct 06 17:55:44 +0000 2013', u'Sun Oct 06 17:54:10 +0000 2013', u'Sun Oct 06 17:35:58 +0000 2013', u'Sun Oct 06 17:35:58 +0000 2013', u'Sun Oct 06 17:35:25 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:34:39 +0000 2013', u'Sun Oct 06 17:30:35 +0000 2013', u'Sun Oct 06 17:25:28 +0000 2013', u'Sun Oct 06 17:24:04 +0000 2013', u'Sun Oct 06 17:24:04 +0000 2013', u'Sun Oct 06 17:22:08 +0000 2013', u'Sun Oct 06 17:22:08 +0000 2013', u'Sun Oct 06 17:21:00 +0000 2013', u'Sun Oct 06 17:18:49 +0000 2013', u'Sun Oct 06 17:18:49 +0000 2013', u'Sun Oct 06 17:15:29 +0000 2013', u'Sun Oct 06 17:15:29 +0000 2013', u'Sun Oct 06 17:13:35 +0000 2013', u'Sun Oct 06 17:12:18 +0000 2013', u'Sun Oct 06 17:12:00 +0000 2013', u'Sun Oct 06 17:07:34 +0000 2013', u'Sun Oct 06 17:03:59 +0000 2013']

# This is the format string the date/time stamps are using
# On Python 3.3 on Windows you can use this format
# s_format = "%a %b %d %H:%M:%S %z %Y"
# However, Python 2.7 on Windows doesn't work with that. If all of your date/time stamps use the same timezone you can do:
s_format = "%a %b %d %H:%M:%S +0000 %Y"

# Convert the text list into datetime objects
A = [datetime.strptime(d, s_format) for d in A]

# Get the extremes
oldest = min(A)
newest = max(A)

# If you substract oldest from newest you get a timedelta object, which can give you the total number of seconds between them. You can use this to calculate days, hours, and minutes.
delta = int((newest - oldest).total_seconds())
delta_days, rem = divmod(delta, 86400)
delta_hours, rem = divmod(rem, 3600)
delta_minutes, delta_seconds = divmod(rem, 60)


text:
Q: How do you write shared generic views with the new MVC 2 About a week ago I saw a blog post describing how you could write a set of shared Views in the Views/Shared folder that could be used by all your Models. The post also explained how to decorate the Model properties with validation rules and messages. There was information about the new Model Binding improvements. The examples take advantage of new functionality in the preview release of ASP.Net MVC 2.
For the life of me, I can't find the blog post or other information on how to create the shared views.
Can anyone offer a pointer to the post?

A: Ask and you shall receive.
I've been playing with this quite a bit in the past few days. In addition to generic, dynamic display of editors, details, etc., I've also implemented generic, dynamic modification of data. Essentially, Phil's sample project covers the GET side of things, and I've implemented the POST. I'm also looking into dynamically generating JavaScript in order to have a dynamic list using jqGrid. Stay tuned to my blog if you're interested in this sort of thing.


text:
Q: How do I pass a DynamoDB table address and Redis port and address to my EC2 instance in CloudFormation? I have a system that requires an EC2 instance that has connections to a DynamoDB table and a Redis instance.  How do I set those up as options for my EC2 instance in CloudFormation using YAML?
I've created OptionSettings to set the values as environmental variable for my process on the EC2 instance. I know that I need to do !Ref [something here], but the documentation did not have examples that made sense to me.
Here's a simplified version of the code:
---
AWSTemplateFormatVersion: "2010-09-09"

Description: CloudFormation template

Resources:
  # Beanstalk application
  MyApp:
    Type: AWS::ElasticBeanstalk::Application
  ConfigurationTemplate:
    Type: AWS::ElasticBeanstalk::ConfigurationTemplate
    Properties:
      ApplicationName: !Ref MyApp
      OptionSettings:
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_PORT
        Value: !Ref AttributeCache.Port # Should be 6379
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_ADDRESS
        Value: !Ref MyCache. # Something that AWS creates
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: DYNAMODB_TABLE_ADDRESS
        Value: !Ref MyDynamoTable. # Something that AWS creates
      SolutionStackName: 64bit Amazon Linux 2018.03 v4.8.1 running Node.js

  # Redis cache
  MyCache:
    Type: AWS::ElastiCache::CacheCluster
    Properties:
      ClusterName: MyCacheCluster
      Engine: redis
      EngineVersion: 4.0.10
      NumCacheNodes: 1
      Port: 6379

  # DynamoDB table
  MyDynamoTable:
    Type: "AWS::DynamoDB::Table"
    Properties:
      AttributeDefinitions:
      - AttributeName: theAttributeName
        AttributeType: S
      KeySchema:
      - AttributeName: theAttributeName
        KeyType: HASH
      TableName: myDynamoTable

I am unsure of how to access something that CloudFormation will create.
Is !Ref correct, or do I need the !GetAtt instead?
Here are the links to the two different function docs.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html
Even just pointing me at the thing that I'm missing would be of help.

A: This kind of information is specified under Return Values section in the documentation for every service. This doc section also provides information whether you have to use !Ref or !GetAtt in order to retrieve certain parameter. For example CacheCluster docs say that you have to use !GetAtt MyCache.RedisEndpoint.Port to get redis' port and Dynamo docs say that you have to use !Ref MyDynamoTable to get table name.
      OptionSettings:
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_PORT
        Value: !GetAtt MyCache.RedisEndpoint.Port
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: REDIS_CACHE_ADDRESS
        Value: !GetAtt MyCache.RedisEndpoint.Address
      - Namespace: "aws:elasticbeanstalk:application:environment"
        OptionName: DYNAMODB_TABLE_ADDRESS
        Value: !Ref MyDynamoTable # You got this one right, but no dot in the end


text:
Q: Camel consuming from specific Kafka partition Can someone advise if the kafka-camel could consume message from a specific partition from kakfa topic.
I want to consume a message from specific partition from topic using Camel Kafka component, I have seen consumer options here http://camel.apache.org/kafka.html, but could not see any option for this.
I could do it for producing message to specific partition, just by setting header values.But same thing unable to do it while consuming.
Thank you.


text:
Q: Powershell Invoke-MySQL Having some problems getting MySQL queries working from powershell, here is my code:
function Invoke-MySQL {
Param(
  [Parameter(
  Mandatory = $true,
  ParameterSetName = '',
  ValueFromPipeline = $true)]
  [string]$Query
  )

$MySQLAdminUserName = 'USER'
$MySQLAdminPassword = 'PASSWORD'
$MySQLDatabase = 'DATABASE'
$MySQLHost = 'MYSQLSERVER.mydomain.local'
$ConnectionString = "server=" + $MySQLHost + "; port=3306; uid=" + $MySQLAdminUserName + "; pwd=" + $MySQLAdminPassword + "; database="+$MySQLDatabase

Try {
  [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
  $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
  $Connection.ConnectionString = $ConnectionString
  $Connection.Open()

  $Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
  $DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
  $DataSet = New-Object System.Data.DataSet
  $RecordCount = $dataAdapter.Fill($dataSet, "data")
  $DataSet.Tables[0]
  }

Catch {
  throw "ERROR : Unable to run query : $query `n$Error[0]"
 }

Finally {
  $Connection.Close()
  }
 }

Invoke-MySQL -Query "select * from ImaginaryTable"

The problem occurs on the $Connection.Open() command with the following error:
ERROR : Unable to run query : select * from ImaginaryTable
Exception calling "Open" with "0" argument(s): "Unable to connect to any of the specified MySQL h
osts."[0]

Anyone that can help me? :)

A: There is no error in the script, I think your server is not accesible on port 3306.
Please make sure that you don't have firewall rules blocking this port.
Maybe your mysql server is only listening from localhost ip address.
Assuming you're on linux mysql server follow the steps below :
Open this file /etc/mysql/my.cnf, and change bind-address value from 127.0.0.1 to the  corresponding IP address of your network card (example : 192.168.0.50 or external ip if your server is hosted outside).
Then restart your mysql server
/etc/init.d/mysql restart

After mysql restart execute this query :
GRANT ALL PRIVILEGES ON *.* TO 'USER'@'%' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;

Now you'll be able to query your Database via Powershell.


text:
Q: DrawerLayout - Opaque Status Bar Over Drawer and Translucent Status Bar Over Container I've tried searching SO a few hours and couldn't find anything relating to what I want. Most questions are in relations to making the Navigation Drawer appear behind the status bar.
However, this isn't the behavior that I want.
I want the status bar to remain opaque over the Drawer, but is transparent over the DrawerLayout container (the fragment).
Here's what I have:

And here's what I want:

I can get the status bar to be translucent over other activities, except for the main activity which has the DrawerLayout. Because everytime I try to make the status bar translucent only the Drawer can become translucent, which is exactly the opposite of what I want for the Drawer. The status bar should only be translucent over the fragment.
Any ideas how I can achieve this?
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    android:fitsSystemWindows="true">

    <!-- This FrameLayout is the container for all other fragments
    so I want this to have a transparent status bar because some fragments
    may have "cover photos" that needs to take up the status bar. It looks
    nicer that way. I tried playing around with the fragment layouts
    themselves. Bit nothing seems to budge, so I give up on that part. -->
    <FrameLayout
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:fitsSystemWindows="false"
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/activity_main_nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>

fragment_profile.xml (one of the fragment to be placed inside the container)
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#fff"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <android.support.v7.widget.CardView
                    android:id="@+id/card_cover"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    app:cardElevation="10dp">

                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="#11b4ff"
                        android:src="@android:drawable/sym_def_app_icon"/>
                </android.support.v7.widget.CardView>

                <android.support.v7.widget.CardView
                    android:id="@+id/card_profile"
                    android:layout_below="@id/card_cover"
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    app:cardElevation="10dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginBottom="15dp"
                    android:layout_marginTop="-60dp">
                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="#1119ff"
                        android:src="@android:drawable/sym_def_app_icon"
                        />
                </android.support.v7.widget.CardView>

                <TextView
                    android:layout_margin="15dp"
                    android:layout_below="@id/card_cover"
                    android:layout_toRightOf="@id/card_profile"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Profile Name"
                    android:textSize="30sp"/>

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/fragment_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </android.support.design.widget.CollapsingToolbarLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="6dp"
            app:tabMode="scrollable"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextColor="@android:color/white"/>

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

v21\styles.xml
<resources>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

A: After more searching on SO I found this answer that although didn't directly solve my problem, it gave me clues as to what was going on. In order to enable the translucent status bar in the fragment I needed to change the container layout to a CoordinatorLayout.
Furthermore, I needed to add "fitsSystemWindows=true" to all child views in order for the inset to be placed correctly in my desired fragment.
Here's the updated code that gave me the desired result:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        android:fitsSystemWindows="true"
        android:id="@+id/main_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:fitsSystemWindows="false"
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/activity_main_nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>

fragment_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#fff"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways">

            <RelativeLayout
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <android.support.v7.widget.CardView
                    android:id="@+id/card_cover"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    app:cardElevation="10dp">

                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="#11b4ff"
                        android:src="@android:drawable/sym_def_app_icon"/>
                </android.support.v7.widget.CardView>

                <android.support.v7.widget.CardView
                    android:id="@+id/card_profile"
                    android:layout_below="@id/card_cover"
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    app:cardElevation="10dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginBottom="15dp"
                    android:layout_marginTop="-60dp">
                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="#1119ff"
                        android:src="@android:drawable/sym_def_app_icon"
                        />
                </android.support.v7.widget.CardView>

                <TextView
                    android:layout_margin="15dp"
                    android:layout_below="@id/card_cover"
                    android:layout_toRightOf="@id/card_profile"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Profile Name"
                    android:textSize="30sp"/>

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/fragment_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </android.support.design.widget.CollapsingToolbarLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="6dp"
            app:tabMode="scrollable"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextColor="@android:color/white"/>

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>


text:
Q: Persistence with files in JSF I'm developing a JSF web application, with the current 2.1.7 JSF version.
Actually, I have a login page, associated with a session bean,
which calls to a logic class "PersonCatalog",
which is responsible for reading a text file .txt with the information of the persons, like a database but with files.
The problem is to access the file,
ever I get a NullException because the program doesn't finds the file.
I'm not sure about the path I choose, here is the directory herarchy:
Application
 |-- build
 |-- src
       |--eci
           |--pdsw2012
               |--shoeople
                   |--beans
                       |--loginBean and others ...
                   |--logic
                       |--PersonCatalog and others...
                   |--persistence
                       |--files
                           |--persons.txt
 |-- WebContent
       |--WEB-INF
       |--META-INF
       |--a lot of xhtml pages ...

I'm using in PersonCatalog for read the person.txt file the follow code:
File readFile = new File(new String("src/eci/pdsw2012/shoeople/persistence/files/persons.txt"));

But I get:
java.lang.NullPointerException
at eci.pdsw2012.shoeople.logic.PersonCatalog.loadFile(PersonCatalog.java:31)

I have used the ExternalContext().getRealPath(), but it only shows inside Web-content folder.
I'm using Eclipse, and the default route is the installation folder of Eclipse, the is so strange:
String ruta = System.getProperty("user.dir");
System.out.println("DirAbs: " + ruta.getAbsolutePath());

and prints
 C:/Eclipse/

A: The root of a deployed web application in this case would be the WebContent folder, which contains WEB-INF.
In the deployed version the src files are compiled into class files and placed in the following folder classes.
The path to persons.txt will be \WEB-INF\classes\eci\pdsw2012\shoeople\persistence\files\persons.txt


text:
Q: Exercise 3.2.13 Introduction to Real Analysis by Jiri Lebl
Let $f:S \to \mathbb{R}$ be a function and $c \in S$, such that for every sequence $\{x_n\}$ in $S$ with $\lim x_n = c$, the sequence $\{f(x_n)\}$ converges. Show that $f$ is continuous at $c$.

Suppose that $f$ is not continuous at $c$. Then, $\exists \epsilon > 0$ s.t. for every $\delta> 0$, $\exists x$ s.t. $|x-c| < \delta$, but $|f(x) - f(c)| \ge \epsilon$. Let $\{x_n\}$ be a sequence s.t.   $|x_n - c| < \frac1n$. Then, $|f(x_n) - f(c) | \ge \epsilon$ when $n$ is large enough. But, I think that $f(x_n)$ can still converges to somewhere else other than $f(c)$. How can I proceed from here?
I appreciate if you give some help.

A: Consider any $(x_{n})$ such that $x_{n}\rightarrow c$, consider also the constant sequence $(c,c,...)$ and consider further that $(y_{n}):=(x_{1},c,x_{2},c,...)$, the later also converges to $c$ and $(f(y_{n}))$ has the constant subsequence $(f(c),f(c),...)$, so $f(y_{n})\rightarrow f(c)$ and also that $f(x_{n})\rightarrow f(c)$ as $(f(x_{1}),f(x_{2}),...)$ is also a subsequence of the convergent sequence $(f(y_{n}))$.
So we have proved that, for any $(x_{n})$ such that $x_{n}\rightarrow c$, then $f(x_{n})\rightarrow f(c)$, this is another characterization of continuity.


text:
Q: Communication between consul on local VM and consul in Kubernetes I have a Kubernetes cluster with 2 master nodes and 3 worker nodes. I have used HELM to install consul setup which has 3 consul-servers and 5 consul-clients running.
Here is how the consul server pods and consul client pods are placed on the Kubernetes nodes:
[root@k8masterg2m1 autoinstall]# kubectl get po -o wide | grep consul
consul-consul-4lxtr 1/1 Running 0 103m 192.168.139.139 k8masterg2m1
consul-consul-6wv9w 1/1 Running 0 103m 192.168.118.215 k8workerg2w3
consul-consul-pc562 1/1 Running 0 103m 192.168.108.162 k8workerg2w2
consul-consul-server-0 1/1 Running 0 107m 192.168.118.214 k8workerg2w3
consul-consul-server-1 1/1 Running 0 9m15s 192.168.227.91 k8workerg2w1
consul-consul-server-2 1/1 Running 0 107m 192.168.108.161 k8workerg2w2
consul-consul-tg4kz 1/1 Running 0 103m 192.168.139.72 k8masterg2m2
consul-consul-tj7h5 1/1 Running 0 103m 192.168.227.90 k8workerg2w1

On the other side I have installed consul client on a local VM, which is on the same networks as the Kubernetes nodes.
From the consul server pods running in Kubernetes, I have used the below command to join the local VM(10.0.20.102).
/ # consul join 10.0.20.102
Successfully joined cluster by contacting 1 nodes.

I could see the below output in both the VM and consul pods in the Kubernetes:
/ # consul members

Node Address Status Type Build Protocol DC Segment
consul-consul-server-0 192.168.118.214:8301 alive server 1.8.1 2 dc1
consul-consul-server-1 192.168.227.91:8301 alive server 1.8.1 2 dc1
consul-consul-server-2 192.168.108.161:8301 alive server 1.8.1 2 dc1
k8masterg1m2 10.0.20.102:8301 alive client 1.8.1 2 dc1
k8masterg2m1 192.168.139.139:8301 alive client 1.8.1 2 dc1
k8masterg2m2 192.168.139.72:8301 alive client 1.8.1 2 dc1
k8workerg2w1 192.168.227.90:8301 alive client 1.8.1 2 dc1
k8workerg2w2 192.168.108.162:8301 alive client 1.8.1 2 dc1
k8workerg2w3 192.168.118.215:8301 alive client 1.8.1 2 dc1

Now, when I try to list the services in Kubernetes consul pods it works fine as shown below:
/ # consul catalog services

consul
consul-consul-dns-default
consul-consul-server-default
consul-consul-ui-default
ha-rabbitmq-rabbitmq-ha-default
ha-rabbitmq-rabbitmq-ha-discovery-default
kubernetes-default
vault-agent-injector-svc-default
vault-internal-default

but, when I try to run the same command in local VM it gives the below error:
[root@k8masterg1m2 autoinstall]# consul catalog services
Error listing services: Unexpected response code: 500 (rpc error getting client: failed to get conn: rpc error: lead thread didn't get connection)

Since on the consul agent running in the local VM, it is able to list the members but not services/nodes.
Is this the expected behavior or is there any other configuration which has to be done to get this work.
Also, I wanted to know how the communication happens between consul servers and consul agent which is outside Kubernetes cluster.
Any help is appreciated.
Thanks in Advance!!

A: It's an odd setup that you want to join the VM. But for everything to work you need to make sure that all the required ports are exposed on the Consul Server nodes. It sounds like all of those ports are exposed within the Kubernetes cluster but not outside.
You didn't specify how you deployed Consul but you can use Kubernetes Services to expose the ports. In your case, it's likely that maybe port 8500 is the only exposed from your VM but maybe not the other ports. You have to expose them all if you'd like to enable all the Consul features/functionality.
✌


text:
Q: How to get Username from Channel name via youtube api? I know a youtuber, his name is "Hoggy". But when I find "Hoggy" on youtube, I find this. https://www.youtube.com/user/HoggyCZ
The name is the same, but the "Username" in URL is different "HoggyCZ".
Is it possible to convert the youtuber name/channel name to Username via youtube API?
Thanks.


text:
Q: SSL3_GET_SERVER_CERTIFICATE certificate verify failed on Windows 10 Pro with IIS When trying to send emails through smtp.google.com via PHPMailer on PHP hosted by IIS on Windows 10, I get this error message:
Connection failed.
Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1.
OpenSSL Error messages
error:14090086
SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

The key part of that error I'm sure is certificate verify failed. I'm running OpenSSL and it's enabled and linked to my php. Here is some info output by my local PHP instance:
OpenSSL support => enabled
OpenSSL Library Version => OpenSSL 1.0.1p 9 Jul 2015
OpenSSL Header Version => OpenSSL 1.0.1p 9 Jul 2015

Directive => Local Value => Master Value
openssl.cafile => no value => no value
openssl.capath => no value => no value

Here is my PHP code:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';

$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->Host = "smtp.gmail.com"; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
$mail->Port = 587; // TLS only
$mail->SMTPSecure = 'tls'; // ssl is depracated
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($emailFrom, $emailFromName);
$mail->addAddress($emailTo, $emailToName);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->msgHTML("test body"); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
$mail->AltBody = 'HTML messaging not supported';
// $mail->addAttachment('images/phpmailer_mini.png'); //Attach an image file

if(!$mail->send()){
    echo "Mailer Error: " . $mail->ErrorInfo;
}else{
    echo "Message sent!";
}

I'm out of my depth regarding OpenSSL and cert issues. I have tried to understand the Updating CA certificates section of the PHPMailer troubleshooting guide, but I'm lost and confused. Can someone give me a set of steps I can follow and fix the cert problem on my local Windows 10 machine?

A: To paraphrase the guide, download the CA bundle from curl and store it somewhere on your file system. Take the path you saved it to and add a line to your php.ini file saying:
openssl.cafile = $path

Where $path is where you saved the CA certs to. Then restart your web server to pick up the ini change.
If that worked, you should see that setting in the output from phpinfo(), and it should also give PHP what it needs to validate the certificate when PHPMailer uses it. Be aware that if the server is presenting a truly invalid or expired certificate, this won't help, but given that this a well-known problem and solution, I expect it to work.


text:
Q: Do sub-stochastic matrices reduce the 1-norm of vectors? It is well-known that "stochastic matrices preserve the 1-norm of vectors, $||\mathbf{A}\vec{v}||_1=||\vec{v}||_1$". I am thus wondering whether sub-stochastic matrices (a square matrix $\mathbf{Q}$ with nonnegative entries so that every row adds up to at most 1) reduce instead the 1-norm of a vector, $||\mathbf{Q}\vec{v}||_1\leq ||\vec{v}||_1$...is there a proof of this, and under which conditions?
This should be a well-known fact (or at least easy to disprove), but I have so far failed. Many thanks.

A: Suppose $Q \in \mathbb{R}^{n\times n}$ and $v\in\mathbb{R}^n$ have non-negative entries.
Observe,
$$
Qv
=
\begin{bmatrix}
Q_{1,1}v_1 + Q_{1,2}v_2 + \cdots Q_{1,n}v_n \\
Q_{2,1}v_1 + Q_{2,2}v_2 + \cdots Q_{2,n}v_n \\
\vdots \\
Q_{n,1}v_1 + Q_{n,2}v_2 + \cdots Q_{n,n}v_n \\
\end{bmatrix}
$$
Then, using the assumption that $Q_{i,j} v_j \geq 0$,
$$
\| Qv \|_1
= \sum_{i} \left| \sum_j Q_{i,j} v_j \right|
= \sum_{i} \sum_j Q_{i,j} v_j
= \sum_j \left[ v_j \sum_{i}  Q_{i,j} \right]
$$
Therefore, if the columns of $Q$ sum to 1, then $\| Q v \|_1 = \|v\|_1$.
If the columns of $Q$ sum to something less than 1 (what you're asking about), what does this tell you about how this new sum compares to the sum if the columns of $Q$ summed to 1?


text:
Q: Remove selective hyphenations / punctuations based on list of exceptions Remove selective hyphenations
import pandas as pd
s = pd.Series(['do not-remove this-hyphen but remove-all of these-hyphens'])

list_to_keep =['not-remove', 'this-hyphen']

I want to keep the word hyphenations in the 'list to keep' but replace all other '-' in the series with a space.

A: You could try this:
S = s.str.split(expand=True).T[0]
' '.join(np.where(S.isin(list_to_keep), S, S.str.replace('-', '')))

Output:
'do not-remove this-hyphen but removeall of thesehyphens'

How it works.

*

*Create a pd.Series, S, using the string access and split then transpose
dataframe and get the first column

*Use np.where to get only those terms that aren't in the list and use
replace to remove the hyphen otherwise return the original term.

*Use join to reconstruct the string from the terms in updated pd.Series, S.

A: A simple naïve solution would be:
s = 'do not-remove this-hyphen but remove-all of these-hyphens'
words_to_keep = {'not-remove', 'this-hyphen'}

new_s = []
for word in s.split():
    if word not in words_to_keep:
        word = word.replace('-', ' ')
    new_s.append(word)

print(' '.join(new_s))  # do not-remove this-hyphen but remove all of these hyphens

Another approach with map:
def unhyphen_word(word):
    return word.replace('-', ' ') if word not in words_to_keep else word

print(' '.join(map(unhyphen_word, s.split())))

or list comprehension:
print(' '.join([unhyphen_word(word) for word in s.split()]))

A: edit hmm... it works but something seems wrong...
I'm not a master with regex but one way would be to do this in 2 steps:

*

*Add - to the words to keep

*Remove - from all that match pattern

Proof of concept:
import pandas as pd
s = pd.Series(['do not-remove this-hyphen but remove-all of these-hyphens'])

words_to_keep = {'not-remove', 'this-hyphen'}

p1 = '|'.join(['(?!({}))-(?=({})[.,; ])'.format(*i.split('-'))
               for i in words_to_keep])

p2 = '(?!\w+)-(?=\w+)'

s.str.replace(p1,'--').str.replace(p2,'')[0]

Returns:
'do not-remove this-hyphen but removeall of thesehyphens'


text:
Q: Can't get GCC's -static-libgcc working with DYLIB libraries on Mac OS X I've installed GCC 4.6.3 into a non-system path on a Mac system and it works fine. However, GCC wants to use code from libgcc for all the binaries I compile, and running otool -L shows that these compiled programs look for libgcc_s.1.dylib in GCC's install path. I can override this by passing -static-libgcc, which just compiles the stuff needed into the binary and that's fine. The problem is this only seems to work with executables, not shared libraries. If I use GCC to compile some third-party lib I want to use in one of my programs as a .dylib, these libraries still look for libgcc_s.1.dylib in the local GCC install path even if I specify -static-libgcc! Needless to say, this is a problem as there's no guarantee that those libraries will find libgcc when run on some other system.
I tried this with ffmpeg. If I look at config.log, the -static-libgcc is most certainly being used. GCC is just not linking libgcc statically with the resulting dylibs. I even tried the -nostdlib, -nostartfiles and -nodefaultlibs options but they were ignored. Again, I checked config.log and they're definitely there!

A: I believe this is to do with throwing exceptions across the shared library boundary.  This page says:

There are several situations in which an application should use the
  shared libgcc instead of the static version. The most common of these
  is when the application wishes to throw and catch exceptions across
  different shared libraries. In that case, each of the libraries as
  well as the application itself should use the shared libgcc.
Therefore, the G++ and GCJ drivers automatically add -shared-libgcc
  whenever you build a shared library or a main executable, because C++
  and Java programs typically use exceptions, so this is the right thing
  to do.

The rest of that sections gives a possible workaround (it appears) and that is to use the GCC driver to link your shared library, however if the statically-linked library throws exceptions you'll probably get a Segmentation Violation.


text:
Q: Representing a binary tree in an SQL table using foreign keys This is an example of a representation of a binary tree in an SQL table:
     A                                 node  | parent
    / \                                  A   |  NULL
   /   \                                 B   |   A
  /     \                                C   |   A
 B       C                               D   |   B
 |      / \                              E   |   C
 |     /   \                             F   |   C
 D     E    F

As you can see the table tree has two columns: node which is a primary key, and parent which is foreign key. In each node is stored a reference to its parent node.
I want to define the same tree but this time using children, each node should reference its children instead.
Any idea on how this can be done?

A: You'd have some table with three columns. One for an identifier for the node and two for them of its children. So basically something along the lines of:
CREATE TABLE bintree
             (id integer,
              left integer,
              right integer,
              PRIMARY KEY (id),
              FOREIGN KEY (left)
                          REFERENCES bintree
                                     (id),
              FOREIGN KEY (right)
                          REFERENCES bintree
                                     (id));

And maybe a check constraint, that checks that left isn't equal to right and a (constraint) trigger that checks that the thing stays cycle free...

A: Alternatively, you can also define the tree in term of arcs by using two tables
For example:
     A              Table: Nodes       Table: Arcs
    / \             node               parent  | child
   /   \              A                    A   |   B
  /     \             B                    A   |   C
 B       C            C                    B   |   D
 |      / \           D                    C   |   E
 |     /   \          E                    C   |   F
 D     E    F         F

This way the a parent can be related to zero, one, or more children.
The SQL script to do this is:
create table nodes (
  id varchar(10) primary key not null
);

create table arcs (
  parent varchar(10) not null,
  child varchar(10) not null,
  constraint uq1 unique (parent, child), -- optional
  foreign key (parent) references nodes (id),
  foreign key (child) references nodes (id)
);


text:
Q: How to make a Material UI grid element sticky? I am creating the front-end of for shopping cart. I have divided the container into two columns (using Grid container and Grid item) and inside each column, I have inserted some components. The left side contains components for each item and the left side contains only one component that shows the Order Summary. This picture illustrates what I am saying:

My question is how to make this left side (Order Summary) sticky at the top of the page when a user scrolls. I tried a couple of things with z-index and costume CSS-styling (position: fixed and position: sticky) but they break the Grid Structure that the Material UI offers. Also considering that the view is responsive it would be great that for mobile screens the Order Summary component stays at the end of the page where it is now:

I could achieve to stick the component on top on desktop but then when I added custom styling the component stuck in the top in the mobile view and looks terrible. Is there any practical way to achieve this that I may have not noticed?
Here is the Sandbox of the project: https://codesandbox.io/s/charming-cherry-eh27f
I hope that this way of dividing the page into columns would be helpful for somebody because I struggled a bit to find something similar online and thought of this way myself this morning. At the same time, I would appreciate any feedback and help for this feature I am trying to implement.
UPDATE
The solution provided by MaCadiz below works totally fine. I just wanted to say that feel free to create any pull requests if you want to add more features to this project. Here is the Github repo link: https://github.com/kleviss/shopping-cart-frontend-react-material

A: In your sandbox I realized that you have a nested grid item inside another grid item, I don't know if this was intentional, but I removed it anyway.
<Grid item xs={12} sm={6} md={5} lg={5}>
  <Grid item xs elevation={3}> <==== THIS ONE
    <OrderSummaryItem />
  </Grid>
</Grid>

Then I set the position of the OrderSummaryItem component to sticky and some tweaks and I think it's working fine. Check this fork I made from your sandbox: https://codesandbox.io/s/amazing-darkness-q0o5h

A: Try position:"fixed" if position:"sticky" is not working.


text:
Q: Java Process stops early even when output is redirected I have a Java application that calls a tcsh script which in turn calls a perl script in the same directory. If I run this script from the command by typing "runPerlScript.sh", it works completely fine, and generates several output files as it should. However, if I call the script from Java, using the code below:
    String[] runCmd  = {"/bin/tcsh","-c","/filepath/runPerlScript.sh"};
    Process run = Runtime.getRuntime().exec(runCmd);

    BufferedReader reader = new BufferedReader(new InputStreamReader(run.getInputStream()));

    String line = "";
    line = reader.readLine();
    System.out.println("\nStarting while.");
    while((line)!=null){
        System.out.println("Output from script: "+line);
        line=reader.readLine();
    }
    reader.close();
    System.out.println("Finished running perl script.");

it prints out the echo statements from my shell script to my console (I'm using NetBeans), but generates only 4 output files (when normally it generates near 50). It seems as if the process is quitting to early, because after these 4 files are generated, an echo statement in my shell script that says "Finished running runPerlScript.sh" prints out to my console. I've tried several different ways to run this script, including ProcessBuilder, but none seem to generate the output files. The code I have above was in fact the only way I was able to generate ANY output, because ProcessBuilder just resulted in hangups. Does anyone know how I can continuously make the script run?

A: From the Runtime.exec() javadoc:

"Executes the specified string command in a separate process."

Assuming you want to wait for the process to end, you will need to wait for the process to terminate in your main java thread. The best way to do this would be by monitoring the Process returned by ProcessBuilder.start() and wait with Process.waitFor().


text:
Q: How to remove duplicate "id" column values in python I have several dataframes which I want to merge into only one big dataframe to build a classifier.
This is the base dataframe, user_df_copy
In this dataframe, there is the id column which indicates the client id. I have other dataframes like this one, which have columns related to user_id column.
So, the goal is to merge these small dataframes into the user_df_copy, adding columns like subject_id and to have values only if the user_id matches to the main df id, otherwise, NaN. Problem is, in these small dataframes, the id's appear duplicated.
I also applied get_dummies to the subject_id column like this.

A: If you want to just drop duplicate rows in the smaller DataFrames you can use:
df.drop_duplicates(subset="id")


text:
Q: Pig Latin Translator - JavaScript So for my cit class I have to write a pig Latin converter program and I'm really confused on how to use arrays and strings together.
The rules for the conversion are simple, you just move the first letter of the word to the back and then add ay. ex: hell in English would be ellhay in pig Latin
I have this so far:
<form name="form">

English word/sentence:
 <input type="text" id="english" required="required" size="80" />

<input type="button" value="Translate!" onClick="translation()" />

Pig Latin translation:
 <textarea name="piglat" rows="10" cols="60"></textarea>
</form>

I'd really appreciate any help I can get!

A: function translate(str) {
     str=str.toLowerCase();
     var n =str.search(/[aeiuo]/);
     switch (n){
       case 0: str = str+"way"; break;
       case -1: str = str+"ay"; break;
       default :
         //str= str.substr(n)+str.substr(0,n)+"ay";
         str=str.replace(/([^aeiou]*)([aeiou])(\w+)/, "$2$3$1ay");
       break;
    }
    return str;

}

 translate("paragraphs")

A: I think the two things you really need to be looking at are the substring() method and string concatentation (adding two strings together) in general. Being that all of the objects in the array returned from your call to split() are strings, simple string concatentation works fine. For example, using these two methods, you could move the first letter of a string to the end with something like this:
var myString = "apple";

var newString = mystring.substring(1) + mystring.substring(0,1);

A: This code is basic, but it works.  First, take care of the words that start with vowels.  Otherwise, for words that start with one or more consonants, determine the number of consonants and move them to the end.
function translate(str) {
    str=str.toLowerCase();

    // for words that start with a vowel:
    if (["a", "e", "i", "o", "u"].indexOf(str[0]) > -1) {
        return str=str+"way";
    }

    // for words that start with one or more consonants
   else {
   //check for multiple consonants
       for (var i = 0; i<str.length; i++){
           if (["a", "e", "i", "o", "u"].indexOf(str[i]) > -1){
               var firstcons = str.slice(0, i);
               var middle = str.slice(i, str.length);
               str = middle+firstcons+"ay";
               break;}
            }
    return str;}
}

translate("school");

A: If you're struggling with arrays this might be a bit complicated, but it's concise and compact:
var toPigLatin = function(str) {
    return str.replace(/(^\w)(.+)/, '$2$1ay');
};

Demo: http://jsfiddle.net/elclanrs/2ERmg/
Slightly improved version to use with whole sentences:
var toPigLatin = function(str){
    return str.replace(/\b(\w)(\w+)\b/g, '$2$1ay');
};

A: Here's my solution
function translatePigLatin(str) {
  var newStr = str;
  // if string starts with vowel make 'way' adjustment
  if (newStr.slice(0,1).match(/[aeiouAEIOU]/)) {
    newStr = newStr + "way";
  }
  // else, iterate through first consonents to find end of cluster
  // move consonant cluster to end, and add 'ay' adjustment
  else {
    var moveLetters = "";
    while (newStr.slice(0,1).match(/[^aeiouAEIOU]/)) {
      moveLetters += newStr.slice(0,1);
      newStr = newStr.slice(1, newStr.length);
    }
    newStr = newStr + moveLetters + "ay";
  }
  return newStr;
}

A: Another way of doing it, using a separate function as a true or false switch.
function translatePigLatin(str) {

  // returns true only if the first letter in str is a vowel
  function isVowelFirstLetter() {
    var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
    for (i = 0; i < vowels.length; i++) {
      if (vowels[i] === str[0]) {
        return true;
      }
    }
    return false;
  }

  // if str begins with vowel case
  if (isVowelFirstLetter()) {
    str += 'way';
  }
  else {
    // consonants to move to the end of string
    var consonants = '';

    while (isVowelFirstLetter() === false) {
      consonants += str.slice(0,1);
      // remove consonant from str beginning
      str = str.slice(1);
    }

    str += consonants + 'ay';
  }

  return str;
}

translatePigLatin("jstest");

A: this is my solution code :
function translatePigLatin(str) {
var vowel;
var consonant;
var n =str.charAt(0);
vowel=n.match(/[aeiou]/g);
if(vowel===null)
{
consonant= str.slice(1)+str.charAt(0)+"ay";
}
else
{
consonant= str.slice(0)+"way";
}
var regex = /[aeiou]/gi;
var vowelIndice = str.indexOf(str.match(regex)[0]);
if (vowelIndice>=2)
{
consonant = str.substr(vowelIndice) + str.substr(0, vowelIndice) + 'ay';
}

return consonant;
}

translatePigLatin("gloove");

A: Yet another way.
String.prototype.toPigLatin = function()
{
    var str = "";
    this.toString().split(' ').forEach(function(word)
    {
        str += (toPigLatin(word) + ' ').toString();
    });
    return str.slice(0, -1);
};

function toPigLatin(word)
{
    //Does the word already start with a vowel?
    if(word.charAt(0).match(/a*e*i*o*u*A*E*I*O*U*/g)[0])
    {
        return word;
    }

    //Match Anything before the firt vowel.
    var front = word.match(/^(?:[^a?e?i?o?u?A?E?I?O?U?])+/g);
    return (word.replace(front, "") + front + (word.match(/[a-z]+/g) ? 'a' : '')).toString();
}

A: Another way of Pig Latin:

function translatePigLatin(str) {
  let vowels = /[aeiou]/g;
  var n = str.search(vowels); //will find the index of vowels
  switch (n){
    case 0:
      str = str+"way";
      break;
    case -1:
      str = str+"ay";
      break;
    default:
      str = str.slice(n)+str.slice(0,n)+"ay";
      break;
  }
  return str;
}

console.log(translatePigLatin("rhythm"));

A: Your friends are the string function .split, and the array functions .join and .slice and .concat.

*

*https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Accessor_methods

*https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String#Methods_unrelated_to_HTML
warning: Below is a complete solution you can refer to once you have finished or spent too much time.
function letters(word) {
    return word.split('')
}

function pigLatinizeWord(word) {
    var chars = letters(word);
    return chars.slice(1).join('') + chars[0] + 'ay';
}

function pigLatinizeSentence(sentence) {
    return sentence.replace(/\w+/g, pigLatinizeWord)
}

Demo:
> pigLatinizeSentence('This, is a test!')
"hisTay, siay aay esttay!"


text:
Q: Zoomable image on Lightning Component I need to implement dynamic zoom or a "Magnifying Glass" on an image on Lightning Component(Community).
Example: https://sularome.github.io/Zoomple/
I have searched many sites and tried to implement it with Zoomple plugin for JQuery but it doesn't work for some reason.
Is there any way to do this?
Do you know some JS libraries or something that can help me with it?

A: Zoomple can be integrated as other JS libraries. There is some issue in image referencing in libraries otherwise it is working as expected.
Steps to integrate:

*

*Add all js file and images as zip in static resource.

*Create lighting component using this static resource

Code:
ZoomComponent.cmp
<aura:component >
      <ltng:require
     styles="{!join(',',
        $Resource.zoomple + '/styles.css',
        $Resource.zoomple + '/zoomple.css')}"
       scripts="{!join(',',
        $Resource.zoomple + '/jquery-3.3.1.min.js', $Resource.zoomple + '/jquery-migrate-1.4.1.min.js',
        $Resource.zoomple + '/zoomple.js')}"
    afterScriptsLoaded="{!c.scriptsLoaded}" />

Sniper zoom (with cross)

Default settings

</aura:component>

ZoomComponent.js controller
({
    scriptsLoaded : function(component, event, helper) {
        var blank = window.location.protocol +'//'+ window.location.host + $A.get('$Resource.zoomple') + '/blank.gif';
        var loader = window.location.protocol +'//'+ window.location.host + $A.get('$Resource.zoomple') + '/loader.gif';
        var cursor = window.location.protocol +'//'+ window.location.host + $A.get('$Resource.zoomple') + '/cursor.png';
        $(document).ready(function() {

            var url={
                bgColor : '#90D5D9',
                offset : {x:-150,y:-150},
                zoomWidth : 300,
                zoomHeight : 300,
                roundedCorners : true
            };
            url.blankURL=blank;
            url.loaderURL=loader;
            url.cursorURL=cursor;
            $('.zoomple').zoomple(url);

             var url1={
                bgColor : '#90D5D9',
                offset : {x:-10,y:-10},
                zoomWidth : 300,
                zoomHeight : 300,
                roundedCorners : true
            };
            url1.blankURL=blank;
            url1.loaderURL=loader;
            url1.cursorURL=cursor;
            $('.zoomplecross').zoomple(url1);
         });
    }
})


text:
Q: Running Steam in a Virtual Machine Does anyone have experience running Steam in a Windows XP virtual machine. I was wondering if this works and how well does it work.

A: While there's a possibility that it may technically be possible, the likelihood of it working well at all is incredibly slim. The Steam client itself will run fine, but any of the games you would get through Steam are going to need accelerated graphics. Most virtual machines don't have accelerated graphics, and even if they do, aren't going to have nearly as good of performance as they would running directly on the graphics card. Everything in a VM is going to be slower - processor, disk writes (especially), and graphics. The likelihood of a VM meeting a game's system requirements, let alone running it well, is very, very small.


text:
Q: How can I disable Quick Find hotkey in Firefox? Firefox's Quick Find, activated with '/', is a feature that I really don't use and the key conflicts with access keys in certain web sites (namely Pinboard and ScalaDoc). How can I disable this feature or at least its access key?
I have tried Customizable Shortcuts, but it does not seem to let me change this shortcut.

A: Try setting searchkeys.disable.all in about:config as true.

A: There is an "unofficial" plugin called SearchHotKeys available here: http://nic-nac-project.de/~kaosmos/index-en.html (it's about 3/4 down the rather large page).  It seems to do the trick (I have FF 12.0 and it worked for me).


text:
Q: How to check and uncheck the Checkbox? I am creating a checklist that involves XAMPP and JSON. As my first step before saving the Checkbox state into sharedPreferences, can somebody help me on how to check/uncheck the Checkbox in the setOnItemClickListener? I'm using SimpleAdapter in my onPostExecute therefore I do not know how to check/uncheck the Checkbox. All example that I found often use viewHolder and custom adapter. I can't override thegetViewfor SimpleAdapter.
My AllDetails class extends a ListActivity.
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://10.207.200.73/list/get_details.php";

/// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "list";
private static final String TAG_PID = "quantity";
private static final String TAG_NAME = "items";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.all_products);

  ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

             final CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);

        }
    });

   // Loading products in Background Thread
   new LoadAllProducts().execute();

My JSON part
/**
* Background Async Task to Load all product by making HTTP Request
* */class LoadAllProducts extends AsyncTask<String, String, String> {
   /**
    * Before starting background thread Show Progress Dialog
    * */
   @Override
   protected void onPreExecute() {
       super.onPreExecute();
       pDialog = new ProgressDialog(AllDetails.this);
       pDialog.setMessage("Loading Data. Please wait...");
       pDialog.setIndeterminate(false);
       pDialog.setCancelable(false);
       pDialog.show();
   }

   /**
    * getting All products from url
    * */
   protected String doInBackground(String... args) {
       // Building Parameters
       List<NameValuePair> params = new ArrayList<NameValuePair>();

       // getting JSON string from URL
       JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

       // Check your log cat for JSON reponse
       Log.d("All Products: ", json.toString());

       try {
           // Checking for SUCCESS TAG
           int success = json.getInt(TAG_SUCCESS);

           if (success == 1) {
               // products found
               // Getting Array of Products
               products = json.getJSONArray(TAG_PRODUCTS);

               // looping through All Products
               for (int i = 0; i < products.length(); i++) {
                   JSONObject c = products.getJSONObject(i);

                   // Storing each json item in variable
                   String id = c.getString(TAG_PID);
                   String name = c.getString(TAG_NAME);

                   // creating new HashMap
                   HashMap<String, String> map = new HashMap<String, String>();

                   // adding each child node to HashMap key => value
                   map.put(TAG_PID, id);
                   map.put(TAG_NAME, name);

                   // adding HashList to ArrayList
                   productsList.add(map);
               }
           }
       } catch (JSONException e) {
           e.printStackTrace();
       }

       return null;
   }

   /**
    * After completing background task Dismiss the progress dialog
    * **/
   protected void onPostExecute(String file_url) {
       // dismiss the dialog after getting all products
       pDialog.dismiss();
       // updating UI from Background Thread
       runOnUiThread(new Runnable() {
           public void run() {
               /**
                * Updating parsed JSON data into ListView
                * */
               ListAdapter adapter = new SimpleAdapter(
                       AllDetails.this, productsList,
                       R.layout.list_item, new String[] { TAG_PID,
                               TAG_NAME},
                       new int[] { R.id.quantity, R.id.items });

               // updating listview
               setListAdapter(adapter);
           }
       });
    }}

A: This link will guide you to get checkbox value from custom adapter and save to shared preference. Modify this code to feed the info from json
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("AFG","Afghanistan",false);
countryList.add(country);
...

with your product list and pass to custom adapter
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);

in your onPostExecute() and change checkButtonClick() to save your shared preference from dataAdapter


text:
Q: PyQT5 Focus Problem with Embedded Application My setup is python 3.9 and PyQT5 on Windows 10
I have been using the QtGui.QWindow.fromWinId(<window_handle>) function to successfully embed software like VNCviewer, WinSCP, etc. into a python gui. When I embed a console application (PuTTY SSH Session, Command Prompt) it does not accept keyboard or mouse inputs. The python window has focus but it appears the embedded window does not and doesn't respond to keyboard or mouse.
Code:
class MainWindow(QMainWindow):
    """
    Launches the terminal
    """
    def __init__(self, command: str, substring: str):
        super(MainWindow, self).__init__()

        widget = QWidget()
        layout = QGridLayout(widget)
        self.setCentralWidget(widget)

        win = latchToWindow(command, substring)
        hwnd = win._hWnd
        self.window = QtGui.QWindow.fromWinId(hwnd)
        self.windowcontainer = self.createWindowContainer(self.window, widget)

        layout.addWidget(self.windowcontainer, 0, 0)

def latchToWindow(winLaunchCommand: str, gettitle: str):
    """
    Used when there are additional dialogs and you need to grab a specific one
    :param winLaunchCommand:
    :param title:
    :return:
    """
    makeNewWindow(winLaunchCommand)
    while True:
        windows = pygetwindow.getAllWindows()
        for win in windows:
            tempTitle = win.title
            if gettitle in tempTitle:
                return win
        time.sleep(0.1)

def makeNewWindow(winLaunchCommand: str):
    """
    Makes a new window with that command, and returns that window
    :param winLaunchCommand:
    :return:
    """
    windows = pygetwindow.getAllWindows()
    os.popen(winLaunchCommand)
    while True:
        newWindow = pygetwindow.getAllWindows()
        if len(newWindow) != len(windows):
            for win in newWindow:
                if win.title != "":
                    if win not in windows:
                        time.sleep(0.05)
                        return win

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle("fusion")

    # This doesn't work with keyboard and mouse
    form = MainWindow("start cmd.exe", "cmd.exe")

    # This does work with keyboard and mouse
    // form = MainWindow("putty.exe", "PuTTY")
    form.setWindowTitle('Embedded Python Terminal')
    form.show()
    app.exec()

Screenshot:

[EDIT] I've learned that the problem is pyqt5 is in focus and the command prompt is out of focus. What needs to happen is when the embedded window is clicked that window is focused and the pyqt application needs to lose focus Any ideas on how to do that?
I've tried this solution but it does not work for me (scroll to last comment)

A: Preface: Use focus event handlers and not mouse move handlers to do this
You can use win32gui to force the embedded window to be active even though it has been absorbed by qt.
win32gui.BringWindowToTop(hWnd)
win32gui.SetFocus(hWnd)

In this example I have included it to run every time it detects mouse movements inside the GUI. Ideally you would want it to execute every time you click inside the QWidget but I am relatively new to PyQT5 and have not learned how to do that properly.
Fixed code from example:
class MainWindow(QMainWindow):
    """
    Launches the terminal
    """
    def __init__(self, command: str, substring: str):
        super(MainWindow, self).__init__()

        win = latchToWindow(command, substring)
        self.hwnd = win._hWnd
        widget = widgetMouseTracking(self.hwnd)
        widget.setMouseTracking(True)
        layout = QGridLayout(widget)
        self.setCentralWidget(widget)
        self.window = QtGui.QWindow.fromWinId(self.hwnd)
        self.windowcontainer = self.createWindowContainer(self.window, widget)

        layout.addWidget(self.windowcontainer, 0, 0)

class widgetMouseTracking(QWidget):
    def __init__(self, windowsID):
        super().__init__()
        self.id = windowsID

    def mouseMoveEvent(self, a0: QtGui.QMouseEvent):
        win32gui.BringWindowToTop(self.id)
        win32gui.SetFocus(self.id)

def latchToWindow(winLaunchCommand: str, gettitle: str):
    """
    Used when there are additional dialogs and you need to grab a specific one
    :param winLaunchCommand:
    :param title:
    :return:
    """
    makeNewWindow(winLaunchCommand)
    while True:
        windows = pygetwindow.getAllWindows()
        for win in windows:
            tempTitle = win.title
            if gettitle in tempTitle:
                return win
        time.sleep(0.1)

def makeNewWindow(winLaunchCommand: str):
    """
    Makes a new window with that command, and returns that window
    :param winLaunchCommand:
    :return:
    """
    windows = pygetwindow.getAllWindows()
    os.popen(winLaunchCommand)
    while True:
        newWindow = pygetwindow.getAllWindows()
        if len(newWindow) != len(windows):
            for win in newWindow:
                if win.title != "":
                    if win not in windows:
                        time.sleep(0.05)
                        return win

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle("fusion")

    # This doesn't work with keyboard and mouse
    form = MainWindow("start cmd.exe", "cmd.exe")

    # This does work with keyboard and mouse
    # form = MainWindow("putty.exe", "PuTTY")
    form.setWindowTitle('Embedded Python Terminal')
    form.show()
    app.exec()


text:
Q: Selenium ( with Python ) doesn't start when I use a VPN So I made a program that start a headless browser ( Chrome ) with Selenium in Python.
I have a CyberGhost VPN.
When I try to start my script with the VPN active, Selenium open a chrome windows, with "data" in the url but doesn't proceed further.
Otherwise, it works when I start the script with inactive VPN and turn the VPN on when selenium is running normally.
I don't understart what can be the problem ...
Thanks :)

A: VPN is handled at the OS level, before Selenium gets anywhere near. You can try to setup a config with CyberGhostVPN and run an exec command to start your connection. After that, then start Webdriver and it should be running over VPN. See here on Calling an external command from Python
It may also be due to a firewall issue, so you can also try to deactivate the included firewall in CyberGhostVPN.


text:
Q: Pandas split data frames into multiple csv's based on value from column I have a question similar to this one but I need some further steps. The thing is my file contains like 50k+ lines. Each line have 4 values "Indicator","Country","Date" and "value". I want to split my CSV based on country. I do not know how many countries there is so all countries with similar name should be in one CSV file and so on. The CSV file in not order either. I am using pandas and here is my code so far:
import pandas as pd
def read_csvfile():
    df = pd.read_csv('ebola_data_db_format.csv', sep= ',')

    #remove the unneeded columns
    df = df[df['Country'] != "Guinea 2"]
    df = df[df['Country'] != "Liberia 2"]

    #reset the index
    df.reset_index(drop=True, inplace=True)
    print (df.head(10))

read_csvfile()

I want to be able to have a CSV file for every country so I can plot their data separately. Help please!

A: You  can use groupby:
country_dfs = {k:v for k,v in df.groupby('Country')}

To save them in several csv files:
for k, v in df.groupby('Country'):
    v.to_csv(f'{k}.csv')

or from country_dfs:
for k, v in country_dfs.items():
    v.to_csv(f'{k}.csv')

A: You can use dictionary comprehension here:
dfs_dict = {j: df[df['Country'] == j] for j in df['Country'].unique()}

For saving country-wise data in country cdv's, do this:
for k, v in dfs_dict.items():
    v.to_csv('{}.csv'.format(k))


text:
Q: object Object is not a PostCSS plugin | PostCSS Autoprefixer I am trying to use Grunt PostCSS Autoprefixer but it keeps saying that it is not a PostCSS plugin:
package.json
{
  "name": "test",
  "version": "0.2.0",
  "description": "test",
  "keywords": [
    ""
  ],
  "author": "",
  "license": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "cssmin": "^0.4.3",
    "cssnano": "^5.0.6",
    "grunt": "^1.4.1",
    "grunt-babel": "^8.0.0",
    "grunt-contrib-cssmin": "^4.0.0",
    "grunt-contrib-uglify": "^5.0.1",
    "grunt-contrib-watch": "^1.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.5",
    "@babel/preset-env": "^7.14.5",
    "autoprefixer": "^10.2.6",
    "grunt-postcss": "^0.9.0",
    "grunt-postcss-import": "0.0.1",
    "grunt-prettify": "^0.4.0",
    "postcss": "^8.3.2"
  }
}

Gruntfile.js
postcss: {
  options: {
    map: {
      inline: false,
      annotation: 'dist/css/maps/'
    },
    processors: [
      // require('pixrem')(),
      require('autoprefixer')(),
      //require('cssnano')()
    ]
  },
  dist: {
    src: 'dist/css/bundle.css'
  }
},

I made sure to first remove the grunt-autoprefixer and install autoprefixer which should be a postcss plugin.

A: It turns out it was just a version compatibility issue. I simply changed:
"autoprefixer": "^10.2.6",

with:
"autoprefixer": "^9.7.4",


text:
Q: How can I read an audio file using streams? I am currently looking for away to stream audio-files. I'd like to read x amounts of seconds from a given .wav file, do my analysis task and repeat.....
Here is some code to get the idea of what i want:
`read_x_seconds = 30
 file_length_in_min = 15
 for x in range(file_length_in_min * (60 / read_x_seconds)):
    y, fs = librosa.core.load(FILENAME, offset=x * read_x_seconds,
    duration=read_x_seconds)
    do_analysis(y, fs)`

A: Assuming we're considering a case of reading a chunk of local WAV file:
import wave
import numpy as np

def read_wav_part_from_local(path: str, start_s: float, duration_s: float):
    with wave.open(path, mode='rb') as wavread:
        fs = wavread.getframerate()
        start = int(start_s * fs)
        duration = int(duration_s * fs)
        wavread.setpos(start)
        wav_bytes = wavread.readframes(duration)

        if wavread.getsampwidth() == 2:
            dtype = 'int16'
        elif wavread.getsampwidth() == 4:
            dtype = 'int32'
        else:
            raise NotImplemented('I give up!')

        wav_array = np.frombuffer(wav_bytes, dtype=dtype)
        return wav_array, fs

How to use it:
audio_chunk, fs = read_wav_part_from_local('your.wav', offset_in_s, duration_in_s)

A: with open(stream_file, 'rb') as audio_file:
    content = audio_file.read(BYTES_PER_SECOND)

A: I have got two solutions for blockwise reading / streaming wav files.
This is number one. I have written it my self, so don't relay on it.
def stream_gen(path: str):
    WINDOW_s = 10
    HEADER = 44

    bytes_per_sampling: int
    samplerate: int
    CHUNk: int

    first_block = True
    run = True

    with open(path, 'rb') as stream:
                data = stream.read(HEADER)
                samplerate = int.from_bytes(data[24:28], byteorder='little')
                bits_per_sampling = int.from_bytes(data[34:36], byteorder='little')

                if bits_per_sampling == 16:
                    dtype = 'int16'
                elif bits_per_sampling == 32:
                    dtype = 'int32'
                else:
                    raise IOError()

                CHUNK = WINDOW_s * samplerate * (bits_per_sampling // 8)

                while run:
                    data = stream.read(CHUNK)
                    if data == b'':
                        break
                    yield(np.frombuffer(data, dtype=dtype))

Number two is the obvious one to chose. It was written by professionals.
def soundfile_gen(path):
    window_s = 10
    samplerate = sf.info(path).samplerate
    blocksize = samplerate * window_s
    block_gen = sf.blocks(path, blocksize=blocksize)
    return block_gen


text:
Q: Nomogram with R
view("Mydata")
summary(Mydata)
dim(Mydata)
x = as.matrix(Mydata[,-c(1,2)])
str(x)
time = Mydata$DFT
#time <- as.numeric(time)
event = Mydata$Rec
library(survival)
y = Surv(time, event)
suppressMessages(library(doParallel))
registerDoParallel(detectCores())
aenetfit = fit_aenet(x, y, nfolds = 10, rule = "lambda.1se",
                       seed = c(5, 7), parallel = TRUE)

names(aenetfit)
fit = aenetfit$model_init
alpha = aenetfit$alpha_init
lambda = aenetfit$lambda_init
adapen = aenetfit$pen_factor
suppressMessages(library("rms"))
x.df = as.data.frame(x)
dd = datadist(x.df)
options(datadist = "dd")

nom <- as_nomogram(aenetfit, x, time, event, pred.at = 365 * 2,
                   funlabel = "2-Year Overall Survival Probability")
plot(nom)

*

*I intend to create a nomogram. I have used my own data named
"Mydata".

*It has 9 columns (the time to event column is DFT, while the output of interest is Rec which is binary).

When I run the code, everything worked except the plot (nom). It gave the below error.
Thank you.


text:
Q: Rikulo Bootjack + PolymerDart I'm trying to use the excellent Bootjack library with PolymerDart, and although the CSS theming is working, the dart code isn't executing in the Polymer component.
I've created a dead simple test showing the problem. You'll see the raw html version works fine, but the shadow DOM version doesn't.
Here is the gist. Just download as a zip, it has everything to not work ;)
Any help would be greatly appreciated.
-- Update --
After TinyFox's advice of directly wiring up the control, it now half works. I've updated the gist with the change.
-- Shane

A: The code is not executed because the way you include the main.dart file is outdated.
use
<script type="application/dart">export "main.dart";</script>

The dropdown still doesn't work probably because
..on('click.bs.dropdown.data-api', _toggleEvent, selector: _TOGGLE_SELECTOR)

in packages/bootjack/src/dropdown.dart
where _TOGGLE_SELECTOR is (same file)
static const String _TOGGLE_SELECTOR ='[data-toggle=dropdown]';

isn't working as expected.
I guess the selector doesn't find elements inside a polymer element even if you have set applyAuthorStyles to true.

A: zoechi's answer and my comment explains the possible cause of the problem.
To work it around, you can try to wire the element manually inside your shadow DOM, and it should be able to handle the click event by itself.


text:
Q: How to create and publish a pod in cocoapods.org? What are the steps to follow to create and publish a pod in cocoapods?

A: Prerequisite: Pod should be installed.
Run the following commands in the terminal to install cocoapod.
Sudo gem install cocoapods
Check if installation is successful by running the command.
pod --version
Official cocoapods installation guide
Installation troubleshooting
Steps:

*

*First we have to create an xcode framework that to be hosted in Cocoapods.org.

*To share the framework functionalities to the public, that is, to be accessible outside the module, we have to make the classes, structures, methods of the framework public.

*Then, we have to push the framework to github.

*Create a github tag (Version number) and push the tag.

*We have to create a podspec locally and later (step 8) upload it in the same github directory of the framework. To create a podspec locally run terminal command: pod spec create FrameworkName

*Describe the podspec file accordingly. Podspec guide
Example podspec:
Pod::Spec.new do |spec|
  spec.name = 'Reachability' # name of the framework
  spec.version = '3.1.0' # same as github tag version
  spec.license = { :type => 'BSD' } # can be :type=> 'MIT'
  spec.homepage = 'https://github.com/tonymillion/Reachability' # Website with details about pod or github repository link
  spec.authors = { 'Tony Million' => 'tonymillion@gmail.com' } # name & email address of the framework author
  spec.platform = :ios, "13.0"
  spec.summary = 'ARC and GCD Compatible Reachability Class for iOS and OS X.'
  spec.source = { :git => 'https://github.com/tonymillion/Reachability.git', :tag => 'v3.1.0' } # url to clone the framework, tag may be same as spec.version
  spec.source_files = 'Reachability.{h,m}' # add the regex to access                all the files for the framework ex: 'FrameworkName/**/*.{h,m,swift}'
end

*Save the podspec and then test (lint) the podspec.
Terminal command:  pod spec lint
Warnings can be allowed:  pod spec lint --allow-warnings

*After the podspec passes validation, update the remote repository by pushing the podspec to github repository. (add -> commit -> push)

*To upload the pod in cocoapods.org to be accessible publicly, we have create a pod session. For this, first we have to register to cocoapods if we are not registered yet.
Terminal command:  pod trunk register email username --description='macbook pro'
Then a verification email will be sent to us that we have to verify.

*Create the session. Terminal command:  pod trunk me

*Then we will push the pod. Terminal command: pod trunk push FrameworkName.podspec
Warnings can be allowed :  pod trunk push FrameworkName.podspec --allow-warnings
It will validate (lint) the podspec file.

*It will show a success message if everything goes right with a cocoapods.org link of the framework.

*Push the updated local repository to the remote repository. (add -> commit -> push)

*Following the URL we get from "12", we can see our framework being hosted in cocoapods.org


text:
Q: sharing code from a browserify file I have a JavaScript library that is using Browserify to keep the code modular.
The library itself uses basic Browserify functionality to require other JS files.
myLibrary.js
var utils = require('helpers/utils.js')
console.log("Hello, I am logging from myLibrary")
function my_api(){
  utils.someFn()
}

I'm using Gulp to browserify myLibrary.js and it is being built correctly, I've put several logs into myLibrary.js and when I load the file in an example html file I can see the logs.
I have an example index.html file that uses myLibrary.js and I expect my_api to be accessible from index.html.
index.html
<script src="my_url/myLibrary.js"></script>
<script src="app.js"></script>

app.js
my_api()

Chrome console
Hello I am logging from myLibrary (myLibrary.js)
Uncaught ReferenceError: my_api is not defined (app.js)

I've tried to defer the loading of app.js until myLibrary.js was ready but I'm beginning that that is not the problem.

A: You need to export your public functions.
module.exports = {my_api: my_api};

A: The solution I ended up using was to expose one global object that contains all the methods I want to expose through myLibrary using the window object.
myLibrary.js is requiring a utility function file and using them as helpers in the methods that I want to expose.
myLibrary.js
var util = require("utils.js")
window.myGlobalObjWithAUniqueName = {
  myFn: function(){
    util.someHelper()
  }
}

Then I use Browserify to create the new browserified_myLibrary.js and use its methods in any file I want to load it in.
index.html
<script src="browserified_myLibrary.js"></script>
<script src="app.js"></script>

app.js
myGlobalObjWithAUniqueName.myFn()

Not sure if this is the best way of doing this but this seems to suit my need to modularize a client side library and use it without having to use Browserify every time I use it.

A: You may also want to look into the --standalone option exposed by browserify:

When opts.standalone is a non-empty string, a standalone module is created with that name and a umd wrapper. You can use namespaces in the standalone global export using a . in the string name as a separator, for example 'A.B.C'. The global export will be sanitized and camel cased.

From https://github.com/substack/node-browserify#usage


text:
Q: Is there any way to retrieve the chef node specific parameters available in data bag Hi i have the parameters in my chef databag which is encrypted.
Now i want some parameters to be displayed from chef data bag
is there any way or command similar for that

A: you can retrieve a data bag item and decrypt it using knife:

$ knife data bag show DATA_BAG_NAME (options)
This argument has the following options:

*

*DATA_BAG_ITEM
  The name of a specific item within a data bag.

*--secret SECRET
  The encryption key that is used for values contained within a data bag item. If secret is not specified, the chef-client looks for a
  secret at the path specified by the encrypted_data_bag_secret setting
  in the client.rb file.

*--secret-file FILE
  The path to the file that contains the encryption key.

A: The above query is for the single databag properties to retrive but what about multiple data bags at a time is there any command or script for that i have tried several combinations but i am unable to retrive the data.
i mean to sat that
lets put all the data bag names passed in a variable and that variable is called with in the script along with the knife command is there any possibility like that.