text:
Q: Angular momentum and Schrodinger equation I'm studying stationary states and their orbital angular momentum in 3D Schrodinger equation. I have tried to understand by myself the situation but I get lost. I think it might be useful to know which cases are possible before starting the derivation by myself, so can you tell me:

Which of the following three situations are possible?

*

*A stationary state in a central field that has a non determined modulus of the orbital angular-momentum.

*A stationary state in a non-central field that has a non determined modulus of the orbital angular-momentum.

*A stationary state in a non-central field has a determined modulus of the orbital angular-momentum.

A: By definition, a central force is spherically symmetric. From Noether's theorem, this implies that angular momentum is conserved. Equivalently, the angular momentum operator commutes with the Hamiltonian. This implies that $L^2$ and $H$ have simultaneous eigenvectors, so there are stationary states (i.e. eigenvectors of $H$) which have definite angular momentum (i.e. eigenvectors of $L^2$). Let's see what this argument implies about each of the three cases:

*

*$L^2$ and $H$ must share some eigenstates. However, there's no guarantee that they share all eigenstates. When $H$ has repeated eigenvalues, there might exist eigenstates of $H$ which are not also eigenstates of $L^2$, so this is possible.

*This is also possible, for more or less the same reason as 1.

*Two operators can share one eigenstate without sharing a complete basis of eigenstates, so this is possible.


text:
Q: Web Scrape Second  tag in single  I am trying to web scrape using beautifulsoup the first and second  tags (-130, and +110) in this single HTML div (as seen below):
example HTML
However I can not figure out how to scrape the second tag, can only scrape the first. Thank you.
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

day = "09"
month = "10"
year = "2017"
my_url = 'https://www.sportsbookreview.com/betting-odds/mlb-baseball/?date=' + year + month + day

# Opening up the connection and grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parser
page_soup = soup(page_html, "html.parser")

allBovadaOdds = page_soup.find_all("div", {"rel": "999996"})

firstOdds = allBovadaOdds[1].b.string
print(firstOdds)

A: What you want can be written fairly simply, I think.
>>> import bs4
>>> import requests
>>> page = requests.get('https://www.sportsbookreview.com/betting-odds/mlb-baseball/?date=20171009').text
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> soup.select('#eventLine-3330496-43 b')
[-130, +110]
>>> for item in soup.select('#eventLine-3330496-43 b'):
...     item.text
...
'-130'
'+110'

However, I notice two potential problems:

*

*The labelling of the elements (ie, ids of divs, etc) might vary from one invocation of the web page to the next.

*There are actually two columns with this pair of values. It might be safer to identify the required items by using booking agent and number for instance.

A: You may try to use soup.select() filter tags and use  for i in range(): to get all of the second  tags. Note that the step in range() should be 2.
# html parser
page_soup = soup(page_html, "html.parser")
allBovadaOdds = page_soup.select('div[rel="999996"] b')
print(allBovadaOdds)
for i in range(1,len(allBovadaOdds),2):
    SecondOdds = allBovadaOdds[i].string
    print(SecondOdds)

redpajama_set_name: RedPajamaStackExchange


text:
Q: modelo ApplicationUser no aparece en el listado 'Model class' cuando intento crear un controlador nuevo utilizando un 'Controlador con vista y usando Entity Framework' este modelo en particular no aparece dentro, lo que me hace preguntarme: por qué no aparecería una clase en este listado?
Por favor ayúdenme con esto
Mi data context class está seleccionada, pero aún asi no carga la clase ApplicationUser.cs


text:
Q: How to search array using UISearchBar I have multiple ViewControllers all linked to an initial ViewController. Each of the extra ViewControllers acts as a 'tennis court', with player1 and player2's names entered into UITextFields, and then stored in an array.
Is it possible, using a UISearchBar on the initial ViewController, to search the name of a player stored in one of the various variables, and then for that result to link to the ViewController within which it appears?

A: Recall MVC.
You never store your data or model in any viewControllers. You store them in a model that may be an array, dictionary, or plist or even a database.
So you need to search from the model using your UISearchBar.
*If you show your code, we can correct them.


text:
Q: Maven exclude file from final WAR I'm using Maven 3 to package a WAR file, and I cannot figure out how to exclude files in src/main/webapp from the final WAR generated. One of the directories in src/main/webapp is a git submodule, and I want to exclude files like README, docs/, etc. in that git submodule form going to my final WAR.
My initial attempt was to use the maven-antrun-plugin to delete the files. I tried the delete actions in prepare-package and package, but neither worked. Doing the deletes in package removed the files from my target/<projname>/..., but the final WAR still contains the files. Running maven with -debug shows that the files are deleted after the WAR file is generated. It's almost as if I want to do the deletes in between prepare-package and package.
My next attempts were to try to specify files to exclude from the WAR (some solutions linked below), but nothing seems to work. I might not be specifying the path to the unwanted files correctly, and I'm wondering if it has to do with the fact that my unwanted files are not in src/main/resources, but in src/main/webapp.
I've tried many solutions, but nothing seems to work. Each time I try something new, I do mvn clean and delete the target directory. The final generated WAR file always contains the unwanted files.
I feel like the answer to my problem exists on the SO and google searches I've come across, but nothing I've tried has worked exactly as I need. Below are some solutions I've tried.

*

*exclude file from maven build

*In Maven how to exclude resources from the generated jar?

A: since the files are inside the webapp folder I would guess the maven-war-plugin is the best point to start. the resource filtering with excludes points to src/main/resources and is not aware of the webapp folder.
So http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html
There is a parameter: warSourceExcludes: http://maven.apache.org/plugins/maven-war-plugin/war-mojo.html#warSourceExcludes
this should allow filtering the README files and so on.


text:
Q: Scrolling left/right to new pages I am creating an application which displays several "pages" of content. Typically this is representative as tabs on a desktop based application.
On android, I want to be able to flick between the tabs of information, using there finger anywhere on the screen. The content of these tabs will just be XML views, or programmatically created views.
Looking at Applications on android, there are several applications that do this. Google Play, Gmail, Beautiful Widgets, BBC News, Contacts, Engadget.
I've looked for several terms, mostly scrollable tabs but haven't found anything that is similar to the above applications. I'm looking at TabHost, TabWidget and ViewPaper at the moment, but not sure if these do what I'm looking for.
Can anyone tell me which control can be used in android to get the functionality. Out of the apps listed I'm looking to have it styled more like the Google Play store, with the name of the tab at the top, and the names of the nearby tabs to the left and right if applicable.

A: There is an example on the android blog for this, used on google play app.
Horizontal View Swiping with ViewPager

A: Sounds like you're looking for this. It's compatible with ViewPager, the v4 compatibility library, and ActionBarSherlock.


text:
Q: Properly invoking an interactive script from elisp I have an external command line program that I would like to invoke from elisp. This is easy enough with shell-command, but it doesn't work correctly when the command line program is interactive, which in my particular case it is: The invoked script sees EOF when it reads stdin when I call it like this:
  ;; upload command is a string with the name of
  ;; a python script and some args
  (shell-command upload-command
                 (get-buffer-create "*upload output*")))))

The python script identified by upload-command may ask some yes/no questions and it may prompt for a password, for which I'd like masked input. Ideally, all of this interaction would occur within the minibuffer.
How can I arrange things so that my external interactive command interacts with the user via minibuffer when called via elisp?

A: The easiest way is to use either make-comint or make-comint-in-buffer:
(make-comint-in-buffer "upload-script-process" "*upload output*" upload-command)

This will runs the script in a buffer like a shell buffer, so it doesn't fulfill the requirement of having all interaction happen in the minibuffer.  It will, however, automatically read passwords in masked form from the minibuffer, provided the password prompt matches comint-password-prompt-regexp.
Note that upload-command in this example here needs to be the name of an executable file on exec-path.  Any extra switches or other arguments to the script have to be passed as string arguments to make-comint:
(make-comint-in-buffer "upload-script-process" "*upload output*"
   upload-command nil "--verbose" "--other-option")

See the Emacs documentation for more details.


text:
Q: Partcles JS component is not visible in react app
I want to add the contellation pattern as background of my react app.
But even after adding the component
I cannot see the design.
I am using particle.js A lightweight JavaScript library for creating particles and then using that as design for website

Pattern Design

[enter image description here][1]

Website Design

[enter image description here][2]

File Structure
[enter image description here][3]

> Particle Config File
const ParticlesConfig = {
    particles: {
      number: {
        value: 120,
        density: {
          enable: true,
          value_area: 800
        }
      },
      color: {
        value: "#ffffff"
      },
      shape: {
        type: "circle",
        stroke: {
          width: 0,
          color: "#000000"
        },
        polygon: {
          nb_sides: 5
        },
        image: {
          src: "img/github.svg",
          width: 100,
          height: 100
        }
      },
      opacity: {
        value: 0.5,
        random: false,
        anim: {
          enable: false,
          speed: 1,
          opacity_min: 0.1,
          sync: false
        }
      },
      size: {
        value: 3,
        random: true,
        anim: {
          enable: false,
          speed: 40,
          size_min: 0.1,
          sync: false
        }
      },
      line_linked: {
        enable: true,
        distance: 150,
        color: "#ffffff",
        opacity: 0.4,
        width: 1
      },
      move: {
        enable: true,
        speed: 6,
        direction: "none",
        random: false,
        straight: false,
        out_mode: "out",
        bounce: false,
        attract: {
          enable: false,
          rotateX: 600,
          rotateY: 1200
        }
      }
    },
    interactivity: {
      detect_on: "canvas",
      events: {
        onhover: {
          enable: false,
          mode: "repulse"
        },
        onclick: {
          enable: true,
          mode: "push"
        },
        resize: true
      },
      modes: {
        grab: {
          distance: 400,
          line_linked: {
            opacity: 1
          }
        },
        bubble: {
          distance: 400,
          size: 40,
          duration: 2,
          opacity: 8,
          speed: 3
        },
        repulse: {
          distance: 200,
          duration: 0.4
        },
        push: {
          particles_nb: 4
        },
        remove: {
          particles_nb: 2
        }
      }
    },
    retina_detect: true
  }

export default ParticlesConfig;

Particle Background component

import React from 'react'
import Particles from 'react-tsparticles'
import ParticlesConfig from '../config/particleConfig.js'

const ParticleBackground = () => {
  return (
    <Particles   style={{ position: "absolute" }}
    height="95%"
    width="95%"
   params={ParticlesConfig}></Particles>
  )
}

export default ParticleBackground

> Home component Consists of  particle component but I don't see any design.

import React from 'react'
import Links from '../components/Links'
import Main from '../components/Main'
import Navbar from '../components/Navbar'
import ParticleBackground from '../components/ParticleBackground'
import Portfolio from '../components/Portfolio'

const Home = () => {
  return (
    <div className='bg-gradient-to-b from-black to-gray-800'>
        <ParticleBackground/>
        <Navbar/>
        <Main/>
        <Links/>
        <Portfolio/>
    </div>
  )
}

export default Home

  [1]: https://i.stack.imgur.com/DzLmU.png
  [2]: https://i.stack.imgur.com/Mjd7E.png
  [3]: https://i.stack.imgur.com/n9yAT.png


text:
Q: angularjs - Error: [$rootScope:infdig] I recently updated my controller and factories to get a better scope of handling my data flow, my Controller looks like this:
uno.controller('newsCtrl', function($scope, $http, adbFactory, $cacheFactory, unoFunctions){
    $scope.init = function(){
        adbFactory.get($http, 'get all blog_posts', true).success(function(data){
            $scope.posts = data;

            $scope.getUser = function(_id) {
            $scope.userData = unoFunctions.getUser(_id);
                //console.log($scope.userData);

                return $scope.userData;
            };
        });

        $scope.getTags = function(_id) {
            var post = unoFunctions.getPost(_id);
            var _tags = post.tags.split(',');
            for(var i = 0; i < _tags.length; i++)
            {
                _tags[i] = _tags[i].trim();
            }

            return _tags;
        };

        $scope.getUserName = function(_id) {
            $scope.userData = unoFunctions.getUser(_id);
            return $scope.userData.display_name;
        };

        $scope.getUser = function(_id) {
            $scope.userData = unoFunctions.getUser(_id);
            //console.log($scope.userData);
            return $scope.userData;
        };

        $scope.getUserName = function(_id) {
            $scope.userData = unoFunctions.getUser(_id);
            return $scope.userData.display_name;
        };
    };
});

the unoFunctions factory is wht I use now to handle certain requests from my database, and that is shown below.
uno.factory('unoFunctions', function(adbFactory, $http, $cacheFactory){
    var fact = {};

    var user = $cacheFactory('user');
    var post = $cacheFactory('post');

    fact.getUser = function(_id) {
        if(!user.get(_id)){
            adbFactory.get($http, 'get users id '+_id+' spec', false).success(function(data){
                user.put(_id, data);
            });
        }

        return user.get(_id);
    };
    fact.getPost = function(_id) {
        if(!post.get(_id))
        {
            adbFactory.get($http, 'get blog_posts id '+_id+' spec', false).success(function(data){
                post.put(_id, data);
            });
        }

        return post.get(_id);
    };

    fact.loggedIn = function()
    {
        console.log('gfdg');
    };

    /*------------------------------*/
    return fact;
});

And my template to output the result is this:

                            {{topic['title']}}

{{ topic.time | timeago }} {{  }}

Posted By, {{ getUser(topic.author_id).display_name }}

{{ topic['body'] }}

{{ tag }}

{{ topic.category }}</p

This works fine and returns the required results I'm looking for but I wish to get rid of the countless Error: [$rootScope:infdig] errors and keep my console clean.. I researched the error and it seems to be because when I call functions from the unoFunctions factory like, getUser, or getPost. it returns a new array each time or something like that which I guess throws things out of scope. I'm not entirely sure, but is there a solution to this?


text:
Q: nmap skip port scan but execute --script? I'm trying to use nmap with a script which works with a normal scan. But when executing nmap -sn --script=... it just finds the host (target) and stops.
What would the command be to scan the target with the script but not do a port scan?

A: NSE (Nmap Scripting Engine) scripts are designed to run based on the return value of at least one of four functions (called Rules)defined in the script:

*

*prerule() - This function is run once at the beginning of the entire scan. If it returns true, then the action function is called with no arguments.

*portrule(host, port) - This function is run once for every open port on every host. If it returns true, then the action(host, port) function is run for that host and port combination.

*hostrule(host) - This function is run once for every host that is found to be up. If it returns true, then the action(host) function is run for that host.

*postrule() - This function works the same as the prerule but is run after all hosts have been scanned.

So when you scan with -sn ("skip port scan"), the portrule scripts will not run at all, since there are "no open ports." The best way to do a targeted script scan is to determine what the relevant ports are and specify them with -p. For instance, if I wanted to run ssh-hostkey without doing a full port scan, I would do this: nmap -p 22 --script ssh-hostkey <targets>


text:
Q: Create Windows installer I was wondering if anyone had any advice on the best way to create an installer for an application that first checked if the correct version of .NET was installed and if it wasn't downloaded and installed it first and then continued on to install my application.
The application itself is quite small so bundling .NET in with the installer is crazy as it would push the size from 5Mb to 250Mb thats why I want it to download first.
Any advice or links to articles about this problem would be great,

A: You can use Visual Studio Setup project to get done this easily. What you have to do is add required .net framework under "Detect Dependencies". You can give the link to download the .net framework. Here is a good step by step example.
Here is a another example for your case.

A: Inno Setup is a free tool that's easy to use and that will do it for you, and I think ClickOnce might provide a link also. http://jrsoftware.org


text:
Q: Are conditions equaivalent that they are roots of unity? If I have conditions that $|z_1|=|z_2|=|z_3|=|z_4|=1$ and $z_1+z_2+z_3+z_4=0$
Is it suffice to state they are roots of unity ?

A: No. For an $n$th root of unity we must have $z_1=e^{2k\pi i/n}$ with $k\in\mathbb Z$. So if $z_1=e^i$, it is not an $n$th root of unity for any $n$ (because $\pi$ is irrational), but still $|z_1|=1$. Let $z_2=iz_1$, $z_3=-z_1$, $z_4=-iz_1$ to have four distinct nonroots of unity that add up to $0$.

A: If $z=re^{iy}$ where $r\ge0,y$ are real
$\implies|z|=r$
So, if $|z|=1,r=1\implies z=e^{iy}$
So, $z$ is  $\dfrac{2\pi}y$th root of unity

A: Hint:
Since we're interested in nth root of unity so, $$x^n=1$$
$$x^n-1=0$$
Now we can use product of roots $=-1$ and other conditions depending on degree of polynomial.


text:
Q: Better way to set the user that last updated a model, when the model has many childs I have a model that I'll call Parent. When this model is updated, I register which User did this last update on the parent model. I do this at the ParentsController like this:
def update
  @parent = Parent.find(params[:id])
  @parent.assign_attributes(params[:parent])
  @parent.last_editor = current_user

  if @parent.save
    # continue....

This works well. The controller tells the model who is the current_user. The concerns are separated well.
But the Parent model has many different child models and I want to update the last_editor of the Parent when its childs are updated. (The last_editor is a User).
I could do this:
class ChildOnesController
  # ...
  def create
    @child_one = ChildOne.new(params[:child_one])

    if @child_one.save
      @child_one.parent.update_attribute(last_editor: current_user)
    else
      # ...
    end
  end

  def update
    @child_one = ChildOne.find(params[:id])

    if @child_one.update_attributes(params[:child_one])
      @child_one.parent.update_attribute(last_editor: current_user)
      # continue....
    end
  end

  def destroy
    # Destroy...then
    @child_one.parent.update_attribute(last_editor: current_user)
    # ...
  end

The main problem is: As my Parent model has various child models, I'll have to add those lines to every child model controller.
Is there a better, more concise way to do this?
Thanks a lot for any hint!!!

A: You could use a mixin and name the instance variable you assign a child to consistently in all controllers.
module ChildControllerMixin
  def update_last_editor
    @child.parent.update_attribute(last_editor: current_user) if @child.valid?
  end
end

class ChildOnesController
  include ChildControllerMixin
  after_filter :update_last_editor, only: [:create, :update, :destroy]
end

I don't know how great of an option it is since it seems a little fragile but it might help you.
Edit: you may want to reconsider why you have a separate controller for each child. Are they similar enough that there is only a need for one controller?

A: Using such approach, your data will be messed up soon. You will be forced to manage each action in controller, so last_editor is set properly. I recommend you to change it like this:
# user.rb

def self.current_user=(user)
  Thread.current[:current_user] = user
end

def self.current_user
  Thread.current[:current_user]
end

Now current_user will be available using User.current_user in your models. All we need is just set it in your application controller.
# application_controller.rb

before_filter :set_current_user

def set_current_user
  User.current_user = current_user
end

From this moment we can create callback in model to set last_editor on every save.
# parent.rb

before_save :set_last_editor

...

def set_last_editor
  self.last_editor = User.current_user
end

And last moment for your children models. You need just resave parent on every change in children models.
# every_children_model.rb

after_save :update_parent

...

def update_parent
  # ... get parent
  parent.save!
end

Now any action in your system, no matter which controller you use, will handle last_editor problem.


text:
Q: EXTJS MVC Tree store Am having a tree view which gets its data from the tree store. But, however, am able to see only the small folders that gets displayed as part of a tree structure. the name of the nodes is not getting displayed, and when i try to print the record, it just says that its an empty string. Here is the code:
App/View
Ext.define('App.view.Hierarchy', {
    alias: 'widget.hierarchy',
    extend: 'Ext.panel.Panel',

    initComponent: function () {

        var config = {

            xtype: 'panel',
            border: false,
            autoScroll: true,
            baseCls: 'topMenu',
            html: '
' + LANG.HIERARCHYT + '
' + LANG.HIERARCHYTxt + '
' + '
',

            items: [{
                xtype: 'toolbar',
                border: false,
                dock: 'top',
                items: [{
                    xtype: 'button',
                    text: LANG.BTADDREG,
                    iconCls: 'icon-add-tb',
                    cls: 'tip-btn',
                    iconAlign: 'right',
                    action: 'addRegion',
                    id: 'ADDREGION'
                }]

            },

            {
                xtype: 'treepanel',
                title: 'Hierarchy Tree',
                id: 'hierarchyTree',
                border: false,
                alias: 'widget.hierarchyTree',
                height: 1000,
                viewConfig: {
                    enableDD: true,
                    plugins: {
                        ptype: 'treeviewdragdrop'
                    }
                },
                collapsible: false,
                useArrows: true,
                rootVisible: false,
                store: Ext.create('Campus.store.HierarchyTree'),
                displayField: 'Title',
                multiSelect: false,
                singleExpand: false,

            }]
        }

        var holder = Ext.getCmp('center');
        holder.remove(0);
        holder.add(Ext.apply(config));
        this.callParent(arguments);
    }
});

Model
Ext.define('App.model.HierarchyTree', {
    extend : 'Ext.data.Model',
    fields : ['Title', 'ID', 'LevelID', 'ParentID']
});

Store
Ext.define('App.store.HierarchyTree', {
    extend: 'Ext.data.TreeStore',
    model: 'App.model.HierarchyTree',
    storeID: 'HierarchyTree',

    proxy: {
        type: 'ajax',
        url: 'data/Locations.aspx',

        reader: {

        },
        actionMethods: {
            create: 'POST',
            read: 'POST',
            update: 'POST'
        },
        extraParams: {
            mode: 'HIERARCHYFULLLIST'

        }
    },
    autoLoad: true
});

Controller
Ext.define('App.controller.Hierarchy', {
    extend: 'Ext.app.Controller',
    stores: ['Me', 'Regions', 'Areas', 'Towns', 'HierarchyTree'],
    model: ['Me', 'Teams', 'Regions', 'User', 'HierarchyTree'],
    views: ['App.view.Hierarchy', 'App.view.AddRegions'],
    refs: [{
        ref: 'myHierarchyTree',
        selector: 'hierarchyTree'
    }],

    init: function () {

        this.getHierarchyTreeStore().load();

        this.control({
            'button[action=addRegion]': {
                click: this.addRegion
            },
            '#hierarchyTree': {
                itemclick: this.itemclick

            }
        })
    },
    itemclick: function (view, record) {
        console.log(record.get('Title'))
    }
});

Also, the JSON thats being returned is:
{"text":".","children": [{"text":"Asia Pacific","id":"537","level":"1", "expanded":
 false,"singleClickExpand":true,"children":[{"text":"Japan", "cls":"xtreenode-Level2-
Indent", "id":"538", "hl1":"537","level":"2","singleClickExpand":true, "expanded":
false, "children":[]},

A: Treepanel's display field defaults to text, which is ok with the json being returned, but the problem is the store model, which should include as fields the text, cls ..and other attributes you have in your json. Otherwise these will not be mapped to the records and you get empty text.
Ext.define('App.model.HierarchyTree', {
extend : 'Ext.data.Model',
fields : ['Title', 'ID', 'LevelID', 'ParentID', 'text', 'level','cls,....]

EDIT
You have modified the displayField to be the Title, but the json doesn't contain the title attribute. You have to simple fixes, either you modify the model if the text is actually the title. You can do this by setting a mapping to the field.
  Ext.define('App.model.HierarchyTree', {
    extend : 'Ext.data.Model',
    fields : [{name:'Title',type:'string',mapping:'text'}, 'ID', 'LevelID', 'ParentID',]

This will cause the Title to be populated by the text values from the json.
Also you can remove the displayField config and then the text value will be applied, but this will still mean that the 'Title' value will be empty.

A: OK, finally got it:)
Set the displayfield in the tree to 'text'
 displayfield : 'text'

And, Once again thank you nscrob
And one more question, could you please give me any guidance on how to open different views depending upon the level in the tree that is being clicked
This works.
if (record.get('level')==1)
    {
        this.erWin = Ext.create('App.view.EditRegions');

        this.erWin.showWin();
    }
    else{
        //open another_view
    }


text:
Q: iframe display:none not working My code is:
<!DOCTYPE html>

Your browser does not support iframes.

I want to change the css property "display" as "none" but it showing an error after page loading.

*

*Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "http://www.amway.in".  The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "http". Protocols must match.

A: That's because of Same-origin policy.

The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin.
  [...]
Cross-origin script API access
JavaScript APIs such as iframe.contentWindow, window.parent, window.open and window.opener allow documents to directly reference each other. When the two documents do not have the same origin, these references provide limited access to the Window and Location objects. Some browsers allow access to more properties than the spec allows. You can use window.postMessage instead to communicate between documents.

You can read more about this subject here.


text:
Q: AttributeError: 'str' object has no attribute 'name' in Tensorflow I am trying to predict the prices of items using Dnnregressor and I couldn't figure out this error that keeps coming. I created tf numeric and categorical columns from pandas dataframe and fed it into the DNNRegressor. There is not much help online regarding this particular error.
Please help me fix this error. Thanks
AttributeError                            Traceback (most recent call last)
<ipython-input-27-790ecef8c709> in <module>()
 92
 93 if __name__ == '__main__':
---> 94     main()

<ipython-input-27-790ecef8c709> in main()
 81      #   learning_rate=0.1, l1_regularization_strength=0.001))
 82     est = tf.estimator.DNNRegressor(feature_columns = feature_columns,  hidden_units = [10, 10], model_dir = 'data')
---> 83     est.train(input_fn = get_train_input_fn(Xtrain, ytrain), steps = 500)
 84     scores = est.evaluate(input_fn = get_test_input_fn(Xtest, ytest))
 85     print('Loss Score: {0:f}' .format(scores['average_loss']))

C:\Users\user\Anaconda3\lib\site-   packages\tensorflow\python\estimator\estimator.py in train(self, input_fn, hooks, steps, max_steps)
239       hooks.append(training.StopAtStepHook(steps, max_steps))
240
--> 241     loss = self._train_model(input_fn=input_fn, hooks=hooks)
242     logging.info('Loss for final step: %s.', loss)
243     return self

C:\Users\user\Anaconda3\lib\site-packages\tensorflow\python\estimator\estimator.py in _train_model(self, input_fn, hooks)
628           input_fn, model_fn_lib.ModeKeys.TRAIN)
629       estimator_spec = self._call_model_fn(features, labels,
--> 630                                            model_fn_lib.ModeKeys.TRAIN)
631       ops.add_to_collection(ops.GraphKeys.LOSSES, estimator_spec.loss)
632       all_hooks.extend(hooks)

C:\Users\user\Anaconda3\lib\site- packages\tensorflow\python\estimator\estimator.py in _call_model_fn(self, features, labels, mode)
613     if 'config' in model_fn_args:
614       kwargs['config'] = self.config
--> 615     model_fn_results = self._model_fn(features=features, **kwargs)
616
617     if not isinstance(model_fn_results, model_fn_lib.EstimatorSpec):

C:\Users\user\Anaconda3\lib\site-packages\tensorflow\python\estimator\canned\dnn.py in _model_fn(features, labels, mode, config)
389           dropout=dropout,
390           input_layer_partitioner=input_layer_partitioner,
--> 391           config=config)
392     super(DNNRegressor, self).__init__(
393         model_fn=_model_fn, model_dir=model_dir, config=config)

C:\Users\user\Anaconda3\lib\site-packages\tensorflow\python\estimator\canned\dnn.py in _dnn_model_fn(features, labels, mode, head, hidden_units, feature_columns, optimizer, activation_fn, dropout, input_layer_partitioner, config)
100       net = feature_column_lib.input_layer(
101           features=features,
--> 102           feature_columns=feature_columns)
103
104     for layer_id, num_hidden_units in enumerate(hidden_units):

C:\Users\user\Anaconda3\lib\site-packages\tensorflow\python\feature_column\feature_column.py in input_layer(features, feature_columns, weight_collections, trainable)
205     ValueError: if an item in `feature_columns` is not a `_DenseColumn`.
206   """
--> 207   _check_feature_columns(feature_columns)
208   for column in feature_columns:
209     if not isinstance(column, _DenseColumn):

 C:\Users\user\Anaconda3\lib\site-  packages\tensorflow\python\feature_column\feature_column.py in     _check_feature_columns(feature_columns)
1660   name_to_column = dict()
1661   for column in feature_columns:
-> 1662     if column.name in name_to_column:
1663       raise ValueError('Duplicate feature column name found for columns: {} '
1664                        'and {}. This usually means that these columns refer to '

C:\Users\user\Anaconda3\lib\site-packages\tensorflow\python\feature_column\feature_column.py in name(self)
2451   @property
2452   def name(self):
-> 2453     return '{}_indicator'.format(self.categorical_column.name)
2454
2455   def _transform_feature(self, inputs):

AttributeError: 'str' object has no attribute 'name'

And below is code:
def get_train_input_fn(Xtrain, ytrain):
return tf.estimator.inputs.pandas_input_fn(
        x = Xtrain,
        y = ytrain,
        batch_size = 30,
        num_epochs = None,
        shuffle = True)

def get_test_input_fn(Xtest, ytest):
return tf.estimator.inputs.pandas_input_fn(
        x = Xtest,
        y = ytest,
        batch_size = 32,
        num_epochs = 1,
        shuffle = False)
def main():
Xtrain, Xtest, ytrain, ytest = train_test_split(merc, ytr, test_size = 0.4, random_state = 42)
feature_columns = []
brand_rating = tf.feature_column.numeric_column('brand_rating')
feature_columns.append(brand_rating)
sentiment = tf.feature_column.numeric_column('description_polarity')
feature_columns.append(sentiment)
item_condition = tf.feature_column.numeric_column('item_condition_id')
feature_columns.append(item_condition)
shipping = tf.feature_column.indicator_column('shipping')
feature_columns.append(shipping)
name = tf.feature_column.embedding_column('item_name', 34) #(column name, dimension(no. of unique values ** 0.25))
feature_columns.append(name)
general = tf.feature_column.categorical_column_with_hash_bucket('General', 12)
feature_columns.append(general)
sc1 = tf.feature_column.categorical_column_with_hash_bucket('SC1', 120)
feature_columns.append(sc1)
sc2 = tf.feature_column.categorical_column_with_hash_bucket('SC2', 900)
feature_columns.append(sc2)
print(feature_columns)
#est = tf.estimator.DNNRegressor(feature_columns, hidden_units = [10, 10], optimizer=tf.train.ProximalAdagradOptimizer(
 #   learning_rate=0.1, l1_regularization_strength=0.001))
est = tf.estimator.DNNRegressor(feature_columns = feature_columns, hidden_units = [10, 10], model_dir = 'data')
est.train(input_fn = get_train_input_fn(Xtrain, ytrain), steps = 500)

A: The first argument to tf.feature_column.embedding_column must be a categorical column, not a string. See API spec.
The offending line in your code is:
tf.feature_column.embedding_column('item_name', 34)

A: After using
general = tf.feature_column.categorical_column_with_hash_bucket('General', 12)

and other feature_column.categorical_column_with..., you should use
general_indicator = tf.feature_column.indicator_column(general)

and then append it to your feature_columns list.
feature_columns.append(general_indicator)


text:
Q: how to solve triangles count puzzle Below is a puzzle of counting triangles.How to solve such puzzle ?

source:
http://gpuzzles.com/mind-teasers/how-many-triangles-challenge/?source=stackmath

A: Be systematic. Label all your points. Choose a unique label for each triangle, e.g. by listing point labels in alphabetic order. Enumerate triangles in some order so you can check for them one at a time. I'd suggest lexicographic order.
Exploit symmetry. Many triangles will occur four times, or even eight times, throughout the figure in rotated and posibly reflected versions of one another. So you can keep the work down if you find only one representative of each such group, as long as you make sure to get the associated count right.
Combining these ideas, I'd label the figure like this:

Then you can enumerate triangles like this:

*

*Axy: $4ABB, 0ABC, 8ABE, 8ABF, 0ACC, 0ACD, 0ACE,$
$\qquad 8ACF, 0ADD, 0ADE, 8ADF, 0AEE, 0AEF, 4AFF$

*Bxy: $4BBB,0BBC,0BBD,0BBE,4BBF,0BCC,0BCD,0BCE,$
$\qquad 8BCF,0BDD,0BDE,8BDF,0BEE,8BEF,4BFF$

*Cxy: $0CC*, 0CDD, 0CDE, 8CDF, 0CE*, 4CFF$

*Dxy: $0DD*, 0DE*, 0DFF$

*Exy: $0EE*, 0EFF$

*Fxy: $4FFF$

So you get a total of
$$(4+8+8+8+8+4)+(4+4+8+8+8+4)+(8+4)+4=92$$
unless I (still) made a mistake. But since this solution now agrees with the $92$ stated on the original problem statement question, I trust it might (finally) be correct now. Thanks to TonyK for spotting the one I had missed! My first attempt was way lower, so you really have to be very systematic to get this even close to correct.
Originally I had a higher count, namely $104$ (would be $108$ by now with my other fixes), but that's because I'd assumed $BCF$ to be collinear so I had $8ABC$ and $8BBC$. Jyrki pointed out in a comment that it doesn't look like that in your original post, even though it's close.
The same approach can be applied to other, similar tasks, as demonstrated in this post.

A: Here's a solution that only requires specifying the sets of collinear points of the diagram as input to a computer program. It's similar to triangle counting with an adjacency matrix (using the trace of the cube of the adjacency matrix), but it uses an edge adjacency matrix, not a vertex adjacency matrix, and it accounts for the fact that collinear edges cannot be part of the same triangle.
Let $V$ be the set of vertices in the diagram $D$. Define the set of edges of $D$ as the ordered pairs of vertices that are connected, just as usual for a directed graph. For an undirected graph, let both $(v,w)$ and $(w,v)$ be edges if $v$ and $w$ are adjacent.
Now for the new part. (The code below will do this, given as input just the "lines" of $D$, which are much easier to list by hand than the edges.)
Define an adjacency matrix $M$ for the edges of $D$. Consider the edge $(v,w)$ to be adjacent to $(v',w')$ if $w=v'$ and the edges are not collinear. In other words, the edges, if followed one after the other, form a "bent angle" in $D$. Note that an edge is not adjacent to itself by this definition.
Now consider $M^3$. Its $(i,j)$ entry equals the number of 4-edge sequences $e_i, e_2, e_3, e_j$ where a non-straight angle is formed from $e_i$ and $e_2$, from $e_2$ and $e_3$, and from $e_3$ and $e_j$. If $j=i$, this is a non-degenerate triangle.
Each non-degenerate triangle will be counted six times: once for each starting edge and once for each orientation (clockwise or counter-clockwise). So the number of triangles is $\dfrac{tr(M)}{6}$.
Here is Mathematica code for this example. I've used MvG's labeling of the vertices. There are 204 edges in the diagram, but only 28 lines, so the data entry and manual requirements aren't bad. To find the number of triangles in any diagram, all that needs to be modified is the list of lines.
lines={
{"A1","B2","B4","C2","C4","D2","D4"},{"A1","B1","B3","C1","C3","D1","D3"},
{"A1","E2","E4","F2","F4"},{"A1","E1","E3","F1","F3"},
{"D3","F2","F3"},{"D4","F3","F4"},{"B3","B4","E3"},{"B2","B3","E2"},
{"D2","F1","F2"},{"D1","F1","F4"},{"B1","B4","E4"},{"B1","B2","E1"},
{"C4","F3"},{"B3","F3"},{"C3","F3"},{"B4","F3"},
{"B3","F2"},{"C2","F2"},{"C3","F2"},{"B2","F2"},
{"B4","F4"},{"C1","F4"},{"B2","F1"},{"C1","F1"},
{"C4","F4"},{"B1","F4"},{"C2","F1"},{"B1","F1"}
};

isedge[p_]:=Max[Map[Length,Map[Intersection[p,#]&,lines]]]==2;

edgeset= Select[Tuples[{Union[Flatten[lines]],Union[Flatten[lines]]}],isedge[#]&];

makesangle[e1_,e2_]:=
Length[Intersection[e1,e2]]==1&&
isedge[e1]&&isedge[e2]&&e1[[2]]==e2[[1]]&&
Max[Map[Length,Map[Intersection[Union[e1,e2],#]&,lines]]]<=2;

adjacentEdgePairs=Select[Tuples[{edgeset,edgeset}],makesangle[#[[1]],#[[2]]]&];

edgeadjacencymatrix=
Map[{Position[edgeset,#[[1]]][[1]][[1]],
Position[edgeset,#[[2]]][[1]][[1]]}->1& ,adjacentEdgePairs];

m=SparseArray[edgeadjacencymatrix,{Length[edgeset],Length[edgeset]}];
Tr[m.m.m]/6

The result is 92, as expected.


text:
Q: Magento2 change Tax to VAT I am trying to change Tax to say VAT across the site. I have tried to change the en_US.csv file located in i18n in my theme, but with no result. Is this changed on database level, and if so, where?

A: Magento ver. 2.1.9
go to here: / vendor / magento / module-tax / view / frontend / layout / checkout_cart_index.xml
find and replace Tax to VAT
and
/ vendor / magento / module-tax / view / frontend / layout / checkout_index_index.xml

A: You are in the right place, but presumably you need to use:
en_GB.csv

if your store is in the UK.

A: Perfect
Thank you
For Australian GST,  file name needs to be added en_AU.csv
add line
"Tax", "GST"

A: /public_html/vendor/magento/module-tax/i18n
in folder create file en_GB.csv and write
Tax   VAT


text:
Q: Bringing an oscilloscope through the airport My university loaned us some oscilloscopes (Picoscope 2206B) to use in our free time. In a couple days I have to travel to my hometown for the holidays by plane. To make the most of my free time, I want to take the oscilloscope with me, meaning that I will have to carry it on the flight.

*

*Does it make more sense to put it in my bag, my carry-on baggage or my checked baggage?

*Is there anything I have to look out for?

*Will it create any problems when passing through security?

*Are there any chances that its functionality may be affected by X-rays?

I am aware that the question is rather silly and possibly even off-topic, but the oscilloscope is not mine and the last thing I want is to damage it.

A:
Does it make more sense to put it in my bag, my carry-on baggage or my checked baggage?

It's quite small (13 cm x 10.5 cm), so you can put it anywhere you want. However...

Is there anything I have to look out for?

Will it create any problems when passing through security?

When your bag(s) pass through x-ray the officers may notice it (especially if it has probes with it) so they may want you to open the bag and show the product and even explain its purpose. If you have a laptop I personally recommend you to keep the scope and its related parts in your laptop bag so that the officers think that those are part of your laptop and may ignore it during x-ray checks. Some officers are quite sensitive to some tools such as screw drivers. So, a small chance but the officers may treat the scope's probes as screwdrivers because of their shape :)

Are there any chances that its functionality may be affected by X-rays?

Nope. At least, I don't think so. I took a Fluke battery-operated handheld scope and a Fluke battery-operated handheld power analyser with me to the airplane twice in the same day. Nothing happened.


text:
Q: Why was B-4 disassembled? In the new Star Trek: Picard series, we see a disassembled B-4 kept in storage at the Daystrom Institute in Okinawa.
The last time he was seen on-screen was on Star Trek: Nemesis, when he was depicted as an android with limited capabilities if compared to the more his more "advanced brothers" Data and Lore, but nonetheless it was certainly a life-form, even if one with a limited intelligence.
And the reasoning behind Data's defense and his right to live in The measure of a man could certainly apply also for the less intelligent B-4, in the end.
Why was he disassembled and stored away like an "item" instead of being regarded as a life-form and consequently with his right to live (despite his status) recognized and protected?
He is told to be not like Data at all, but this seems to be a rather feeble reason to deny him the right to live, and doesn't seem like something that some of the more idealistic and humanist characters in the Star Trek universe could easily look-upon, especially Picard himself.
Are there some other reasons of his current state that maybe I have missed?

A: ** WARNING: SPOILERS for Star Trek: Picard Ahead**
The reason given in-universe was ALL positronic-type developments had to cease and any androids/robots, ie Synths, disassembled after the "attack on Mars", by the order of Federation council.

Since it was initially thought to be a programming error in the synths, the Federation Council placed a ban on synthetic lifeforms. Androids such as B-4 were dismantled, and the Daystrom Institute was restricted to "theoretical" studies on synthetics.

-- Memory Alpha
The decision was not well liked, as that also meant Riker/Troi's son cannot be saved due to the ban on positronic devices.

With all active positronic matrixes shut down, people who would contract mendaxic neurosclerosis, such as Thaddeus Troi-Riker, would eventually die from the illness without treatment

-- Memory Alpha


text:
Q: How to execute command on button in WPF? I need to have a button in each ListViewItem. I've created the Button in DataTemplate, bound the command and it doesn't get executed when I press the button. It just doesn't being called.
I was referring to different tutorials and questions like
WPF Button doesn't execute Command or How to bind WPF button to a command in ViewModelBase? and created a RelayCommand class, which implements ICommand.
Actually, I need to call the action with the parameter, but I can't even get it to work without parameters, so I'm planning to get to it next. Everything else is bound perfectly and works like a charm.
View
<Page.Resources>
<CollectionViewSource x:Key='src'
              Source="{Binding TimesheetEntries}"
                      >
    <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="Date" />
    </CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Page.Resources>
<Page.DataContext>
    <ViewModels:TimesheetViewModel/>
</Page.DataContext>

<ListView
    x:Name="TimesheetEntriesListView"
    Margin="10"
    Grid.Row="1"
    Grid.ColumnSpan="2"
    ItemsSource="{Binding Source={StaticResource src}}"
    SelectedItem="{Binding SelectedEntry, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    >
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Height="30" Margin="3" IsEnabled="{Binding IsEditable}">
                <ComboBox
                    SelectedValuePath="Key" DisplayMemberPath="Value"
                    ItemsSource="{Binding EmploymentTypesDictionary, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    SelectedValue="{Binding SelectedEmployment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    Width="300"/>
                <TextBox
                    Text="{Binding Hours, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat=N2}"
                    Margin="5,0,0,0"
                    Height="Auto"
                    IsEnabled="{Binding HoursAvaliable}"
                    Width="70"/>
                <Button Margin="5,0,10,0"
                        Content="+"
                        Command="{Binding AddNewTimesheetEntryCommand}"
                        CommandParameter="{Binding Path=Name}"
                ></Button>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <StackPanel Margin="5,5,5,0" Orientation="Horizontal">
                        <TextBlock  FontSize="14" Text="{Binding Path=Name, StringFormat='{}{0:dd/MM/yyyy, dddd}'}"/>
                    </StackPanel>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ListView.GroupStyle>
</ListView>

ViewModel
class TimesheetViewModel : BaseViewModel
{
    public ICommand AddNewTimesheetEntryCommand
    {
        get
        {
            return _AddNewTimesheetEntryCommand ?? new RelayCommand(AddNewTimesheetEntry);
        }
    }

    private ICommand _AddNewTimesheetEntryCommand;

    public void AddNewTimesheetEntry(object parameter)
    {
        //Do stuff
    }

    public TimesheetViewModel()
    {

    }
}

RelayCommand
public class RelayCommand : ICommand
{

    private Action<object> mAction;

    public event EventHandler CanExecuteChanged = (sender, e) => { };

    public RelayCommand(Action<object> action)
    {
        mAction = action;
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        mAction(parameter);
    }
}

A: Your button need to have been different bind, beacuse inside the list-template you do not have access to global DataContext only to local. You need to use relative source to access global DataContext.
Command="{Binding Path=DataContext.AddNewTimesheetEntryCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"


text:
Q: Parse as a system generated array based from a session
Possible Duplicate:
forcing access to __PHP_Incomplete_Class object properties
Able to see a variable in print_r()'s output, but not sure how to access it in code

I would like to ask for some advice on how to parse a system generated array which I got from session.
when I do print_r($_SESSION); here's what I've got.
Array (
    [user] => __PHP_Incomplete_Class Object (
        [__PHP_Incomplete_Class_Name] => DEX_User
        [permissionID:DE_User:private] => 9
        [login:DE_User:private] => James.S
        [email:DE_User:private] => james.s@domain.com
        [firstName:DE_User:private] => James
        [lastName:DE_User:private] => Steal
        [title:DE_User:private] => Warehouse Man
        [manager:DE_User:private] => Manager's Name
        [workPhone:DE_User:private] => +1 (111) 111-1111
        [mobilePhone:DE_User:private] => +1 (222) 222-2222
        [homePhone:DE_User:private] => +1 (333) 333-3333
        [im:DE_User:private] =>
        [timeDelta:DE_User:private] => Asia/Hongkong
        [lastLogin:DE_User:private] => __PHP_Incomplete_Class Object (
            [__PHP_Incomplete_Class_Name] => GB_Date
            [valueStored:protected] => 13545544126666309821
            [mode:protected] => BASE
            [master:protected] =>
        )
        [description:DE_User:private] => Warehouse Engineer
        [isActive:DE_User:private] => __PHP_Incomplete_Class Object (
            [__PHP_Incomplete_Class_Name] => GB_Boolean
            [valueStored:protected] => 1
            [mode:protected] => BASE
            [master:protected] =>
        )
        [isTerminate:DE_User:private] => __PHP_Incomplete_Class Object (
            [__PHP_Incomplete_Class_Name] => GB_Boolean
            [valueStored:protected] =>
            [mode:protected] => BASE
            [master:protected] =>
        )
        [id:protected] => 231968
        [isModifyed:protected] =>
        [needInsert:protected] =>
        [isDeleted] =>
        [isRemoved] =>
    )
    [enter_password] => 2asas(qwqw
)

What I would like to achieve is to get 3 items from the array.
I want to get the data
login = James.S
firstName = James
lastName = Steal

Thanks a lot.

A: You can't.
Examine this piece of code:
[login:DE_User:private] => James.S
[firstName:DE_User:private] => James

The login and first name are private properties of a object, that is not accessible from the outside.


text:
Q: How do I set up Chat-API correctly? I have downloaded and installed PHP 7 and Composer.
I can use both but I don't really know what to do next.
I need PHP Protobuf and Curve25519 but I don't know how to install that.
Also, it says to do "composer require whatsapp/chat-api", but where do I have to do that when I need a .php file to write the program?


text:
Q: If Exists allowing a null value through I have a catch script that is meant to pick up when a sum comes out with a null value and insert a 0, which works fine on one query but not my current one, if I break down what code I am using
Declare @Period int = 5
SELECT A.MATTER_CODE,DATEPART(month,A.DATE_OPENED) As DateOpened,B.DEPTNAME,B.DEPTCODE
INTO #TmpPREVYTD
FROM MATTER A
LEFT JOIN DEPT_MASTER B on A.DEPT_CODE = B.DEPTCODE
WHERE A.date_opened between DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, -1, GETDATE())), 120) and
DATEADD(YEAR, DATEDIFF(YEAR, 0,DATEADD(YEAR, 0, GETDATE())), 120)
ORDER BY DATE_OPENED

This pushes out the data I require for the query in the correct year and month
SELECT COUNT(*) As 'Fin',Dateopened Into #TmpPFin FROM #TmpPREVYTD where DEPTCODE = 'FIN' GROUP BY
DATEOPENED

This counts every time a job relating to Finance is in the raw data.
SELECT SUM(FIN)As Fin INTO #PFIN FROM #TmpPFIN WHERE Dateopened Between 5 and @Period

This then sums up all the months which relate to the required set months, so in this example I just want it to count May only, which has nothing in it, thus why it is pushing a null value.
If EXISTS(Select Fin from #PFIN)
GOTO TmpITD
Else insert into #PFIN (Fin) Values( 0)
TmpITD:

Finally this is the catcher which should be finding the #PFin has a null value and inserting a 0, however what I think it is doing is going straight to TmpITD, as if I just run the insert statement it adds the 0.
so currently if I run the entire statement I keep getting a null value which means the report in the end comes out blank.
Am I missing something here as this exact same code works in other queries but not in this one, it would appear that perhaps it does exist somehow but with a null value, which has totally confused me.
EDIT: If I add something to the end of TmpITD it pushes that out so I know for sure now that the problem is the if Exists thinks it does exist when it is actually Null

A: If your final table #PFIN has rows then it exists even if the values in it are NULL.
A solution might be the following tweak to remove NULL rows and get a truly empty data set:
If EXISTS(Select Fin from #PFIN WHERE Fin IS NOT NULL)
GOTO TmpITD
Else insert into #PFIN (Fin) Values( 0)
TmpITD:

Alternatively as aggrigates can return 0 when you group a set of NULLS you may want to exclude 0 values too:
If EXISTS(Select Fin from #PFIN WHERE Fin <> 0)
GOTO TmpITD
Else insert into #PFIN (Fin) Values( 0)
TmpITD:


text:
Q: Average of compound value or compound of averages? Suppose I'm measuring the flow rate of a tube. I measure the time it takes to fill it twice. Each time, I also measure its final volume.
So what is the best approach to calculate the average flow? Calculating each flow and averaging them or averaging the measurements and then calculating the flow?
I'm sure I've read something about this while studying error propagation back in college, but I can't find a good resource on the topic. Any pointers are much appreciated!


text:
Q: Convert XDocument to string without added /r /n Hello I'm trying to find a way to convert my XDocument to a string so that I can send that back with an ajax call.
So I have a XDocument as following
   var xml = new XDocument(
            new XElement("Contract",
                new XAttribute("version", "1.0"),
                new XElement("child", "Hello World!")));

I'm able to convert this to a string doing the following
string i = xml.Document.ToString();

but but by doing this my xml document comes out as wrong since alof ot /r/n and alot of "/" get added overall. Is there a way to convert an XDocument to string without this added values?
The string I get
"<Contract version=\"1.0\">\r\n  <child>Hello World!</child>\r\n</Contract>"

A: This should do the trick:
string i = xml.Document.ToString(SaveOptions.DisableFormatting);


text:
Q: python json.dump creating duplicate keys I am working on a feature in my discord bot to store information in json files (the code for the discord bot is irrelevant for this problem). The problem I am having is that json.dump is creating duplicate keys in the json file, ignoring the previous one and adding another key with the new value.
class _ServerSettingsJsonType:
    def __init__(self) -> None:
        with open(settings_file, encoding=DEFAULT_ENCODING) as file__:
            self.profiles_dict: dict[str, dict] = json.load(file__)

    def __getitem__(self, name: str):
        return self.profiles_dict[name]

    def __setitem__(self, name: str, value: Any):
        self.profiles_dict[name] = value

    def dump(self, guild: nextcord.Guild):
        with open(settings_file, "w", encoding=DEFAULT_ENCODING) as file__:
            file__.truncate(0)
            json.dump(self.profiles_dict, fp=file__)

This was suppost to store the information in the file by editing the key as a three level dictionary. However, it created a new key after the previous key. Every time after that, however, it simply rewrote the previous key. For some reason json.dump doesn't see the previous key.
for example, if I have the dictionary {'a':{'b':{'c':'d'} and I wanted to edit the value of 'd', it would give me {'a':{'b':{'c':'d', 'c': 'new-d'}}} I am confused about why it does that


text:
Q: Nvidia GPU not detected in system I'm trying to install drivers for the Nvidia GPU built into my laptop. I'm running Ubuntu 18.04 and the gpu is a Geforce GTX 950M. Nothing I do can get the GPU to show up as even installed in the laptop.
ubuntu-drivers devices displays nothing, lscpi has no mention of Nvidia or an installed card. glxinfo also doesn't show anything about Nvidia, it says my OpenGL vendor is Intel. When I try to install the drivers manually from the runfile I downloaded from Nvidia, it says that no compatible GPU was detected.
In my BIOS, I have secure boot disabled, and there's no setting for me to enable/disable a dedicated GPU (so I assume that it's enabled by default). Despite all this, I'm unable to find my GPU. Installing the drivers from aptitude doesn't change any of this behavior, and the Nvidia Settings application doesn't show a GPU installed either.
Any help is appreciated, I'm very confused.
Edit: My full config is:

*

*Acer Aspire V5-591G-56AS

*

*Intel i5-6300HQ @ 2.3 Ghz

*16 GB DDR3 RAM

*NVidia GTX 950M

*128 GB M.2 SSD

*1TB HDD

*Ubuntu 18.04

*

*Kernel 4.15.0-46-generic

*i3 Window Manager

Edit 2: Something I just remembered that might be relevant. About a year ago, I accidentally sent 9 volts through a USB port, which shorted something in the port (confirmed with a multimeter). Ever since, the USB port is constantly 'active' and drains my battery regardless of sleep state, so I keep my laptop plugged in all the time. I can't think of any other reason why my GPU wouldn't be showing up, but I also don't think the USB port/controller and the GPU are directly connected, so I'm not sure why it would have any effect.
Edit 3: Contents of /var/log/gpu-manager.log

A: I try to install from nvidia site , but it is unsuccessful.
Please try
https://launchpad.net/~graphics-drivers/+archive/ubuntu/ppa
Nvidia Driver Version 418

A: I was facing problem where Ubuntu (20.04.1) was not able to detect my NVIDIA graphics (RTX2060).
I checked the command nvidia-smi and it showed that it cannot communicate with the NVIDIA drivers.
I solved it using following commands (Nvidia driver already should be installed sudo apt install nvidia-driver-455 or from software & update - Additional driver section )
prime-select query
sudo prime-select intel
sudo prime-select nvidia

Then I installed CUDA using sudo apt install nvidia-cuda-toolkit. Finally reboot.


text:
Q: What alternative to C++ vector when it comes to fast deletion? vector is the first choice in many situations because random access is O(1), as there are not many containers that are fast enough, or at least O(log(n)).
My issue with vector being that vector<>::erase() is O(n), map<>::erase() is faster and is a better container.
An alternative would be to use an object pool, but it is not a standard container, and implementations might vary depending on use, so I'm not very keen on using something I don't really understand or know a lot about.
It seems map is a very good alternative to vector<> when there is often-occurring deletions, but I wanted to know if there are better alternatives to it.
So is there a container that is both fast with random access and deletion?
Is there an usual way to make an object pool?

A:
What alternative to C++ vector when it comes to fast deletion?

Erasing the last element of a vector (i.e. pop operation) has constant complexity, so if you don't need to keep your sequence ordered, then an efficient solution is to swap the target element with the last one, and pop it.
A linked list has constant complexity deletion that maintains the order of the sequence, but indexed lookup is linear (i.e not random access).

The (unordered) map sure has both asymptotically efficient lookup and erase, but you won't get the same behaviour as a vector would have. If you create an index -> element map, and remove element from index i, then there will be a gap between i - 1 and i + 1, while the vector would shift the elements at indices greater than i left.
The indexable skip list has logarithmic (on average; worst case is linear) lookup and deletion. However, there is no implementation of it in the standard library.


text:
Q: Найти длину каждого слова, количество цифр в каждом слове, количество гласных букв в каждом слове Помогите пожалуйста!
Ввести текстовую строку с помощью функции gets, слова в строке отделяются пробелами
В каждом слове определить:
1.Длину слова
2.Количество цифр
3. Количество гласных прописных букв
Результат вывести в виде:
Input text:
 MAma2001     Papa1234056789
 Text: MAma2001     Papa1234056789

                slovo                len_slova        kol_cifr        kol_glas_bukv

          MAma200                    8                     4                      1

Papa1234056789                   14                   10                     2

A: Вот пример кода
#include <stdio.h>
#include <stdlib.h>

int main()
{

char w[256], *p;
int c;
int lw=1, ld=0, lg=0;
    p = w;
    printf("input string: ");
    c = getchar();
    *p++ = c;
    printf("slovo\t\t\tlen_slova\tkol_cifr\tkol_glas_bukv\n",w,lw,ld,lg);
    while (c != '\n') {
        c = getchar();
        if (c ==' ' || c=='\n' ) {
            *p = '\0'; /* add null terminator */
            if (lw<15){
            printf("%s\t\t%d\t\t%d\t\t%d\n",w,lw,ld,lg);
            }
            else{
            printf("%s\t%d\t\t%d\t\t%d\n",w,lw,ld,lg);
            }
            p = w;
            ld=0;
            lg=0;
            lw=0;
        }
        else {
            lw++;
            if (c>='0' && c<='9'){ld++;}
            if (c=='a' || c=='e' || c=='u' || c=='i' || c=='o'){lg++;}
            if (c=='A' || c=='E' || c=='U' || c=='I' || c=='O'){lg++;}
            *p++ = c;
        }

    }

return 0;
}

Вывод
input string: MAma2001 Papa1234056789
slovo                   len_slova       kol_cifr        kol_glas_bukv
MAma2001                8               4               2
Papa1234056789          14              10              2


text:
Q: How do I ensure children of a subprocess don't get SIGINT in Python (on Linux)? I'm trying to use a custom job pool (using multiprocessing.Process), and it works nicely, except SIGINT gets passed on from the parent process all the way to the children of the pool workers, Chrome instances in this case. I used signal.signal(signal.SIGINT, signal.SIG_IGN) in the pool workers, which seems to keep them from getting (or at least responding to) the SIGINT, but I'm using third-party code (Selenium) which creates subprocesses that get the SIGINT and stop because of it. I want only the parent process to receive and handle the SIGINT. How do I do this?
My inclination would be to give the pool workers /dev/null as STDIN, so it would give that to its children rather than the terminal, which, if I understand correctly, will keep it from receiving SIGINT from Ctrl+C. However, it seems that multiprocessing.Process already does that, though presumably too late (after the process is created; using a double-fork should get past this). Is there a good way to do that (or anything else that blocks SIGINT) through multiprocessing, or do I need a different solution to work around that? Maybe there's an easy way to use multiprocessing.Queue with Popen(), so I can use that instead?
To be clear, I still need to be able to log to the console (indirectly through the parent process is fine, maybe better even).


text:
Q: Why my last named group catches everything else? So, I have these data that come from SMSes exported to text that I want to be able to extract and create a better report than plain text, so I have a file full of these lines:
1.   01 mag 2015   10:55:08 AM   stringOne  PersonName                       +999999999999  MultilineText

Let me break it down:

*

*"1." is like a line number

*"01 mag 2015   10:55:08 AM" is the date

*"stringOne" is a string that can be either "stringOne" or "stringTwo"

*"PersonName" is a string that represents the name of the person

*"+999999999999" is the phone number

*"MultilineText" is a multiline string that can contain anything

I am using Regex.Matches to get the MatchCollection to iterate on.
I can get everything to work if I don't include the last group, and I really need to get these data, so here is the regular expression I am using that successfully retrieves the data without the last group:
@"(?<lineNumber>\d{1,3}\.   )(?<date>\d{2} \w{3} \d{4}   \d{2}\:\d{2}\:\d{2} (AM|PM))\s*(stringOne|stringTwo)\s*(?<from>\w+)\s*(?<celnumber>\+?\d+)"

I tried to add the following part to that regular expression:
(?<text>.*)

However, I don't correctly get the multiline text, I do get some data but when it goes multiline it is cut out.
Then, I have tried to use this instead:
(?<text>(.|\n)*)

I only get one line as result.
So, how can I get that last "piece" of information as a multiline text?

A: (?<lineNumber>\d{1,3}\.   )(?<date>\d{2} \w{3} \d{4}   \d{2}\:\d{2}\:\d{2} (AM|PM))\s*(stringOne|stringTwo)\s*(?<from>\w+)\s*(?<celnumber>\+?\d+)\s*(?<text>[\s\S]*?)(?=\n[ ]*\d+\.|$)

You can try this.
(?<text>[\s\S]*?)(?=\n[ ]*\d+\.|$) will catpure multiline text untill it finds a newline which has a number and ..The lookahead checks for it but doesnt consume it

A: You are missing the singleline operator that will make . match newline symbols, and the multiline option (?m) that will enable us to control start of a line. I'd also recommend to replace literal spaces with \s since it will help with eventual future debugging:
Here is a regex with the inline (?s) and (?m) options:
(?sm)(?<lineNumber>\d{1,3}\.\s+)(?<date>\d{2}\s+\w{3}\s+\d{4}\s+\d{2}\:\d{2}\:\d{2}\s*(AM|PM))\s*(stringOne|stringTwo)\s*(?<from>\w+)\s*(?<celnumber>\+?\d+)(?<text>.*?)(?=\z|^\s*\d+\.)

Or inside a program (RegexOptions.Singleline and RegexOptions.Multiline):
var rx = new Regex(@"(?<lineNumber>\d{1,3}\.\s+)(?<date>\d{2}\s+\w{3}\s+\d{4}\s+\d{2}\:\d{2}\:\d{2}\s*(AM|PM))\s*(stringOne|stringTwo)\s*(?<from>\w+)\s*(?<celnumber>\+?\d+)(?<text>.*?)(?=\z|^\s*\d+\.)", RegexOptions.Singleline|RegexOptions.Multiline);

See demo
You might wonder what \z does: it matches the end of the string irrespective of the multiline flag that modifies the meaning of ^ and $ anchors.
Please check the C# code:
var rx = new Regex(@"(?<lineNumber>\d{1,3}\.\s+)(?<date>\d{2}\s+\w{3}\s+\d{4}\s+\d{2}\:\d{2}\:\d{2}\s*(AM|PM))\s*(stringOne|stringTwo)\s*(?<from>\w+)\s*(?<celnumber>\+?\d+)(?<text>.*?)(?=\z|^\s*\d+\.)", RegexOptions.Singleline | RegexOptions.Multiline);
var strr = "1.   01 mag 2015   10:55:08 AM   stringOne  PersonName                       +999999999999  Multiline\r\nText\r\n    2.   01 mag 2015   10:55:08 AM   stringOne  PersonName                       +222229999  Multiline\r\nText";
var mth = rx.Matches(strr).Cast<Match>().ToList();

Output:


text:
Q: JavaScript this issue with SetInterval I'm trying to call a portion of code in a class over and over again at every second,
update() {
    for (let entity of this.entities) {
      if (entity instanceof Alien) {
        entity.y += 1;
        renderAliens(entity, this.context);
      }
    }
  }

this is the code I am trying to call inside of my Game object using
setInterval(newGame.update(),1000), however when I attempt to do this it errors saying that Uncaught TypeError: this.entities is undefined, I understand that this is due to a scope issue with this and setinterval, yet I am unsure how to use bind to solve the issue
edit: here's the whole piece of relevant code

class Game {
  constructor() {
    this.gameOver = false;
    this.entities = [];
    this.context = document.getElementById("canvas").getContext("2d");
  }
  start() {
    this.entities.push(new Ship(0, 400));
    this.entities.push(new Alien(1, 0));
    this.entities.push(new Alien(20, 0));
    this.entities.push(new Alien(40, 0));
  }
  render() {
    for (let entity of this.entities) {
      if (entity instanceof Alien) {
        renderAliens(entity, this.context);
      } else if (entity instanceof Ship) {
        renderShip(entity, this.context);
      }
    }
  }
  update() {
    for (let entity of this.entities) {
      if (entity instanceof Alien) {
        entity.y += 20;
        renderAliens(entity, this.context);
      }
    }
  }

  endGame() {}
}

const newGame = new Game();
newGame.start();
newGame.render();
let t = setInterval(newGame.update, 1000);

A: You have two options:

*

*use .bind(). This binds this to the newGame instance
setInterval(newGame.update.bind(newGame), 1000);

*define a callback function:
setInterval(function(){
  newGame.update();
}, 1000);

A: Just write the interval like:
const intervalRef = setInterval(() => { newGame.update() }, 1000);

A: Why don't you just declare the interval in your constructor? This way, you will avoid any context issues.
constructor() {
    this.gameOver = false;
    this.entities = [];
    this.context = document.getElementById("canvas").getContext("2d");
    setInterval(this.update.bind(this), 1000); // Here
  }


text:
Q: How do I push the footer to the bottom of the page? I don't have any space under my footer in the desktop as well as the mobile versions with the exception of the iPhone X and the iPad. I've messed around with media, calc(100vh - height) overflow, position etc., but nothing seems to be working. I read one suggestion that was to put all the content into a container and then set the footer to position: absolute, but I'm not sure how that will affect my grid.
body {
  line-height: 1;
  background-color: #f3f3f3;
}

.services-wrapper {
  display: grid;
  width: auto;
  grid-template-rows: auto 3fr;
  grid-row-gap: 20px;
  height: calc(100vh - 30px);
}

.services-grid {
  padding-bottom: 30px;
  overflow: auto;
}

.services-grid>div {
  background-color: white;
  vertical-align: middle;
  padding: 25px;
  margin: 30px;
}

footer {
  position: relative;
  padding-top: 5px;
  margin-top: -30px;
  background-color: white;
  height: 30px;
  width: 100%;
  overflow: hidden;
  clear: both;
}

A: I think you are looking for something like this:

    html,  div, header, nav, section,
    time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    outline:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
    }

    footer,header,nav,section {
    display:block;
    }

    .services-wrapper {
    display: grid;
    width: auto;
    grid-template-rows: auto 3fr;
    grid-row-gap: 20px;
    height: calc(100vh - 30px);
    }

    .services-grid {
    padding-bottom: 30px;
    overflow: auto;
    }

    .services-grid > div {
    background-color: white;
    vertical-align: middle;
    padding: 25px;
    margin: 30px;
    }

    body{
        background-color:rgb(39, 39, 39);
          }
    .footer {
       position: fixed;
       left: 0;
       bottom: 0;
       width: 100%;
       background-color: black;
       color: white;
       text-align: center;
       padding: 17px;
    }
    a{
      padding: 20px;
      font-size: 18px;
      color:white;
      text-decoration:none;
    }

        Terms

       Privacy policy
       About
       Contact Us

Let me know if it helps you.

A: You can try setting the body to be flex.
Also it helps setting the html and body to have a min height of the window height.

html, body {
  min-height: 100vh;
}

body {
  display: flex;
  flex-direction: column;
}

footer {
  margin-top: auto;
}

A: body {
    position: relative;
    min-height: 100vh;
}

main {
    padding-bottom: 2.5rem;/* Footer height */
}

footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 2.5rem;/* Footer height */
}

or use a grid:

.grid-container {
    display: grid;
    grid-template-areas:
    'header'
    'main'
    'footer';
    grid-template-columns: 1fr;
    grid-template-rows: 5rem 1fr 5rem;
    height: 100%;
}


text:
Q: R: How to access the elements of a list in a loop I have two files. One file contains information about Genes. It looks like this.
Query|       Gene |  Desc
APECO1_1380 | fldA   | flavodoxin FldA
APECO1_2545 | fpr    |ferredoxin-NADP reductase
APECO1_3632  |fldB   | flavodoxin FldB
APECO1_1465  |fepA   | ferrienterobactin receptor
APECO1_4396 | cirA   | colicin I receptor

The second files contains a list of GeneCodes.
APECO1_1380
APECO1_2545
APECO1_3632

I'm trying to extract Gene information from file 1 for the Gene codes in File 2. Below is the code I'm using.
#Files with gene data for GeneCodes(File 1)
dataT = read.csv("D://SBMLexploration/Genes/genenames.csv",header = TRUE)

#Has the second type of files (files with the GeneCode) - File 2

fileList = list.files("D://SBMLexploration/Genes/Test1")

df = data.frame(MonkCode = character(), GeneName = character(),
                Description = character(), stringsAsFactors = F)

for(i in 1:length(fileList))
{
  currentGenes = read.csv(fileList[i],header = T)

  for(j in 1:nrow(currentGenes))
  {
    curentRow = subset(dataT,dataT$Query == currentGenes[j,1])

    df<-rbind(df,data.frame(MonkCode = currentRow$Query,
                            GeneName = currentRow$Gene,
                            Description = currentRow$Desc))
  }
  write.table(df,fileName,sep=",",row.names = F)
  df = NULL

}

My problem is when I provide a GenCode as currentGenes[j,1] the query returns 0 rows. But when I give the Code as a string (with in APECO1_1465) it returns the record. The issue is with the way I'm referring to the list. Can someone please help me with this?

A: Simply transform currentGenes[j,1] into a string using as.character().
I.e.as.character(currentGenes[j,1])

A: R's syntax is not it's strong point and can lead to lots of frustrating errors like the one you describe. At the risk of starting a flamewar, let me suggest the dplyr library and show an alternative, dplyr-based solution below.
library(dplyr)

#load your reference data and register your gene files
dataT = read.csv("D://SBMLexploration/Genes/genenames.csv",header = TRUE)
fileList = list.files("D://SBMLexploration/Genes/Test1")

# load genes from a file and output refencedata
processdata <- function(ref_df, filename){

  genes = read.csv(filename,header = T, col.names = c("genes"))

  refdf %>%
    filter(Query %in% genes$genes) %>%
    mutate(MonkCode = Query,
           GeneName = Gene,
           Description = Desc) %>%
    select(MonkCode,GeneName,Description) %>%
    write.table(file=paste0(filename,"_hits.txt"))
}

#apply your function to each file
Map(processdata,fileList)


text:
Q: I used the correct code but still this returning false SIGNUP.PHP/HTML
<?php
    require_once("connections/db.php");

    $error = array();
    if($user->is_loggedin())
    {
        $user->redirect('index.php');
    }

    if(isset($_POST['signup-btn']))
    {
      $username = $_POST['signup-username'];
      $password = $_POST['signup-password'];
      $email = $_POST['signup-email'];

      if($user='')
      {
          $error[] = "Please enter a username";
      }
      else if($pass='')
      {
          $error[] = "Please enter a password";
      }
      else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
      {
          $error[] = "Please enter a valid email address";
      }
      else
   {
      try
      {
            if($user->register($username, $password, $email))
            {
                echo "registered";
            }
     }
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  }
    }
   ?>

class.user.php
<?php
class USER{

    private $db;

    function __construct($db_con)
    {
        $this->db = $db_con;
    }

    public function register($username,$password,$email)
    {
        try
        {
          $protected_password = password_hash($upass, PASSWORD_DEFAULT);
          $stmt = $this->db->prepare("INSERT INTO users(username,password,email)
          VALUES(:username, :password, :email)");

           $stmt->bindparam(":username", $username);
           $stmt->bindparam(":password", $protected_password);
           $stmt->bindparam(":email", $email);
           $stmt->execute();

           return $stmt;
        }

        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

    public function is_loggedin()
    {
        if (isset($_SESSION['user_session']))
        {
            return true;
        }
    }

    public function redirect($url)
    {
        header("Location: $url");
    }

    public function logout()
    {
        session_destroy();
        unset($_SESSION['user_session']);
        return true;
    }
}

?>

db.php
<?php
session_start();

$connection = parse_ini_file('config.ini');

try{
    $db_con = new PDO("mysql:host={$connection['host']}; dbname={$connection['dbname']}", $connection['username'], $connection['password']);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e){
    echo $e->getMessage();
}

include_once 'class.user.php';
$user = new USER($db_con);
?>

I keep receiving the error Fatal error: Call to a member function register() on string in C:\xampp\we\signup.php on line 32
I'm completely new to PDO's.  and I can't see why this is not working.
I tried changing the code up as much as I could, but this error doesn't change.  I'm sure it's a simple stupid problem i'm overlooking as well.

A: We start out setting $username from your form
$username = $_POST['signup-username'];

Then I assume an equality check was meant to happen on this variable ($username == ''?) but instead $user is set to an empty string.
if($user='')
{
    $error[] = "Please enter a username";
}

Afterwards, $user->register() is called, and $user is still a string instead of an instance of your class USER.
Be careful that you dont put in variable assignments where you meant to put in equality checks elsewhere! I do it all the time.
if($user='')
{
    $error[] = "Please enter a username";
}
else if($pass='') // should this be $password == ''?
{
    $error[] = "Please enter a password";
}


text:
Q: How to reproduce java.net.SocketException: Broken pipe I need to right test that ensures that i fixed java.net.SocketException: Broken pipe. How to reproduce it if I have socket in java code?

A: Assuming that you want to reproduce it on a unit test, you should use Mockito framework to reproduce this exception.
doThrow(new SocketException()).when(mockedObject.methodReturningVoid(...))

You can find more information  here

A: If you dont want to deal with unit tests though thats an awesome answer and I wasnt even aware of Mockito - simple solution though drastic is stop the application you're connecting to or temporarily disable your network device from your dev box.  I've used both.


text:
Q: XSLT transform with no output I have the following XML file and want to create a XSLT to transform into table with headings, such as.
Item No.  Part Number    Description                Material     etc.
1         0040-84339     Rotor, Wafer Head MK1
2         0020-93948     Insulator, Echuck Contact

Here is the XML. I have tried some XSLT creation tools, but with very little luck in creating the required output. Can someone define the basic XSLT structure to format this XML as needed.
<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <transactions>
        <transaction date="1485976336" type="export_bom_spreadsheet" vaultname="PDM_Pro">
            <bom document_id="2113" document_path="\EPDM Demo Files\9011-01765.SLDDRW" id="2133"
                name="9011-01765.SLDDRW: Bill of Materials1" path="\EPDM Demo Files\" type="3">
                <bomheader>
                    <bomcol alignment="center" col_no="0" name="ITEM NO."/>
                    <bomcol alignment="center" col_no="1" name="PART NUMBER"/>
                    <bomcol alignment="center" col_no="2" name="DESCRIPTION"/>
                    <bomcol alignment="center" col_no="3" name="MATERIAL"/>
                    <bomcol alignment="center" col_no="4" name="STOCK SIZE"/>
                    <bomcol alignment="center" col_no="5" name="WEIGHT"/>
                    <bomcol alignment="center" col_no="6" name="VENDOR"/>
                    <bomcol alignment="center" col_no="7" name="Default/QTY."/>
                </bomheader>
                <bomrow document_id="2120" path="\EPDM Demo Files\0040-84339.sldasm" row_no="0">
                    <bomcell col_no="0" value="1"/>
                    <bomcell col_no="1" value="0040-84339"/>
                    <bomcell col_no="2" value="ROTOR, WAFER HEAD MK1"/>
                    <bomcell col_no="3" value=""/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value=""/>
                    <bomcell col_no="7" value="1"/>
                </bomrow>
                <bomrow document_id="2126" path="\EPDM Demo Files\0020-53948.sldprt" row_no="1">
                    <bomcell col_no="0" value="2"/>
                    <bomcell col_no="1" value="0020-53948"/>
                    <bomcell col_no="2" value="INSULATOR, ECHUCK CONTACT"/>
                    <bomcell col_no="3" value="PEEK"/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value=""/>
                    <bomcell col_no="7" value="2"/>
                </bomrow>
                <bomrow document_id="2125" path="\EPDM Demo Files\0020-53949.sldprt" row_no="2">
                    <bomcell col_no="0" value="3"/>
                    <bomcell col_no="1" value="0020-53949"/>
                    <bomcell col_no="2" value="HIGH VOLTAGE CONTACT"/>
                    <bomcell col_no="3" value=""/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value=""/>
                    <bomcell col_no="7" value="2"/>
                </bomrow>
                <bomrow document_id="2115" path="\EPDM Demo Files\9010-01765-1.sldprt" row_no="3">
                    <bomcell col_no="0" value="4"/>
                    <bomcell col_no="1" value="3700-04467"/>
                    <bomcell col_no="2" value="O-RING,  BUNA-N 2-011 70 DURO"/>
                    <bomcell col_no="3" value="-"/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value="PARKER SEALS"/>
                    <bomcell col_no="7" value="2"/>
                </bomrow>
                <bomrow document_id="2119" path="\EPDM Demo Files\3690-05375.sldprt" row_no="4">
                    <bomcell col_no="0" value="5"/>
                    <bomcell col_no="1" value="3690-05375"/>
                    <bomcell col_no="2" value="SET SCR CUP PT STEEL,  M2.5 X 5"/>
                    <bomcell col_no="3" value="STEEL"/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value="STOCK DRIVE"/>
                    <bomcell col_no="7" value="2"/>
                </bomrow>
                <bomrow document_id="2117" path="\EPDM Demo Files\3700-02453.sldprt" row_no="5">
                    <bomcell col_no="0" value="6"/>
                    <bomcell col_no="1" value="801655-150"/>
                    <bomcell col_no="2" value="O-RING, BUNA N 2-150 N674-70"/>
                    <bomcell col_no="3" value=""/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value=""/>
                    <bomcell col_no="7" value="1"/>
                </bomrow>
                <bomrow document_id="2118" path="\EPDM Demo Files\3700-01044.sldprt" row_no="6">
                    <bomcell col_no="0" value="7"/>
                    <bomcell col_no="1" value="3700-01044"/>
                    <bomcell col_no="2" value="O-RING 2-224 BUNA-N"/>
                    <bomcell col_no="3" value="-"/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value="Parker Seals"/>
                    <bomcell col_no="7" value="2"/>
                </bomrow>
                <bomrow document_id="2116" path="\EPDM Demo Files\3700-98003.sldprt" row_no="7">
                    <bomcell col_no="0" value="8"/>
                    <bomcell col_no="1" value="3700-98003"/>
                    <bomcell col_no="2" value="O-RING, 2-011 BUNA-N"/>
                    <bomcell col_no="3" value="RUBBER"/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value="Parker Seals"/>
                    <bomcell col_no="7" value="1"/>
                </bomrow>
                <bomrow document_id="2127"
                    path="\EPDM Demo Files\Additional File Folder\0020-53947.sldprt" row_no="8">
                    <bomcell col_no="0" value="9"/>
                    <bomcell col_no="1" value="0020-53947"/>
                    <bomcell col_no="2" value=""/>
                    <bomcell col_no="3" value=""/>
                    <bomcell col_no="4" value=""/>
                    <bomcell col_no="5" value=""/>
                    <bomcell col_no="6" value=""/>
                    <bomcell col_no="7" value="1"/>
                </bomrow>
            </bom>
        </transaction>
    </transactions>
</xml>

A: You could start with this, and then refine it as needed:
<xsl:template match="bom">

   <xsl:apply-templates/>

</xsl:template>

<xsl:template match="bomheader">

   <xsl:apply-templates/>

</xsl:template>

<xsl:template match="bomheader/bomcol">

   <xsl:value-of select="@value"/>

</xsl:template>

<xsl:template match="bomrow">

   <xsl:apply-templates/>

</xsl:template>

<xsl:template match="bomcell">

   <xsl:value-of select="@value"/>

</xsl:template>


text:
Q: How to convert a large string data array from file to np.array with float data type My task is to direct a potentially large set of elements for training a neural network. I am trying to use tf.data.experimental.CsvDataset and tf.data.experimental.make_csv_dataset but I keep getting stuck.
My dataset is a text file containing strings with numbers separated by ';'. This is how it looks:
14;14;14;55;55;20;20...33;34;34
20;20;20;15;15;15;26...10;10;10
....
10;10;10;30;30;35;35...23;23;23

Each line contains 2500 numbers, separated by each other. I tried to use this code
dataset = tf.data.experimental.CsvDataset(pathAsk,
                                          record_defaults=[tf.float32],
                                          field_delim=";",
                                          na_value='NA'
                                          )

for element in dataset.as_numpy_iterator():
  print(element)

But I get an error like there are more elements in the row than I specified in record_defaults. Also I try to use this:
dataset = tf.data.experimental.make_csv_dataset(pathAsk, batch_size=2, field_delim=';')
iterator = dataset.as_numpy_iterator()
print(dict(next(iterator)))

But I get error:
Cannot have duplicate column names.

My task is to use this dataset so that it can get into the input of a neural network built in a similar way:
inputs = keras.Input(shape=(2500), name="ask")
x = keras.layers.Embedding(1000, 64)
x = keras.layers.Dense(64, activation=keras.activations.relu)(inputs)
x = keras.layers.Dense(32, activation=keras.activations.relu)(x)
outputs = keras.layers.Dense(6, activation=keras.activations.relu)(x)

model = keras.Model(inputs, outputs)
model.compile("adam", "binary_crossentropy", metrics=["accuracy"])

A: It looks like I found the answer to my question.
I added an indication of the number of dimensions of the row in the record_defaults property.
datasetAsk = tf.data.experimental.CsvDataset(
    pathAsk,
    record_defaults = [tf.constant(0, dtype=tf.float32)] * 2500,
    header = False,
    field_delim = ";",
    )

As a result, the number of elements in a line corresponds to the number of data types dtype and the iteration operation passes without errors.


text:
Q: how to pass variable into conditional join in codeigniter? earlier sorry if my english bad
first i have variable like this
$data[code] = "xyz123";
$data[type] = "train";

and the query i write in model like this
$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table2.id = table1.id');
$this->db->select('table3', 'table3.id = table1.id AND table1.code LIKE $data[code] AND table1.type LIKE $data[type]');

But when i try, its not working and i think the syntax AND and LIKE i write is wrong to. Please anyone know the solution?
Thank you before.

A: I think you need to try this :
$this->db->select('table1.*,table2.*,table3.*');
$this->db->from('table1');
$this->db->join('table2', 'table2.id = table1.id');
$this->db->join('table3', 'table3.id = table1.id');
$this->db->like('table1.type', $data['type']);
$this->db->like('table1.code', $data['code']);

A: Try CI like function:
$this->db->like('type', $data['type']);
$this->db->like('code', $data['code']);

A: $data["code"] = "xyz123";
$data["type"] = "train";

$this->db->select('*');
$this->db->from('table1');
$this->db->join('table2', 'table2.id = table1.id');
$this->db->select('table3', 'table3.id = table1.id AND table1.code LIKE '.$data["code"].' AND table1.type LIKE '.$data["type"].'');


text:
Q: Combining reactive responses into one payload I am doing rest service that accepts 'id' and then uses it to do multiple calls to different reactor api's :
Mono<Response1> getResponse1(id)
Flux<Response2> getResponse2(id)
Flux<Response3> getResponse3(id)
Mono<Response4> getResponse4(id)
Flux<Response5> getResponse5(Response4) (this call uses response from 4th)
Mono<Response6> getResponse6(id)

and then I have to combine them into one huge payload and return it as a Single<>:
{
  fooInfo {
     response1 {}
     response2 {}
  },
  barInfo {
     barBar {
        response3 {}
     },
     barBarBar {
        response4 {},
        response5 {}
     }
  }
}

I have created Dto:
public class MyDto {

    @JsonProperty("fooInfo")
    private MyDto.FooInfo fooInfo;

    @JsonProperty("barInfo")
    private MyDto.BarInfo barInfo;

    public static class FooInfo {
          private Response1 response1;
          private Response2 response2;
    }

    public static class BarInfo {
          @JsonProperty("barBar")
          private BarInfo.BarBar barBar;

          @JsonProperty("barBarBar")
          private BarInfo.BarBarBar barBarBar;

          public static class BarBar {
               private Response3 response3;
               private Response4 response4;
          }

          public static class BarBarBar {
               private Response5 response5;
               private Response6 response6;
          }
    }
 }

I am getting all the responses and converting them into Observables(using RxJava2Adapter.monoToMaybe and then toObservable for mono and using RxJava2Adapter.fluxToObservable and .toList() and .toObservable() for flux) and then using Observable.zip to combine them
Observable<MyDto.FooInfo> fooInfo = Observable.zip(
       response1,
       response2,
          (o1, o2) -> new MyDto.FooInfo(o1, o2)
        );

Observable<MyDto.BarInfo> barInfo = Observable.zip (
       Observable.zip(
           response4,
           response5,
           (o1, o2) -> new MyDto.BarInfo.BarBar(o1, o2)
       ),
       Observable.zip(
           response5,
           response6,
           (o1, o2) -> new MyDto.BarInfo.BarBarBar(o1, o2)
       ),
       (o1, o2) -> new MyDto.BarInfo(o1, o2)
 );

and then one more zip to combine both:
Observable.zip(
          fooInfo,
          barInfo,
          (o1, o2) -> new MyDto(o1, o2)
);

and in the end I use .singleOrError to convert it to single and return as a response.
I'm new to rxjava and wanted to ask

*

*what is the best way to combine multiple reactor responses into Single and what should I change?

*If 5th api relies on response from 4th, should I be using : response4.flatMap(getResponse5()) or what is the best practice for chaining calls?


text:
Q: ¿Hacer este círculo específico en html/css?
He intentado haciéndolo en CSS así:
     .circle{
        background-color: white;
        width: 100px;
        height: 100px;
        border-radius: 50%;

    }

y me da un círculo completo pero sólo quiero que se vea la línea blanca ya que lo de dentro es de la imagen de fondo, en otros posts que he encontrado sólo dicen un círculo como el que he dicho antes

A: Para permitir ver el fondo tendrías que ponerle al
 del círculo un background-color: transparent y para el borde blanco del círculo tienes que darle estilos al borde, que es lo que estás redondeando con border-radius: 50%;.

.fondo {
  background-color: red;
  display: inline-block;
}

.circulo {
  background-color: transparent;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 3px solid white;
}


text:
Q: How to add string text and a variable in d3.js text attribute? I am trying to add a text field to a treemap I am creating in d3.js. I know in c++ you can do
string str = "again";
cout << "Hello World " + str << endl;

which would output
Hello World again

I am trying to do this is d3.js but I can seem to get it. Ive tried adding another text field but that doesn't work either.
This is what I currently have
cells.append("text")
              .attr("x", function(d) { return d.x0 +10 })
              .attr("y", function(d) { return d.y0 +27 })
              .style("font", "10px times")
              .text("Item count: " + function(d) {return d.data.itemCount})
              .attr("fill", "white")

which outputs
Item count: function(d) {return d.data.itemCount}

but I need it to output for instance,
Item count: 2042

Thanks for any help

A: Try this:
.text(function(d) { return "Item count: " + d.data.itemCount })

A: Try this one:
cells.append("text")
              .attr("x", function(d) { return d.x0 +10 })
              .attr("y", function(d) { return d.y0 +27 })
              .style("font", "10px times")
              .text("Item count: ")
              .append()
              .text(function(d) {return d.data.itemCount})
              .attr("fill", "white")


text:
Q: Eclipse RCP Product Export using Ant I am looking for a way to export the Eclipse RCP product using ant, I couldn't find a straight forward approach to achieve this (Of course after searching the web as well as our forum).
The link that I found that was more relevant to my question was "http://stackoverflow.com/questions/9098378/how-to-build-eclipse-rcp-application-from-product-with-ant-on-jenkins" but that doesn't say on usage of ant. Also there was a guide "http://www.vogella.com/articles/EclipsePDEBuild/article.html" but even after trying it out, I am not able succeed in usage of Ant ni exporting the Eclipse product.
Any help/pointers would be greatly appreciated.

A: You want the PDE build (which is ant based) as listed in http://www.vogella.com/articles/EclipsePDEBuild/article.html.  That's the right place to look, what was it not doing for your setup?
See also http://pweclipse.blogspot.com/2010/09/simple-rcp-product-build.html for an example of a basic RCP product build.  While it's ant based, you still have to use eclipse to run it:
eclipse/eclipse -application org.eclipse.ant.core.antRunner \
 -buildfile eclipse/plugins/org.eclipse.pde.build_3.6.0.v20100603/scripts/productBuild/productBuild.xml \
 -Dbuilder=/opt/local/rcp/builder  \
 -Dbase=/opt/local/rcp/base \
 -Dtimestamp=20100924-1100


text:
Q: Parametric Equation - need help I was wonder if anyone would be able to help me with this problem. I have done problems similar but the +3 is throwing me off in this problem. How would you make it into a rectangular equation?
equation

A: $$x=\sin t + 3 \implies \sin^2 t = (x-3)^2$$
$$y=4\cos^2t = 4(1-\sin^2 t) = 4(1-(x-3)^2)$$
Hopefully you can do the simplification.


text:
Q: C# COM Office Automation - RPC_E_SYS_CALL_FAILED I'm writing a C# program that acts as a PowerPoint 2007 plugin. On some machines, some calls to the PowerPoint object model throw a COMException with the message RPC_E_SYS_CALL_FAILED. I couldn't find any specific advice on what to do regarding this error, or how to avoid it. From Googling it looks like something to do with the message queue or Single-Threaded Apartments. Or am I way off?
Example of the error message is:

System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))
  at Microsoft.Office.Interop.PowerPoint._Presentation.get_FullName()

Unfortunately, the problem is occurring on a client's machine, so I have no easy way to debug it! Should I just retry the calls whenever I get this error?
Any advice to help me resolve this problem would be greatly appreciated!

A: I don't know it is related to your problem, but all your COM calls must come from within the same thread your add-in was created on. If you created new threads you must take special care. Details are described in these two articles:

*

*Implementing IMessageFilter in an Office add-in and

*Why your COMAddIn.Object should derive from StandardOleMarshalObject

A: are you making the call from a thread with its ApartmentState set? if not, that might be the culprit - COM interop is pretty finicky about that sort of thing

A: What are the security settings of the client? It is quite possible that the security settings of the client (either Windows/OS settings or PowerPoint/App settings) won't allow your plug-in to communicate via RPC.

A: This can very easily happen if you make any calls to the Powerpoint object model from a background thread. One plausible scenario is having a timer that periodically checks some sort of status value. If, when the timer fires, Powerpoint is busy (for example a dialog box is open) the call will fail.
This Microsoft article gives an overview of threading support in Office:
http://msdn.microsoft.com/en-us/library/8sesy69e.aspx