text:
Q: Links in Spring MVC with Tiles I'm still trying to get acquainted with Tiles, I've used it before in Struts 1.x without any problems but that's not the case with Spring MVC. With Struts I'm aware that you have to create actions or use its forward tag to get to a page defined in tiles via a link, I assumed that with Spring you would similarly need to use a controller. But, it doesn't seem to be finding my tiles definitions since whenever the controller executes I get this error:

Jul 17, 2014 11:21:07 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
  WARNING: No mapping found for HTTP request with URI [/BudgeAllocatorWeb/home] in >DispatcherServlet with name 'spring-mvc'

My controller is really simple, since I'm just trying to learn and figure out how it works:
@Controller
@RequestMapping("/login")
public class LoginController {
    @RequestMapping(method=RequestMethod.GET)
    public String login(ModelMap map) {
        return "home";
    }
}

And my tiles-def.xml looks like:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="base" template="/pages/base_layout/layout.jsp">
        <put-attribute name="title" value="" />
        <put-attribute name="header" value="/pages/base_layout/header.jsp" />
        <put-attribute name="menu" value="/pages/base_layout/menu.jsp" />
        <put-attribute name="body" value="" />
        <put-attribute name="footer" value="/pages/base_layout/footer.jsp" />
    </definition>

    <definition name="home" extends="base">
        <put-attribute name="title" value="Budgeter" />
        <put-attribute name="body" value="/pages/home.jsp" />
    </definition>

</tiles-definitions>

And my spring-mvc-servlet XML file:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

       <context:component-scan base-package="controllers" />

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- <property value="/" name="prefix" />
            <property value=".jsp" name="suffix" /> -->
       </bean>

    <!-- Spring Tiles -->

    <bean id="tilesviewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles2.TilesView
            </value>
        </property>
    </bean>

    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles-def.xml</value>
            </list>
        </property>
    </bean>
</beans>

So my controller returns "home" intending to hit the "home" that is defined in my tiles-def. It works for regular pages, but not tiles definitions. Is there anything I'm missing here?

A: Remove the InternalViewResolver or set an order to the resolvers with resolver.setOrder(x). Try removing this code
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- <property value="/" name="prefix" />
        <property value=".jsp" name="suffix" /> -->
</bean>

This way only the tiles view resolver will be used.


text:
Q: How to reset OS X volume after sleep using launchd? I'm been trying to write a plist file on which when I return from sleep mode, I always want to make my Mac volume to the minimum amount. However, it looks like the following plist doesn't work, with an error: 1:1: syntax error: Expected string but found end of script. (-2741)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>KeepAlive</key>
        <false/>
        <key>Label</key>
        <string>my.plist</string>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/bin/osascript</string>
            <string>-e</string>
            <string>"</string>
            <string>set</string>
            <string>volume</string>
            <string>output</string>
            <string>volume</string>
            <string>0</string>
            <string>"</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
    </dict>
</plist>

Also, when the following is not working:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>KeepAlive</key>
        <false/>
        <key>Label</key>
        <string>my.plist</string>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/bin/osascript</string>
            <string>-e</string>
            <string>"set volume output volume 0"</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
    </dict>
</plist>

The osascript command functions well if I execute it from within Terminal, so I think it's due to how I set my arguments list to the plist.
So is it feasible to take the string argument like "~" in launchd? Or is there some other things that I'm missing here?
I suspect that it might be better to write the osascript command in shell script, and load the shell script to enable the Mac's volume to minimize... but is it the correct approach?
I use OS X Mavericks 10.9.2.

A: The second launchd job ticket format is almost correct. Only a set of quotes need removing.
Quotes
The quotes are no longer needed in the second launchd job ticket, so change:
<string>"set volume output volume 0"</string>

…to…
<string>set volume output volume 0</string>

Grouping Arguments
In this case, the quotes grouped the set of arguments for osascript to see as one item. Thus osascript gets two arguments, the flag -e and the script. This meets the requirements from the osascript manual.
When called through Terminal.app and thus through the shell, the quotes are needed to perform the grouping. When osascript gets the arguments, the shell has removed the quotes.
Without quotes, spaces subdivide each item passed via the shell.
When called through a launchd job ticket, the grouping is intrinsic within the array passed as ProgramArguments. In your first ticket, the array contained nine items and in the second ticket, the array contained three.
LaunchAgent
Be sure to add this launchd job as a ~/Library/LaunchAgents as osascript requires an active user with a graphical session.
This approach approximates what I do with Power Manager in How to Set the Volume When Logging In.

A: The second plist should work if you remove the extra quotes, but it only runs the command at login and not after waking up from sleep.
You can use sleepwatcher to run a command after waking up from sleep. Run sudo -v and paste lines like this in a shell:
curl http://www.bernhard-baehr.de/sleepwatcher_2.2.tgz|tar -x
sudo mkdir -p /usr/local/sbin /usr/local/share/man/man8
sudo cp sleepwatcher_2.2/sleepwatcher /usr/local/sbin
sudo cp sleepwatcher_2.2/sleepwatcher.8 /usr/local/share/man/man8
cp sleepwatcher_2.2/config/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist
echo $'#!/bin/sh\nosascript -e "set volume output volume 0"'>~/.sleep
chmod +x ~/.sleep

redpajama_set_name: RedPajamaStackExchange


text:
Q: System wide libxml2 not working, compilation from sources failes in configure System Wide libxml2
I want to compile the Chroma suite of physics simulations on the JUQUEEN supercomputer which is an IBM BlueGene/Q installation. The frontends run on RedHat Linux 6. Architecture is PowerPC 7 on both frontend and compute nodes. They CPUs used differ though, the frontend has IBM Power 740, the compute nodes are IBM Power A2 chips. Using compilers like mpigcc and mpig++ automatically cross compile for the compute nodes.
Modern versions of programs can be loaded into the path using module. There are dependencies on two other libraries that have to be compiled. I am done with qmp for now. qdpxx also depends on libxml2 and this is where I am stuck:
chroma --- qdpxx --- qmp
                 \-- libxml2

On my Fedora 24 workstation, I can compile qdpxx just fine using the system wide installation of libxml2. I have just installed the RPM packages libxml2 and libxml2-devel and did not have to specify any -with-libxml2=DIR arguments to qdpxx/configure.
On the supercomputer frontend, I get this:
+ ./configure --prefix=/homec/hbn28/hbn28e/local/ --host=powerpc64-bgq-linux --build=powerpc64-unknown-linux-gnu --enable-bgq-thread-binding --enable-openmp --enable-parallel-arch=parscalar --enable-precision=double --enable-parallel-io --enable-qdp-alignment=128 --with-qmp=/homec/hbn28/hbn28e/local/ 'CFLAGS=-O2 -finline-limit=50000 -I/usr/local/bg_soft/mpich3/include -Wall -Wpedantic -fdiagnostics-color=auto --std=c99 -fopenmp --std=gnu99' 'CXXFLAGS=-O2 -finline-limit=50000 -I/usr/local/bg_soft/mpich3/include -Wall -Wpedantic -fdiagnostics-color=auto --std=c++11 -fopenmp' LDFLAGS= LIBS= CC=/bgsys/local/gcc/4.9.3/bin/mpigcc CXX=/bgsys/local/gcc/4.9.3/bin/mpig++
checking for C++ compiler default output file name... a.out
checking whether the C++ compiler works... yes
checking whether we are cross compiling... yes
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether /bgsys/local/gcc/4.9.3/bin/mpig++ accepts -g... yes
checking for powerpc64-bgq-linux-ranlib... no
checking for ranlib... ranlib
configure: WARNING: using cross tools not prefixed with host triplet
checking for powerpc64-bgq-linux-ar... no
checking for ar... ar
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for powerpc64-bgq-linux-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking for style of include used by make... GNU
checking dependency style of /bgsys/local/gcc/4.9.3/bin/mpig++... gcc3
configure: Configuring QDP++ for Nd = 4
configure: Configuring QDP++ for Nc = 3
configure: Configuring QDP++ for Ns = 4
configure: Configuring QDP++ Alignment size=16
configure: Fallback to generic C routines if needed: yes
configure: Enabling BGQ Thread Binding
configure: Configuring for double precision
configure: Configuring QDP++ with cb2 layout
configure:  Parscalar build! Checking for QMP
checking for qmp-config... /homec/hbn28/hbn28e/local//bin/qmp-config
configure: Found QMP configuration program /homec/hbn28/hbn28e/local//bin/qmp-config
configure: QMP compile flags: -I/homec/hbn28/hbn28e/local/include
configure: QMP linking flags: -L/homec/hbn28/hbn28e/local/lib
configure: QMP libraries flags: -lqmp
checking if we can compile/link of a simple QMP C++ program... yes
Value of with_libxml2 is XX
checking for xml2-config... /usr/bin/xml2-config
configure: Found libxml2 configuration program
configure: libxml2 compile flags: -I/usr/include/libxml2
configure: libxml2 libraries flags: -lxml2 -lz -lm
checking if we can compile/link a simple libxml2 program... no
configure: error: Cannot compile/link a program with libxml2.
    Use --with-libxml2=<dir> to select a working version.

In qdpxx/config.log, the relevant section is this here:
configure:4321: checking for xml2-config
configure:4339: found /usr/bin/xml2-config
configure:4351: result: /usr/bin/xml2-config
configure:4370: Found libxml2 configuration program
configure:4374: libxml2 compile flags: -I/usr/include/libxml2
configure:4378: libxml2 libraries flags: -lxml2 -lz -lm
configure:4386: checking if we can compile/link a simple libxml2 program
configure:4434: /bgsys/local/gcc/4.9.3/bin/mpig++ -o conftest -O2 -finline-limit=50000 -I/usr/local/bg_soft/mpich3/include -Wall -Wpedantic -fdiagnostics-color=auto --std=c++11 -fopenmp -I/usr/include/libxml2    conftest.cpp  -lxml2 -lz -lm >&5
conftest.cpp: In function 'int main()':
conftest.cpp:30:16: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
  char *docname="foo";
                ^
conftest.cpp:28:13: warning: unused variable 'argc' [-Wunused-variable]
         int argc ; char **argv ;
             ^
conftest.cpp:28:27: warning: unused variable 'argv' [-Wunused-variable]
         int argc ; char **argv ;
                           ^
conftest.cpp:29:19: warning: variable 'doc' set but not used [-Wunused-but-set-variable]
         xmlDocPtr doc;
                   ^
/usr/local/bg_soft/gcc/4.9.3/bin/../lib/gcc/powerpc64-bgq-linux/4.9.3/../../../../powerpc64-bgq-linux/bin/ld: cannot find -lxml2
/usr/local/bg_soft/gcc/4.9.3/bin/../lib/gcc/powerpc64-bgq-linux/4.9.3/../../../../powerpc64-bgq-linux/bin/ld: cannot find -lz
collect2: error: ld returned 1 exit status
configure:4441: $? = 1
configure: failed program was:
| /* confdefs.h.  */
| #define PACKAGE_NAME "qdp++"
| #define PACKAGE_TARNAME "qdp--"
| #define PACKAGE_VERSION "1.44.0"
| #define PACKAGE_STRING "qdp++ 1.44.0"
| #define PACKAGE_BUGREPORT "edwards@jlab.org"
| #define PACKAGE "qdp--"
| #define VERSION "1.44.0"
| #define QDP_ND 4
| #define QDP_NC 3
| #define QDP_NS 4
| #define QDP_AC_ALIGNMENT_SIZE 16
| #define QDP_USE_GENERIC_OPTS 1
| #define QDP_USE_BLUEGENEL 1
| #define BASE_PRECISION 64
| #define QDP_USE_CB2_LAYOUT 1
| #define ARCH_PARSCALAR 1
| #define QDP_USE_LIBXML2 1
| /* end confdefs.h.  */
|
|         #include <libxml/xmlmemory.h>
|       #include <libxml/parser.h>
|
| int
| main ()
| {
|
|         int argc ; char **argv ;
|         xmlDocPtr doc;
|       char *docname="foo";
|       doc = xmlParseFile(docname);
|          ;
|          ;
|
|   ;
|   return 0;
| }
configure:4483: result: no
configure:4486: error: Cannot compile/link a program with libxml2.
    Use --with-libxml2=<dir> to select a working version.

The cannot find -lxml2 sounds like there is no /usr/lib/libxml2.so. And indeed, there is none there. Running locate libxml gives the following interesting lines:
/usr/include/libxml2/libxml/xpath.h
...
/usr/include/libxml2/libxml/xpointer.h
/usr/lib/libxml2.so.2
/usr/lib/libxml2.so.2.7.6
/usr/lib64/libxml2.so
/usr/lib64/libxml2.so.2
/usr/lib64/libxml2.so.2.7.6

Apparently the 32-bit version has a strange so-name and only the 64-bit version has a regular so-name. Trying to add -L/usr/lib64 turned out to break other things:
+ ./configure --prefix=/homec/hbn28/hbn28e/local/ --host=powerpc64-bgq-linux --build=powerpc64-unknown-linux-gnu --enable-bgq-thread-binding --enable-openmp --enable-parallel-arch=parscalar --enable-precision=double --enable-parallel-io --enable-qdp-alignment=128 --with-qmp=/homec/hbn28/hbn28e/local/ 'CFLAGS=-O2 -finline-limit=50000 -I/usr/local/bg_soft/mpich3/include -Wall -Wpedantic -fdiagnostics-color=auto --std=c99 -fopenmp --std=gnu99' 'CXXFLAGS=-O2 -finline-limit=50000 -I/usr/local/bg_soft/mpich3/include -Wall -Wpedantic -fdiagnostics-color=auto --std=c++11 -fopenmp' LDFLAGS=-L/usr/lib64/ LIBS= CC=/bgsys/local/gcc/4.9.3/bin/mpigcc CXX=/bgsys/local/gcc/4.9.3/bin/mpig++
checking for C++ compiler default output file name...
configure: error: in `/homec/hbn28/hbn28e/qdpxx':
configure: error: C++ compiler cannot create executables
See `config.log' for more details.

In the log file, it says the following:
configure:2159: /bgsys/local/gcc/4.9.3/bin/mpig++ -O2 -finline-limit=50000 -I/usr/local/bg_soft/mpich3/include -Wall -Wpedantic -fdiagnostics-color=auto --std=c++11 -fopenmp  -L/usr/lib64/ conftest.cpp  >&5
/usr/local/bg_soft/gcc/4.9.3/bin/../lib/gcc/powerpc64-bgq-linux/4.9.3/../../../../powerpc64-bgq-linux/lib/crt1.o: In function `_start_no_magic':
(.text+0x58): undefined reference to `__libc_no_magic_start_main'
/bgsys/local/gcc/4.9.3/powerpc64-bgq-linux/lib/libdl.so.2: undefined reference to `_dl_addr_range@GLIBC_PRIVATE'
collect2: error: ld returned 1 exit status
configure:2163: $? = 1
configure:2201: result:
configure: failed program was:
| /* confdefs.h.  */
| #define PACKAGE_NAME "qdp++"
| #define PACKAGE_TARNAME "qdp--"
| #define PACKAGE_VERSION "1.44.0"
| #define PACKAGE_STRING "qdp++ 1.44.0"
| #define PACKAGE_BUGREPORT "edwards@jlab.org"
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:2207: error: in `/homec/hbn28/hbn28e/qdpxx':
configure:2210: error: C++ compiler cannot create executables

It seems that I have just junked all other paths where libraries can reside such that nothing builds any more.
Trying to create a symlink from /usr/lib/libxml2.so.2 to $HOME/libxml2.so and addling -L$HOME has not worked either.
Trying to Compile libxml2 from Git
At this point I stopped pursuing the system wide installation and tried to install libxml2 from the Git repository. So I have cloned the repository and typed ./autogen.sh. This failed saying:
Checking zlib
./configure: line 12546: syntax error near unexpected token `Z,zlib,'
./configure: line 12546: `    PKG_CHECK_MODULES(Z,zlib,'

The autotools there claim to be version 2.69. This is the same version installed on the university cluster (where it also fails). On my Fedora 24 workstation that same version is installed but ./autogen.sh just runs through and creates a Makefile.

I am a bit lost now. Is there a bug in the build script of libxml2 if it fails on the ppc64 RedHat and also on the amd64 Debian university cluster but not my x86_64 Fedora laptop?
How could I get the configure script of qdpxx to use the system wide installation of libxml2? It does already extract the proper flags using xml2-config:
configure: libxml2 compile flags: -I/usr/include/libxml2
configure: libxml2 libraries flags: -lxml2 -lz -lm

What can I do to get my program compiled further?

A: Running ln -fs /usr/share/aclocal/pkg.m4 . in the source directory made configure find PKG_PROG_PKG_CONFIG. However, there is still the syntax error around. Rerunning autoreconf created a configure file that now has no syntax errors any more.


text:
Q: Is there a word for "guessing in favor of someone"? Is there a word for the situation when you don't know the truth but you decided to guess the best for one person. Such as in "I don't know if she has washed her hands or not, but let's just believe she did."

A: You give someone the benefit of the doubt.

a judgment in one's favor when the evidence is neither for one nor against one.

(source: The Free Dictionary)


text:
Q: How can I add a click handler to BODY from within a React component? I am building a pulldown menu React component that should close when the user clicks anywhere in the DOM outside of the component.
Using jQuery I would typically add an event listener to the body when the pulldown is opened, and remove it again when the pulldown is closed. (The event listener itself closes the pulldown – any click events within the component are not propagated to prevent the body click handler from firing.)
Is there any way to attach a listener to the body element from within a React component? Or should I just use jQuery? (I'm a bit wary of mixing React and jQuery.)

A: It's help who used function based components:
import React, { useEffect  } from 'react';

const ZSideBar = (props) => {

    useEffect(() => {
        document.body.addEventListener('click', closeSidemenu );

        return function cleanup() {
            window.removeEventListener('click', closeSidemenu );
        }
    },[]);
    let closeSidemenu = () => {
        document.getElementById("sidebar-tree").style.left = "-310px";
    }

    return (

    )

}

A: React is just JavaScript so attaching a click handler to any element is done as normal by using addEventListener(). Doing this in componentDidMount is normally very nice and tidy and clean up after yourself in componentWillUnmount by removing the added event handler.
var Component = React.createClass({
    componentDidMount: function () {
        document.body.addEventListener('click', this.myHandler);
    },
    componentWillUnmount: function () {
        document.body.removeEventListener('click', this.myHandler);
    },
    myHandler: function () {
        alert('click');
    },
    render: function() {
        return
Hello {this.props.name}
;
    }
});


text:
Q: Highlighting specific columns in bar chart in python using altair I want to highlight specific data points in a bar chart in python based on my requirement. using altair, I am able to achieve results for one data point (for e.g 'A' in the code). Here's the sample data frame and code
import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})

bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.datum.Name == 'A',
        alt.value('red'),
        alt.value('blue')
    ))
bar1

How can I highlight two or more datapoints (eg. A & B) with the same color and others with a different one? I tried passing the names as a list  Select = ['A', 'B']  and then passing the alt.datum.Name == Select but that does not work?
How can i get this done?
Also, trying to understand why passing as a list did not work?
thank you

A: You could use the FieldOneOfPredicate to check if the Name column is one of the items in the list:
import pandas as pd
import altair as alt

df = pd.DataFrame({
    'Rank': [25, 20, 40, 10, 50, 35],
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})

bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
                                       x = alt.X('Name:O', sort ='x'),
    color=alt.condition(
        alt.FieldOneOfPredicate('Name', ['A', 'B']),
        alt.value('red'),
        alt.value('blue')
    ))
bar1

You can read more about it in the VegaLite docs. You could also use two expression string with an "or" operator:
color=alt.condition(
    "datum.Name == 'A'"
    "|| datum.Name == 'B'",  # splitting on two rows for readability
    alt.value('red'),
    alt.value('blue')
)

I don't think there is a single Vega expression operator that you can use for checking membership like Python's in. This answer doesn't mention it either.


text:
Q: .nunit file ignoring configfile paramater I have set up a .nunit file to specify a local and remote test suite App.config. Here is my code :
<NUnitProject>
  <Settings activeconfig="local"/>
  <Config name="local" configfile="App.config">
    <assembly path="bin\Debug\Proj.dll"/>
  </Config>
  <Config name="remote" configfile="App.Remote.config">
    <assembly path="bin\Debug\Proj.dll"/>
  </Config>
</NUnitProject>

Now, when I run the following command in my command line
"nunit3-console" "test_runner.nunit" /config:remote

It is still running off of the App.config and not the App.Remote.config file I specified in the Config block.. Am I missing something here? Do I need to have some sort of referance in my App.config?

A: I missed the reply to my comment! In case you haven't already done so, you should ensure that the config file is copied to the output directory.


text:
Q: Почему не работает is_page Wordpress? Требуется сделать так чтобы человек который пришел на сайт мог просмотреть только первый ролик из всех, на данный момент они делятся на Episode 1, Episode 2 и т.д
Код фрейма который отображает видео при залогиненым юзеров

        <iframe src="https://player.vimeo.com/video/<?php echo carbon_get_post_meta($current_episode->ID, 'crb_vimeo_video_id'); ?>" width="100%" height="100%" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="">

Делаю для примера так, но страница перестает отображаться
<?php
    if ( is_user_logged_in() ) {
        }
    else {
        echo "free";
        }
    else (is_page( 'Episode 1' ) ) {
      echo '

';
      }
    ?>

A: Код должен быть примерно таким, с вложенными if
<?php
if ( ! is_user_logged_in() ) {
    if ( is_page( 'Episode 1' ) ) {
        echo '

';
    } else {
        echo "free";
    }
}


text:
Q: Sorting a file based on a field that's not in a fixed position i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?
Here is my input:
reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk

A: I think the bad news is, you can't.  You don't have numbers, you have things that the human eye can discern as numbers, but sort isn't smart enough to parse the number out and sort on it.  You'll have to write some custom software to do it.

A: The sort command on most modern systems is able to select fields and sort a particular field numerically.  For example:
sort -t _ -k 2 input.txt

This would work for the lines that look like reg_1_0.txt.  Of course, it would not work for the lines that contain an extra underscore before the sort field, like s_reg_1_0.txt, where you would need -k 3.
But there are tricks.
sed 's/[^0-9]*\([0-9]*\)\(.*\)/\1 &/' input.txt | sort -n | cut -d ' ' -f 2-

This rewrites the input file so that the sort field is at the beginning of the line. It then sorts numerically, and then removes the first "field" of each line to restore the look of the original content. All using ubiquitous shell tools.

A: You can pass your file through awk, extract the number based on pattern (reg_ vs s_reg), add that as an extra field and then sort it.  And finally use cut to remove the extra field.
awk -F_ '/^reg/ { print $0":"$2 } /^s_reg/ { print $0":"$3 }' file | sort -t: -k2,2n | cut -f1 -d:

Assuming that there are only two patterns, the above command can be further simplified as:
awk -F_ '/^reg/ { print $0":"$2; next } { print $0":"$3 }' file | sort -t: -k2,2n | cut -f1 -d:

Produces this output:
reg_0_0/clk
s_reg_0_0/clk
reg_1_0/clk
s_reg_1_0/clk
reg_2_0/clk
s_reg_2_0/clk
reg_3_0/clk
s_reg_3_0/clk
reg_4_0/clk
s_reg_4_0/clk
reg_5_0/clk
s_reg_5_0/clk
reg_6_0/clk
s_reg_6_0/clk
reg_7_0/clk
s_reg_7_0/clk
reg_8_0/clk
s_reg_8_0/clk
reg_9_0/clk
s_reg_9_0/clk
reg_10_0/clk
s_reg_10_0/clk
reg_11_0/clk
s_reg_11_0/clk
reg_12_0/clk
s_reg_12_0/clk
reg_13_0/clk
s_reg_13_0/clk
reg_14_0/clk
s_reg_14_0/clk
reg_15_0/clk
s_reg_15_0/clk
reg_16_0/clk
s_reg_16_0/clk
reg_17_0/clk
s_reg_17_0/clk
reg_18_0/clk
s_reg_18_0/clk
reg_19_0/clk
s_reg_19_0/clk
reg_20_0/clk
s_reg_20_0/clk
reg_21_0/clk
s_reg_21_0/clk
reg_22_0/clk
s_reg_22_0/clk
reg_23_0/clk
s_reg_23_0/clk
reg_24_0/clk
s_reg_24_0/clk
reg_25_0/clk
s_reg_25_0/clk
reg_26_0/clk
s_reg_26_0/clk
reg_27_0/clk
s_reg_27_0/clk
reg_28_0/clk
s_reg_28_0/clk
reg_29_0/clk
s_reg_29_0/clk
reg_30_0/clk
s_reg_30_0/clk
reg_31_0/clk
s_reg_31_0/clk

A: Here's one way to do it:
sed 's/g_/,/g' data.txt | sort -k2 -t, -n | sed 's/,/g_/g'

(assuming data.txt is a file of the lines to sort)
Since some of the elements to sort have two underscores instead of one, but sort only accepts a single character field separator, you could use sed to replace "g_" with "," and so that there's only one unique separator before the number for each (so the number is the second field always). Then after sorting, filter it through sed again and replace "," back with "g_".
Output:
reg_0_0/clk
s_reg_0_0/clk
reg_1_0/clk
reg_2_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
reg_10_0/clk
s_reg_10_0/clk
reg_11_0/clk
s_reg_11_0/clk
reg_12_0/clk
s_reg_12_0/clk
reg_13_0/clk
s_reg_13_0/clk
reg_14_0/clk
s_reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_30_0/clk
reg_31_0/clk

If you only want unique elements, then just add a -u flag to sort.


text:
Q: some copied folders are not accessible to asp.net site I have a simple ASP.NET site which has two running instances on two different servers.
When first server fails another server comes up servicing and vice versa.
I have a some folders having some file to be made available for user download, which constantly updates depending on user uploads.
During this server switching process a synchronization software helps copying this folders to another server.
The problem when I use site with second server the files uploaded using first server are not accessible however they are present on both server on desired location with same access permissions.
Any idea on this?


text:
Q: UPnP Library for .Net I'm trying to play around with UPnP. Specifically, I'm trying to browse the content library of  a PS3 Media Server.
I tried upnp.dll (a COM library that ships with windows) and found it easy to use. I can discover devices and look at their services pretty easily, however it throws an exception when trying to access the services of the media server (other devices, like my router and windows media player, work fine). A bit of searching around the net revealed that upnp.dll is not well implemented and other people have the same problem and found no solutions.
So I've looked for an alternative and found Mono.Upnp. It looks promising but I just can't get it to work, at all.
I saw mentions of Intel's UPnP SDK but this seems to be deprecated and I can't find a downloadable package.
I'm at a loss. Is there no alternative to upnp.dll ?

A: I decided to bite the bullet and just roll my own. It's not that hard. Simple udp + xml + soap.
This link was very helpful to me:
http://www.upnp.org/download/UPnP_Device_Architecture_Generic_20000710.ppt
For the specifics of a media server's content directory, see:
http://www.upnp.org/standardizeddcps/documents/ContentDirectory1.0.pdf
The Mono.Upnp source was also helpful.
I have no plans to make this open source as it won't be a complete implementation (I'm doing the strict minimum for my project).

A: You could also consider ohNet.  It is BSD licensed and has ports for Windows, Linux, iOS, Android and Mac and language bindings for C++, C#, Java, JavaScript and C.
(I should note that I've been involved in ohNet's development)

A: About the Intel UPnP SDK, it was recently updated and renamed to
Developer Tools For UPnP. Most notable changes are it now includes source code for all the tools and the code generator, the source is under the Apache 2.0 license, and IPv6 support was added in several places.
See blog post 1 and blog post 2 by Intel's Ylian Saint-hilaire.

A: It might be worth browsing the relevant part of MediaPortal source code. Inparticular, the UPnP project may be useful.


text:
Q: Update/append redis values I have recently started using redis. Currently it's simple key value storage. For example:
$this->redis->set('GET_ALL_DEVICES', json_encode($data));

Now if there is new entry into device table, I want to append new entry into same cached data I have. Don't want to flush cached object and create new one to reflect new entry. Is there any way to do this in redis?

A: There is no table in Redis. You must learn what Redis specific data types are.
In this case, a SET could be the right structure to be used, if you don't need the data to be ordered. So you should perform a SADD (adds a value to  SET) instead of a SET instruction, which sets the value for a single string.
$this->redis->sadd('GET_ALL_DEVICES', json_encode($data));

According to your use case, a LIST or a SORTED set may be more appropriate than a SET to store your data.


text:
Q: HTTPS communication with EC2 Instance I have my java spring project running successfully on AWS EC2 instance uploaded via elastic bean stalk but its endpoint is of the form http://...........
Now i have uploaded my angular project on firebase.
I could have uploaded it on AWS itself but it requires geolocation()  which requires HTTPS connection. when i connect my angular app to aws instance via endpoint it shows
Mixed Content: The page at 'https://aspertime-a3b60.firebaseapp.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://aspertime-env.x2enfd8jmj.ap-south1.elasticbeanstalk.com/employee/login?username=123&password=123'. This request has been blocked; the content must be served over HTTPS.
i have tried many times to solve this problem.
    -

A: So as we discussed in the comment, follow these steps

*

*Create a Certificate from AWS ACM

*Verify the certificate by adding an entry to your DNS provider

*Create Load balancer with https listener

*Place Load balancer on the top of Elastic beanstalk

*Update web-app to point New TLS endpoint


text:
Q: How to sync Argo workflow-templates b/w a git-repo and Argo instance? I have a git repository(hosted on Github) where I create my workflow-template YAMLs, and upload them to Argo via UI or REST-api. Now whenever I update any workflow-template, I have to manually update it in 2 places, the git-repo and Argo. There is a chance of either place being missed in this process.
How can I automate the process of updating workflow-templates in Argo-service, whenever the workflow-templates in git repository change?

A: you can do it in many ways.

*

*you have ArgoCD to do CD on GitOps. It will make sure synced with desired state from GitHub(preferred)

*you can use Argo workflow event binding to trigger workflow on GitHub action and get the change from GitHub and apply it. https://github.com/argoproj/argo-workflows/blob/342abcd6d72b4cda64b01f30fa406b2f7b86ac6d/docs/events.md


text:
Q: how to split this dataset into train and validation set? I want to split dataset with sklearn because I don't think validation_split is working for me. Here's how im actually reading dataset:
input_sentences = []
output_sentences = []
output_sentences_inputs = []    #Translated data

count = 0
for line in open(r'/content/drive/My Drive/TEMPPP/123.txt', encoding="utf-8"):
    count += 1

    if count > NUM_SENTENCES:
        break

    if '\t' not in line:
        continue

    input_sentence, output = line.rstrip().split('\t')

    output_sentence = output + ' <eos>'
    output_sentence_input = '<sos> ' + output

    input_sentences.append(input_sentence)
    output_sentences.append(output_sentence)
    output_sentences_inputs.append(output_sentence_input)

Now im confused how to use scikit learn. For now this is what I did.
from sklearn.model_selection import train_test_split
xTrain, xTest, yTrain, yTest = train_test_split(input_sentences, output_sentences, test_size = 0.2, random_state = 1)

First thing, Is it the right approach????
If no? then how do I make the split?
If yes? then help me with this confusion:
I was passing input_sentences and output_sentences to my layers, now what do I need to pass???? Do I still pass input_sentences and output_sentences like before and train model with full dataset or do I need to only send xTrain and yTrain???? And xTest and yTest will never be passed  by layers, only used to validate?

A: Based on your code it seems that what you're currently doing is correct.
No, you can forget about input_sentences and output_sentences, from now only use arrays that train_test_split creates.
If you're using ML algorithm that has a fit() method - this one will use xTrain and yTrain. The predict() method will take xTest and you use yTest to check accuracy of your predictions from predict() method. Say, calling sklearn.metrics.r2_score(predictions, yTest).
Also please note that using multiple question marks to end your sentence makes it sound interrogatory and impolite. You're here asking for help so please watch your punctuation.


text:
Q: Powershell filter files by SQL Server result set and copy I am executing a query in SQL Server and returning a single column result set. I need to loop through the result set and find file names matching the record from the result set. Part of the file name is a sequence number. I need to sort the files in ascending order, select the first file, and then copy only that file to a subdirectory. The records in the result set look like this:

MEMBERS.net MEMBERS_COMMENTS1.net
  MEMBERS_COMMENTS2.net
  MEMBERS_LANGUAGE.net
  MEMBERS_COVER_OHC.net
  MEMBERS_PROBLEM_LIST.net

The file names have this kind of structure:
00_1914330_MEMBERS.net
Can someone tell me why this does not achieve my end result?
add-pssnapin sqlservercmdletsnapin100
add-pssnapin sqlserverprovidersnapin100
cd SQLSERVER:\SQL\LOCALHOST\DEFAULT\Databases\SYSDB\Tables\dbo.STG0_EXPORT_JOBS
$ds = Invoke-Sqlcmd -ServerInstance 'LOCALHOST' -Query "SELECT CASE WHEN SUBSTRING([EXPORT_NAME],1,3) = 'MHC' THEN SUBSTRING([EXPORT_NAME],5,(LEN([EXPORT_NAME])))+'.net' ELSE [EXPORT_NAME]+'.net' END AS export FROM [SYSDB].[dbo].[STG0_EXPORT_JOBS] WHERE [JOB_NAME] = 'MHC_STG0_MEMBERS'"
foreach ($files in $ds) {
    $oldestfile = Get-ChildItem C:\Scripts |
        where{!$_.PSIsContainer -and $_.Name.EndsWith("$($files.export)")} |
        sort-object -property name | select-object -first 1 Name |
        Copy-Item "C:\Scripts\" + $oldestfile.substring(7,$oldestfile.length - 8) `
                   C:\Scripts\MEMBERS
 }

Here is what I get when I run this:
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS H:> C:\powershell_MoveKoreFiles.ps1
Unexpected token 'in' in expression or statement.
At C:\powershell_MoveKoreFiles.ps1:1 char:472
+ add-pssnapin sqlserverprovidersnapin100 add-pssnapin sqlservercmdletsnapin100
 Set-Location SQLSERVER:\SQL\LOCALHOST\DEFAULT\Databases\SYSDB\Tables\dbo.STG0_
EXPORT_JOBS $ds=Invoke-Sqlcmd -Query "SELECT CASE WHEN SUBSTRING([EXPORT_NAME],
1,3) = 'MHC' THEN SUBSTRING([EXPORT_NAME],5,(LEN([EXPORT_NAME])))+'.net' ELSE [
EXPORT_NAME]+'.net' END AS export FROM [SYSDB].[dbo].[STG0_EXPORT_JOBS] WHERE [
JOB_NAME] = 'MHC_STG0_MEMBERS'" -ServerInstance "LOCALHOST" foreach ($files in
<<<<  $ds){$oldestfile = Get-ChildItem C:\Scripts|where{!$.PSIsContainer -and
$.Name.EndsWith("$($files.export)")}|sort-object -property name -descending|se
lect-object -first 1 Name|Copy-Item -path "C:\Scripts\"+$oldestfile.substring(7
,$oldestfile.length - 8) -destination C:\Scripts\MEMBERS}
    + CategoryInfo          : ParserError: (in:String) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken
PS H:>

A: I think there might be one too many pipes in the script.  Remove the one after the Select -first 1 Name e.g.:
Add-PSSnapin sqlservercmdletsnapin100
Add-PSSnapin sqlserverprovidersnapin100
cd SQLSERVER:\SQL\LOCALHOST\DEFAULT\Databases\SYSDB\Tables\dbo.STG0_EXPORT_JOBS
$ds = Invoke-Sqlcmd -ServerInstance 'LOCALHOST' -Query "SELECT CASE WHEN " +
          "SUBSTRING([EXPORT_NAME],1,3) = 'MHC' THEN " +
          "SUBSTRING([EXPORT_NAME],5,(LEN([EXPORT_NAME])))+'.net' " +
          "ELSE [EXPORT_NAME]+'.net' END AS export " +
          "FROM [SYSDB].[dbo].[STG0_EXPORT_JOBS] " +
          "WHERE [JOB_NAME] = 'MHC_STG0_MEMBERS'"
foreach ($files in $ds)
{
    $oldestfile = Get-ChildItem C:\Scripts |
        Where {!$_.PSIsContainer -and $_.Name.EndsWith("$($files.export)")} |
        Sort name | Select Name -First 1
    $oldName = "C:\Scripts\$($oldestfile.substring(7,$oldestfile.length - 8))"
    Copy-Item $oldName C:\Scripts\MEMBERS
}


text:
Q: Interfacing MIDI device (Akai LPD8 mk2) from Python - works for reading but not sending Preface
I have an Akai LPD8 mk2 which I would like to interface from Python.
There are two projects that (I believe) provide interfaces for the predecessor (mk1):

*

*https://github.com/zetof/LPD8

*https://github.com/DrLuke/python-lpd8
I found I needed to make a few small changes to get the reading to work with these libs (*example below, not sure how relevant this is and it could easily be because I misunderstand something).
However, no matter what I tried, I could not get the sending to the device to work. Specifically, changing the state (on/off) of the pads of the device from Python. This state is indicated by the color of the pads' lighting.
Question
A minimal example of what I thought should work is the following:
With the very nice mido library, I would like to read a few state changes of the pads. Then send them back with a small delay (similar idea here: https://stackoverflow.com/a/29501455/655404):
from time import sleep
import mido

def get_ioport_name(search):
    # see footnote **
    names = mido.get_ioport_names()
    names = set(n for n in names if search in n)
    assert len(names) == 1
    return names.pop()

def get_messages(port):
    return list(port.iter_pending())

name = get_ioport_name("LPD8")
port = mido.open_ioport(name) # see footnote ***

# ensure that there are no messages in the queue
get_messages(port)

#pause
input("Press a few pads, then press Enter to continue...")

msgs = get_messages(port)
print(f"Recorded these messages:\n{msgs}\n")

print("Echoing these messages:")
for m in msgs:
    print(m)
    port.send(m)
    sleep(1)

This runs and gives no error messages. However, the expected color changes on the pads do not happen.
What am I doing wrong?
I have tried with different backends for mido (rtmidi, portmidi, pygame) as well as using rtmidi directly, all with the same result.
Footnotes
*Example for changes needed:
I had to change the constant's block here https://github.com/zetof/LPD8/blob/master/lpd8/lpd8.py#L16 to:
    NOTE_ON = 144+9
    NOTE_OFF = 128+9
    CTRL = 176
    PGM_CHG = 192+9

**Port names
names = mido.get_ioport_names() gives:
['Midi Through:Midi Through Port-0 14:0',
 'LPD8 mk2:LPD8 mk2 MIDI 1 20:0',
 'Midi Through:Midi Through Port-0 14:0',
 'LPD8 mk2:LPD8 mk2 MIDI 1 20:0']

and set(names) gives:
{'LPD8 mk2:LPD8 mk2 MIDI 1 20:0', 'Midi Through:Midi Through Port-0 14:0'}

The result is also the same for mido.get_input_names() and mido.get_output_names().
***Ports in mido
From what I understand mido has three port classes:
open_input()  # only receive
open_output() # only send
open_ioport() # both (and what I used above)

If I change from ioport to using an input/output pair, the result is the same:
port_in = mido.open_input(name)
port_out = mido.open_output(name)

# ensure that there are no messages in the queue
get_messages(port_in)

#pause
input("Press a few pads, then press Enter to continue...")

msgs = get_messages(port_in)
print(f"Recorded these messages:\n{msgs}\n")

print("Echoing these messages:")
for m in msgs:
    print(m)
    port_out.send(m)
    sleep(1)


text:
Q: pthread_singal awakes more than one thread on a multiprocessor system This is an excerpt from pthread_cond_wait man page
Some implementations, particularly on a multi-processor, may sometimes cause multiple threads to wake up when the condition variable is signaled simultaneously on different processors.

In general, whenever a condition wait
  returns, the thread has to re-evaluate
  the predicate associated with the
  condition wait to determine whether it
  can safely proceed, should wait again,
  or should declare a timeout. My
  Question: here what is the meaning of
  predicate?Does it mean that I need to
  create one more variable apart from
  the conditional variable provided in
  pthread_cond_wait or does it referring to the same variable which
  has been provided in
  pthread_cond_wait

A: Yes, you need an additional variable like int done_flag; to use like this:
pthread_mutex_lock(&mutex);
while (!done_flag) pthread_cond_wait(&cond, &mutex);
/* do something that needs the lock held */
pthread_mutex_unlock(&mutex);
/* do some other stuff that doesn't need the lock held */

Of course it often might not be a flag but rather a count, or some other type of variable, with a more complicated condition to test.

A: This might be useful.  You can use pthread_kill to wake a particular thread.
sigset_t _fSigMask; // global sigmask

We do this before creating our threads.  Threads inherit their mask from the thread that creates them.  We use SIGUSR1 to signal our threads.  Other signals are available.
sigemptyset(&_fSigMask);
sigaddset(&_fSigMask, SIGUSR1);
sigaddset(&_fSigMask, SIGSEGV);

Then to sleep a thread
int nSig;
sigwait(&fSigMask, &nSig);

Then to wake the thread, YourThread.
pthread_kill(YourThread, SIGUSR1);

By the way, during our testing, sleeping and waking our threads this way was about 40x faster than using condition variables.


text:
Q: Adding a single role to all server members So I am trying to make the bot give all the server members a single role. Code:
    @commands.command(pass_context = True)
    async def test(self, ctx, role: discord.Role):
        for user in ctx.guild.members:
            await user.add_roles(role)
            print(f'{user.name}  {role.name}')

However, it only printsOdysea(the name of my bot)  test role And only gives the role to itself.
Any ideas how to fix this?

A: By the comment section you can do like this.
Ps. Im using client variable instead bot, that's up to you
In main file
client = commands.Bot(command_prefix=[your_prefix], intents=discord.Intents().all())

In cogs
@commands.command()
async def test(self, ctx, role:discord.Role):
    for member in ctx.guild.members:
        try:
            await member.add_role(role)
        except:
            pass
        print(f"{member.name}, {role.name}")


text:
Q: Algebra: Help with these expressions about inverse matrix $x'$ meaning transpose of vector $x$.
Let's say I have this expression:
$$(x\cdot v')^2$$
I can write it as:
$$
(x\cdot v')^2 = (x \cdot v')(x \cdot v')
$$
My question came up when I saw somewhere that
$$
(x \cdot v')(x \cdot v') = (v' \cdot x)(x \cdot v')
$$
Specially when I realized that $(x \cdot v')$ is a matrix and $(v' \cdot x)$ is a constant.
So, obviously $(x \cdot v') != (v' \cdot x)$, but they are generating the same effect multiplying $(x \cdot v')$.
Question 1: Could some one explain it?
Also, in theses notes that I found somewhere, it has the following:
$$
(I - U)^{-1} = I - U + U^2 - U^3 + \cdots
$$
$I$ - seems to be the identity matrix
$U$ - any matrix, maybe a symmetric matrix (I am not sure)
I have no idea where does it comes from. I trying to do some examples but the results obviously doesn't make sense.
Question 2: Could someone give me a hit on what this last formula suppose to be?

A: Question 1: If $x$ and $v$ are column vectors then $v'x$ is a $1 \times 1$ matrix.  Multiplying by a $1 \times 1$ matrix is the same as multiplying by the scalar entry of that $1 \times 1$ matrix.  This is why $v'x$ is often thought of as being a scalar and not necessarily a matrix.
The key point is that scalar multiplication of matrices commutes with matrix multiplication.  So
$$(xv')(xv') = x(v'x)v' = (v'x)xv'$$
where in the very last step I've commuted the scalar $v'x$ past the matrix $x$.
Question 2: Yes $I$ is the identity matrix.  To decide what $U$ is you first have to decide in what context does $I + U + U^2 + \cdots$ make sense.  In general you need the expression $U^n$ to converge to $0$ as $n \to \infty$, but maybe that's more complicated than you'd like.  The easiest is when there is some $n$ such that $U^n = 0$ so I'll explain it in that case.
When $U^n = 0$ then the infinite expression $I + U + U^2 + \cdots$ is actually a finite expression: $I + U + U^2 + \cdots + U^{n - 1}$.  Now that it's finite you can check that
$$(I - U)(I + U + U^2 + \cdots + U^{n - 1}) = I$$
so
$$(I - U)^{-1} = I + U + U^2 + \cdots + U^{n - 1}.$$
Notice my negative signs are different from yours, there's a mistake in your formula.  You can replace $U$ with $-U$ in my formula to get
$$(I + U)^{-1} = I - U + U^2 - U^3 + \cdots + (-1)^{n - 1}U^{n - 1}$$
but that's also different that what you've written.


text:
Q: Accessing 'grailsApplication' from a plugin How do I access "grailsApplication" of the main application from a plugin?
An example situation:
I have a class in a plugin, which needs to get a resource link from the main application, which is usually retrieved via "grailsApplication". How do I do that?
SOLUTION
In the plugin class you may simply specify:
import grails.util.Holders
Holders.getGrailsApplication()

A: In services, you should be able to add
def grailsApplication

and it will be injected into your service.
If your class is a spring bean, then you should be able to inject it inside the
def doWithSpring = { ->
    myBean( org.whatever.BeanClass ) {
        grailsApplication = ref( 'grailsApplication' )
    }
}

block of the plugin main groovy file.
If it's neither of these, have you tried using the Holders class?
def grailsApplication = grails.util.Holders.getGrailsApplication()


text:
Q:  must stay instead of \u003cbr / when using google translate I use function translate as shown below. In the text there are many  tags and they are changed into \u003cbr / after translation.
Example:
Super Preis - Leistungsverhältnis.
Das bekommen Sie nur bei uns !
Super prijs - . Geld \u003cbr /\u003e U ons \u003cbr /\u003e
Question: how can prevent that the text  tags are not changed and stays after translations as  tags.
function translate($text, $from = 'de', $to = 'nl'){
 $texto_traducri = urlencode($text);
 $query = "http://translate.google.nl/translate_a/t?client=t&text=$texto_traducri%0A%0A&hl=$from&sl=$from&tl=$to&multires=1&prev=enter&oc=5&ssel=3&tsel=6&sc=1";
 $response = file_get_contents(
    $query,
    null,
    stream_context_create(
        array(
            'http'=>array(
            'method'=>"GET",
            'header'=>"Referer: http://translate.google.nl/\r\n"
            )
        )
    )
);
$p_separador = strpos($response,'","');
$p_separador = strpos($response,"]]");
$s_previo = substr($response,3,($p_separador));
$a_previo = explode("],[",$s_previo);
$txt_sum = '';
    foreach($a_previo as $s_cadenaparcial){
        $s_cadenaparcial = str_replace("]", "", $s_cadenaparcial);
        $s_cadenaparcial = str_replace("[", "", $s_cadenaparcial);
        $a_cadena = explode('","',$s_cadenaparcial);
        $txt_sum.=substr($a_cadena[0],1);
        }
    $tagresult = $txt_sum;

$tagresult = htmlspecialchars_decode($tagresult);
return $tagresult;
}

A: \u003c and \u003e represent the unicode values for < and >.
You could simply convert them back to normal characters.
Here is an example of how to do that:
<?
    function uconverter($matches) {
        return html_entity_decode('&#' . hexdec($matches[1]) . ';', ENT_COMPAT, 'UTF-8');
    }
    function decode_uchars($str) {
        return preg_replace_callback('/\\\\u([0-9A-Fa-f]{4})/', uconverter, $str);
    }

    $in = 'Super prijs - . Geld \u003cbr /\u003e U ons \u003cbr /\u003e';
    $out = decode_uchars($in); // Super prijs - . Geld
 U ons

    echo $out;
?>


text:
Q: Atomic file write operations (cross platform) How do I build up an atomic file write operation? The file is to be written by a Java service and read by python scripts.
For the record, reads are far greater than writes. But the write happens in batches and tend to be long. The file size amounts to mega bytes.
Right now my approach is:

*

*Write file contents to a temp file in
same directory

*Delete old file

*Rename temp file to old filename.

Is this the right approach? How can avoid conditions where the old file is deleted but the new filename is yet to be renamed?
Do these programming languages (python and java) offer constructs to lock and avoid this situation?

A: At least on POSIX platforms, leave out step 3 (delete old file). In POSIX, rename within a filesystem is guaranteed to be atomic, and renaming on top of an existing file replaces it atomically.

A: It's a classic producer/consumer problem. You should be able to solve this by using file renaming, which is atomic on POSIX systems.

A: In Linux, Solaris, Unix this is easy. Just use rename() from your program or mv. The files need to be on the same filesystem.
On Windows, this is possible if you can control both programs. LockFileEx. For reads, open a shared lock on the lockfile. For writes, open an exclusive lock on the lockfile. Locking is weird in Windows, so I recommend using a separate lock file for this.

A: AFAIK no.
And the reason is that for such an atomic operation to be possible, there has to be OS support in the form of a transactional file system.  And none of the mainstream operating system offer a transactional file system.
EDIT - I'm wrong for POSIX-compliant systems at least.  The POSIX rename syscall performs an atomic replace if a file with the target name already exists ... as pointed out by @janneb.  That should be sufficient to do the OP's operation atomically.
However, the fact remains that the Java File.renameTo() method is explicitly not guaranteed to be atomic, so it does not provide a cross-platform solution to the OP's problem.
EDIT 2 - With Java 7 you can use java.nio.file.Files.move(Path source, Path target, CopyOption... options) with copyOptions and ATOMIC_MOVE.  If this is not supported (by the OS / file system) you should get an exception.

A: Try Java FileLock API

A: You could try and use an extra file to act as a lock, but I'm not sure if that will work out ok. (It would force you to create lock-checking and retry logic at both sides, java and python)
Another solution might be to not create files at all, maybe you could make your java process listen on a port and serve data from there rather than from a file?

A: Have the python scripts request permission from the service.  While the service is writing it would place a lock on the file.  If the lock exists, the service would reject the python request.


text:
Q: Doing lots of boxplot using a loop in R I have a file with another 30 files, imported by:
nomes<-list.files(pattern=".txt$")
dados<-list()

for (i in 1:length(nomes))
{
  dados[[i]]<-read.table(nomes[i])
}

I want to do a box plot with those files, but when I try this:
for (i in nomes)
{
boxplot(dados$i)
}

The i only recognize the last file. I do not understand what I am doing wrong.
Thank you for your help


text:
Q: How to pass a variable from Activity to Fragment, and pass it back? I am currently making an android app, and I want to pass a date between activity and fragment.
My activity has a button, which opens the fragment: DatePickerFragment.
In my activity I show a date, which I want to modify with the fragment. So I want to pass the date to the datepicker, and send it back to the activity.
I've tried a lot of solutions, but none are working. The easy way would pass an argument, but this can't be done with fragments.

A: Sending data from Activity to a Fragment
Activity:
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();

Fragment:
Reading the value in fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String myValue = this.getArguments().getString("message");
    ...
    ...
    ...
}

But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments

A: Use the library EventBus to pass event that could contain your variable back and forth.  It's a good solution because it keeps your activities and fragments loosely coupled
https://github.com/greenrobot/EventBus

A: Sending data from Activity into Fragments linked by XML
If you create a fragment in Android Studio using one of the templates e.g. File > New > Fragment > Fragment (List), then the fragment is linked via XML. The newInstance method is created in the fragment but is never called so can't be used to pass arguments.
Instead in the Activity override the method onAttachFragment
@Override
public void onAttachFragment(Fragment fragment) {
    if (fragment instanceof DetailsFragment) {
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);
     }
}

Then read the arguments in the fragment onCreate method as per the other answers

A: answering in 2021 now a days fragment has in built static methods which are used to
pass arguments while creating the fragment try them future coders
when you create a fragment it has the following  static method with already defined
 public static categoryfrag newInstance(String param1, String param2) {
        categoryfrag fragment = new categoryfrag();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

onCreate method in fragment receives parameters through already defined code
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       if (getArguments() != null) {
           mParam1 = getArguments().getString(ARG_PARAM1);
           mParam2 = getArguments().getString(ARG_PARAM2);
         //  rr=getArguments().getInt("ky");
           sn1=mParam1;
           sn2=mParam2;
       }
   }

the below code is used in activity where mostpop is the name of the fragment class if you want other datatypes modify this in-built lines or use bundle
Fragment mp=mostpop.newInstance("parameter1","parameter2");

A: To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.
On the newInstance function of your fragment you add the arguments you wanna send to it:

/**
 * Create a new instance of DetailsFragment, initialized to
 * show the text at 'index'.
 */
public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}

Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this:
Bundle args = getArguments();
int index = args.getInt("index", 0);

If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.
Documentation tutorial:
http://developer.android.com/training/basics/fragments/communicating.html

A: thanks to @ρяσѕρєя K and Terry ... it helps me a lot and works perfectly
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // get arguments
    String strtext = getArguments().getString("edttext");
    return inflater.inflate(R.layout.fragment, container, false);
}

reference :
Send data from activity to fragment in android

A: For all the Kotlin developers out there:
Here is the Android Studio proposed solution to send data to your Fragment (= when you create a Blank-Fragment with File -> New -> Fragment -> Fragment(Blank) and you check "include fragment factory methods").
Put this in your Fragment:
class MyFragment: Fragment {

...

    companion object {

            @JvmStatic
            fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
                arguments = Bundle().apply {
                    putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
                }
            }
     }
}

.apply is a nice trick to set data when an object is created, or as they state here:

Calls the specified function [block] with this value as its receiver
  and returns this value.

Then in your Activity or Fragment do:
val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here

and read the Arguments in your Fragment such as:
private var isMyBoolean = false

override fun onAttach(context: Context?) {
    super.onAttach(context)
    arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
        isMyBoolean = it
    }
}

To "send" data back to your Activity, simply define a function in your Activity and do the following in your Fragment:
(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class

Enjoy the magic of Kotlin!

A: You can simply instantiate your fragment with a bundle:
Fragment fragment = Fragment.instantiate(this, RolesTeamsListFragment.class.getName(), bundle);

A: Public variable declarations in classes is the easiest way:
On target class:
public class MyFragment extends Fragment {
    public MyCallerFragment caller; // Declare the caller var
...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        // Do what you want with the vars
        caller.str = "I changed your value!";
        caller.i = 9999;
        ...
        return inflater.inflate(R.layout.my_fragment, container, false);
    }
...
}

On caller class:
public class MyCallerFragment extends Fragment {
    public Integer i; // Declared public var
    public String str; // Declared public var
        ...
            FragmentManager fragmentManager = getParentFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            myFragment = new MyFragment();
            myFragment.caller = this;
            transaction.replace(R.id.nav_host_fragment, myFragment)
                    .addToBackStack(null).commit();
        ...
}

If you want to use the main activity it is easy too:
On main activity class:
public class MainActivity extends AppCompatActivity {
    public String str; // Declare public var
    public EditText myEditText; // You can declare public elements too.
                                // Taking care that you have it assigned
                                // correctly.
...
}

On called class:
public class MyFragment extends Fragment {
    private MainActivity main; // Declare the activity var
...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        // Assign the main activity var
        main = (MainActivity) getActivity();

        // Do what you want with the vars
        main.str = "I changed your value!";
        main.myEditText.setText("Wow I can modify the EditText too!");
        ...
        return inflater.inflate(R.layout.my_fragment, container, false);
    }
...
}

Note: Take care when using events (onClick, onChanged, etc) because
you can be on a "fighting" situation where more than one assign a
variable. The result will be that the variable sometimes does not will
change or will return to the last value magically.

For more combinations use your creativity. :)


text:
Q: Where should the reference point be considered during torque measurement? This is an extremely silly and wierd question.
https://en.wikipedia.org/wiki/Varignon%27s_theorem_(mechanics)
While  reading about Varignon's Theorem in wikipedia I noticed this sentence,

"If many concurrent forces are acting on a body, then the algebraic sum of torques of all the forces about a point in the plane of the forces is equal to the torque of their resultant about the same point."

Well what does "a point" specify here? Can it be any point even outside the object which we are dealing with?
Another thing, lets say we are dealing with 2 concurrent forces about a point C and the two forces are acting on A. Now according to the above theorem shouldn't the above scenario be looked as
$$F_1
*AC+F_2*AC=F*CC=F*0=0?$$
Perhaps I misunderstood the theorem. As for the 1st question, I have never thought of any reference point  in case of rotational motion other than the center of mass of the object and mostly dealt with uniform shapes.

A: In general, the sum of vectors gives their resultant. But, for that to be true they must be similar and related: the sum of electric fields at a point, the sum of forces acting on a mass, and the sum of torques about a point.  In the case of torques, the sum produces the rate of change of the angular momentum measured relative to that point.  Some situations suggest a choice of point.  If you have a fixed axle of rotation, the point should be on that axle.  For a freely moving mass, the center of mass is a good choice. In a statics problem choose a point that reduces the number of torques.

A: Not so silly. Toppling of a cylinder on a block may help set the stage. A torque is a pair of anti-parallel forces of equal magnitude with a sideways displacement applied to an object.
Suppose you have a pulley supported by a fixed axis. Suppose a bunch of forces are applied to the pulley, causing it to spin. The fixed axis supplies a reaction force to each applied force. So each applied force is half of a pair of forces that apply a torque to the pulley.
$$\tau = F d_{perp}$$
Since the magnitudes are equal, you can calculate with either force. All the reaction forces are applied to the same place. So it is easy to ignore the reaction forces and focus on the applied forces.
In cases like this, we can speak of each applied force as generating a torque about the axis.

A: One condition is that all the forces lie on a plane, as well as the point of summation. Additionally, if you consider that forces can slide along their axis, it is a requirement they all meet at a point. Let us call this point $\vec{r}_{\rm all}$ and some point each force $\vec{F}_i$ goes through is $\vec{r}_i$.
The above conditions are $$ \sum_i (\vec{r}_i - \vec{r}_{\rm all}) \times \vec{F}_i = \vec{0} \tag{1} $$
The vector cross product of the relative position of each force to the force gives the torque of this force summed at $\vec{r}_{\rm all}$. When the torque is zero, it means the forces all go through this point.
Now with some simple manipulation (1) can be re-stated as
$$ \sum_i \vec{r}_i \times \vec{F}_i = \sum_i \vec{r}_{\rm all} \times \vec{F}_i  = \vec{r}_{\rm all} \times \sum_i \vec{F}_i \tag{2} $$
Or as the theorem states, the sum of all the individual torque components (due to each force) equals the torque of the combined force through the common point.
Note that in my above scenario the point of summation is the origin. It is common to use a common origin to sum up torques using $\sum_i
\vec{r}_i \times \vec{F}_i$. Without loss of generality, you can translate the points around, and the conclusion will remain the same, so choosing the origin as the point of summation just makes the math easier to see.
As noted by @R.W.Bird in the comments, there is really no need to restrict this problem into a plane and thus the torque vectors being parallel. The only real restriction is that the lines of actions of all the forces meet at a single point.


text:
Q: Spring MVC Setting variable in session I am using Spring framework.
I want to set username in session, and want to display that user name in every jsp page.
What can I achieve this in any way....

A: you might want to check out the WebUtils setSessionAttribute method:
http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/web/util/WebUtils.html#setSessionAttribute(javax.servlet.http.HttpServletRequest, java.lang.String, java.lang.Object)


text:
Q: Different sized vectors in word2vec I am trying to generate three different sized output vectors namely 25d, 50d and 75d. I am trying to do so by training the same dataset using the word2vec model. I am not sure how I can get three vectors of different sizes using the same training dataset. Can someone please help me get started on this? I am very new to machine learning and word2vec. Thanks

A: You run the code for one model three times, each time supplying a different vector_size parameter to the model initialization.


text:
Q: Waiting for a signal inside the signal handler itself I was trying to write a program which involves sending signal to a process for notifying it to pause for some time and start work again after another signal is received. I wrote a signal handler like this:
void sig_handler(int alrm)
{
    if(sig_rcv==0)
    {
        printf("Signal received..sig_rcv value: %d\n",sig_rcv);
        sig_rcv = (sig_rcv+1)%2;
        printf("After increment sig_rcv value: %d\n",sig_rcv);
        signal(SIGUSR1,sig_handler);
        if(pause()<0)
        {
            printf("Signal received again..\n");
        }
    }
    else
    {
        sig_rcv = (sig_rcv+1)%2;
        printf("Signal received..sig_rcv value: %d\n",sig_rcv);
        signal(SIGUSR1,sig_handler);
    }
    printf("Exiting..\n");
}

Here I am maintaining a global variable sig_rcv which is initially 0 and if a signal is received when it is zero, it will go to the if condition and pause for another signal.On the other hand, if it gets a signal while sig_rcv is 1, it will just change the value of that variable.
My purpose of writing the signal handler in this way was to use the same signal for two different purposes. I used this system call:
signal(SIGUSR1,sig_handler);

Now when I was sending SIGUSR1 to the process it is executing upto the pause()statement. But after sending SIGUSR1 for the second time, it shows no effect.It just freezes at the pause statement. This problem was resolved after I used another signal for removing the pause state, something like:
void sig_handler2(int a)
{
    sig_rcv = (sig_rcv+1)%2;
    printf("Restarting reading...\n");
}

and
signal(SIGUSR2,sig_handler2);

It worked perfectly in this case.
So, my question is, why is this phenomenon taking place? Can't we wait for a signal while executing the signal handler written for the same signal? If it is so, what is the reason? And is there any way of achieving the same result without using SIGUSR2?

A:
Can't we wait for a signal while executing the signal handler written for the same signal?

Whether the code waited "forever" or would receive the same signal again while already processing it, is depending on the (C/OS) implementation.
From the POSIX documentation:

During the time between the generation of a signal and its delivery or acceptance, the signal is said to be "pending".

and

If a subsequent occurrence of a pending signal is generated, it is implementation-defined as to whether the signal is delivered or accepted more than once [...]

And, BTW, calling printf() & friends from a signal handler is unsafe.

A: More generally than @alk's answer, you can't call any library function from within a signal handler in strictly-conforming C code.
Per 7.1.4 Use of library functions, paragraph 4 of the C standard:

The functions in the standard library are not guaranteed to be reentrant and may modify objects with static or thread storage duration.188

Note footnote 188, for that very paragraph, states:

Thus, a signal handler cannot, in general, call standard library functions.

As @alk states, POSIX allows you to safely call only async-signal-safe functions from within a signal handler.
Absent specific documentation for your platform that states a specific function call is safe to make from within a signal handler, you can't call a function from within a signal handler.

A: Since you're using signal rather than sigaction, it's important to note the following from the POSIX standard:

When a signal occurs, and func points to a function, it is implementation-defined whether the equivalent of a:
signal(sig, SIG_DFL);
is executed or the implementation prevents some implementation-defined set of signals (at least including sig) from occurring until the current signal handling has completed.

This reflects the two historic signal implementations, SVID and BSD.
Since you're using Ubuntu 18.04, you're likely using glibc, which implements the latter (BSD) semantics. SIGUSR1 is masked while its handler is executing.
Since you want the SVID semantics, in which no signals are masked and you need to reestablish the signal handler each time the signal handler is called, you should replace your signal(SIGUSR1, sig_handler); calls with the following:
struct sigaction sa = { .sa_handler = sig_handler, .sa_flags = SA_NODEFER|SA_RESETHAND };
sigemptyset(&sa.mask);
sigaction(SIGUSR1, &sa, NULL);

The SA_NODEFER flag together with the empty mask means no signals will be masked; SA_RESETHAND means the signal action will be reset to SIG_DFL.
In addition, as the other answers said, you shouldn't be calling printf from within the signal handler. The Linux signal safety man page says which functions can be called. sigaction, signal, and pause are OK. You can use write to write strings instead of printf.


text:
Q: alert gives [object NodeList] I have a function in Javascript & jQuery .
dynamic_link = $j('#dynamic_link_add_btn').parent().parent().parent().parent()
                  .children('tbody').html();

function add_tier (t,html_handle){
     alert(html_handle);
     $j(t).parent().parent().parent().parent()
          .children('tbody').append(html_handle);
}

It is called by onclick="add_tier(this,dynamic_link)":

    <button class="scalable add" type="button" id="dynamic_link_add_btn" onclick="add_tier(this,dynamic_link)">
        Add Extra Links
    </button>

What is it?
Handles dynamic form fields (appending HTML, to be more precise).
How should it work?
It should add the HTML it gets from the dynamic_link variable to the designated place.
It works fine with other rows.
Rows have multiple input boxes and checkboxes.
What it does right now?
The alert gives out [object NodeList].
What I have tried till now?
Iterated the NodeList. It doesn't return the HTML (I am not sure that it even does that task).
NOTE: The form is really a big one. There are many dynamic_link type variables which stores HTML. I have also compared character by character between the working and the not working LOC.

Edit: $j is just the $ of jQuery. It's been defined with jQuery.noConflict.

A: first of all you can use jQuery instaed of $j . that way you don't need to add jQuery.noConflict
then another point
instead of using
dynamic_link = $j('#dynamic_link_add_btn').parent().parent().parent().parent().children('tbody').html();

very easily you can use
dynamic_link = jQuery('#dynamic_link_add_btn').parents('.class_name').children('tbody').html();

class_name is the class name of your parent element that you want to select.
then you can try
jQuery('#dynamic_link_add_btn').live('click',function(){

var dynamic_link = jQuery(this).parents('.class_name').children('tbody').html();

      alert(dynamic_link);
      jQuery(this).parents('.class_name').children('tbody').append(dynamic_link);

});

to give a specific solution , you should post your HTML


text:
Q: Custom "With" Report Type returning "Without" records I discovered today with custom reports that have 'with' relationships that records 'without' related records are being returned.
Custom Report Type:
Accounts with Memberships
When I run this report, if I only pull in fields from the Account object, Accounts without Memberships are showing in the report. These accounts do get listed as unique rows.
As soon as I add a field from the Membership object, then only Account With Memberships show up.
I have not found this to be the case with standard report types.
E.g. Standard report type of Opportunities with Products does not show this behavior. If I run this report type and only add Opportunity Name, then the opportunity name will show multiple times(once per Opp Product) but opportunities without products will not show.
Have others experienced this? Is this known behavior? I have always understood report types to be literal and this can be deceiving if when utilizing a 'With' report if it will actually show 'without' records.
Steps to recreate:

*

*Create a Custom report type of Object A with Object B

*Save

*Create a new report using the newly created report type Only

*add a field from Object A to your report preview. You will find records
returned that do not have related Object B records.

A: When adding object B to the new custom record type, be sure to mark
Each "A" record must have at least one related "B" record
instead of
"A" records may or may not have related "B" records


text:
Q: FATAL ERROR syntax error, unexpected T_CONSTANT_ENCAPSED_STRING $googleadsensecode ="a"
"script async src='//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'></script>
<!-- CSGO investing -->
<ins class='adsbygoogle'
 style='display:inline-block;width:728px;height:90px';
 data-ad-client='ca-pub-5887577755866658';
 data-ad-slot='8619972228'></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>"
//now outputting this to HTML
echo $googleadsensecode;

I cant seem to figure out why im getting an error on line 11
FATAL ERROR syntax error, unexpected T_CONSTANT_ENCAPSED_STRING on line number 11
It has to have something to do with the parenthesis but I don't know how to do it any other way, please help.

A: Review
$googleadsensecode ="a""script

Maybe
$googleadsensecode ="script


text:
Q: TensorFlow Lite Conversion Fails Goal:
I am trying to convert a TensorFlow model with custom functions to Tflite that is capable of on-node-training.
System information:

*

*OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 18.04

*TensorFlow installation (pip package or built from source): Pip

*TensorFlow installation (pip package or built from source): tensorflow==2.8.0rc1

Problem:
conversion Fails when adding the "update_control_variate" function.
Code:
Link to the Google Colab: https://colab.research.google.com/drive/1crWPg__nYgt5IUFOA_OzgU0qgvgzmsZc?usp=sharing
Part 1:
!pip install tensorflow==2.8.0rc1

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import *
from tensorflow.keras.regularizers import *
from tensorflow.keras.callbacks import *
from tensorflow.keras.preprocessing.sequence import pad_sequences
import keras
from tqdm import tqdm
print("TensorFlow version:", tf.__version__)

class TestModel:
    def __init__(self):
        case2Idx = {'A': 0, 'B':1, 'C':2}

        self.caseEmbeddings = np.identity(len(case2Idx), dtype='float32')
        long_chars = " 0123456789"
        largest_word = []
        self.char2Idx = {"PADDING":1, "UNKNOWN":0}
        for c in long_chars:
            self.char2Idx[c] = len(self.char2Idx)
        self.charsEmbeddings = np.identity(len(self.char2Idx), dtype='float32')

    def get_model(self):
        convs = []
        casing_input = Input(shape=(12,), name='casing_input', dtype=tf.float32)
        casing = Embedding(output_dim=self.caseEmbeddings.shape[1],
                           input_dim=self.caseEmbeddings.shape[0], weights=[self.caseEmbeddings],
                           trainable=True, name='casing_embedding')(casing_input)

        character_input=Input(shape=(12,6,),name='char_input', dtype=tf.float32)
        embed_char_out=TimeDistributed(Embedding(len(self.char2Idx),
                                 156,
                                 embeddings_initializer=tf.keras.initializers.RandomUniform(minval=-0.5, maxval=0.5),
                                                 trainable=True), name='char_embedding')(character_input)

        for fsz in [2, 5]:
            l_conv = TimeDistributed(Conv1D(filters=64, kernel_size=fsz, activation='relu',
                                            strides=1))(embed_char_out)
            l_pool = TimeDistributed(GlobalMaxPooling1D())(l_conv)
            convs.append(l_pool)

        output = concatenate([casing, l_pool])
        output = Bidirectional(LSTM(74, return_sequences=False, dropout=0.5, recurrent_dropout=0.50))(output)
        output = Dense(1, activation='sigmoid')(output)

        model = Model(inputs=[casing_input, character_input], outputs=[output])
        return model

import numpy as np
import sys
m_model = TestModel()

class NodeTrainableModel(tf.Module):

    def __init__(self, trainedmodel,
                 c_i: list = None,
                 c_g:list = None):

        super(NodeTrainableModel, self).__init__()
        self.model_1 = trainedmodel
        self.model_2 = trainedmodel
        self.c_i = c_i
        self.c_g = c_g

        self.model_1.compile(
            optimizer=tf.keras.optimizers.Adam(),
            loss=tf.keras.losses.BinaryCrossentropy()
        )

    @tf.function(input_signature=[
        tf.TensorSpec([None, 12], tf.float32),
        tf.TensorSpec([None, 12, 6], tf.float32),
        tf.TensorSpec([None], tf.float32),
    ])

    def train(self, x_case, x_chars, labels):

        def process_gradient(g_j:tf.Tensor, c_g_j:tf.Tensor, c_i_j:tf.Tensor) -> tf.Tensor:
            try:
                tf.debugging.check_numerics(g_j, message='Checking gradient')
            except Exception as e:
                assert "Checking g : Tensor had NaN values" in e.message

            return g_j + c_g_j + c_i_j

        with tf.GradientTape() as tape:
            predictions = self.model_1([x_case, x_chars], training=True)
            loss_value = self.model_1.loss(labels, predictions)

        grads = tape.gradient(loss_value, self.model_1.trainable_weights)

        if self.c_i is None:
            self.model_1.optimizer.apply_gradients(
                zip(grads, self.model_1.trainable_weights)
            )

        else:

            if self.c_g is None:
                self.c_g = [g_c_i if \
                                  not isinstance(g_c_i, tf.IndexedSlices) else g_c_i for g_c_i in self.c_i]

            processed_grads = [process_gradient(g ,i, j) if \
                                not isinstance(i, tf.IndexedSlices) else i for g, i, j \
                                in zip(grads, self.c_g, self.c_i)]

            self.model_1.optimizer.apply_gradients(
                zip(processed_grads, self.model_1.trainable_weights)
            )

        results = {"loss": loss_value}

        return results

    @tf.function(input_signature=[
        tf.TensorSpec([None, 12], tf.float32),
        tf.TensorSpec([None, 12, 6], tf.float32)
    ])
    def infer(self, x_case, x_chars):
        logits = self.model_1([x_case, x_chars], training=False)
        return {
                "outputs": logits
                }

    @tf.function(input_signature=[
        tf.TensorSpec([None, 12], tf.float32),
        tf.TensorSpec([None, 12, 6], tf.float32),
        tf.TensorSpec([None], tf.float32),
    ])

    def update_control_variate(self, x_case, x_chars, labels):
        """making an additional pass over the local
            data to compute the gradient at the server model x"""

        if not self.c_i is None:
            self.c_i_old = self.c_i.copy()

        with tf.GradientTape() as tape:
            predictions = self.model_2([x_case, x_chars])
            loss_ = self.model_1.loss(labels, predictions)

        c_i = tape.gradient(loss_, self.model_2.trainable_weights)

        return c_i

    @tf.function(input_signature=[])
    def get_the_update(self):

        if not self.c_g is None:
            delta_c = [g_c_i + g_c_i_old if \
                                    not isinstance(g_c_i, tf.IndexedSlices) else g_c_i for g_c_i, g_c_i_old\
                                    in zip(self.c_i, self.c_i_old)]
        else:
            delta_c = self.c_i

        delta_weights = [local_w + global_w \
                                for local_w, global_w\
                                in zip(self.model_1.trainable_weights,
                                      self.model_2.trainable_weights)]

        return delta_weights

    @tf.function(input_signature=[tf.TensorSpec(shape=[], dtype=tf.string)])
    def save(self, checkpoint_path):
        tensor_names = [weight.name for weight in self.model_1.weights]
        tensors_to_save = [weight.read_value() for weight in self.model_1.weights]
        tf.raw_ops.Save(
            filename=checkpoint_path, tensor_names=tensor_names,
            data=tensors_to_save, name='save')
        return {
                  "checkpoint_path": checkpoint_path
              }

    @tf.function(input_signature=[tf.TensorSpec(shape=[], dtype=tf.string)])
    def restore(self, checkpoint_path):
        restored_tensors = {}
        for var in self.model_1.weights:
            restored = tf.raw_ops.Restore(
              file_pattern=checkpoint_path, tensor_name=var.name, dt=var.dtype,
              name='restore')
            var.assign(restored)
            restored_tensors[var.name] = restored
        return restored_tensors

Part 2:
Create an instance of the model and trained the model
model = m_model.get_model()
m = NodeTrainableModel(model)

more_losses = {}
for i in tqdm(range(10)):
    z = np.random.randint(11, size=[32, 12, 6])
    x = np.random.randint(3, size=[32, 12])
    casing = tf.convert_to_tensor(x, np.float32)
    char = tf.convert_to_tensor(z, np.float32)
    y = np.array(np.random.randint(0, 2, size = 32))
    y = tf.convert_to_tensor(y, np.float32)

    result = m.train(x_case = casing, x_chars = char, labels = y)
    more_losses[i] = result['loss']
    if (i + 1) % 10 == 0:
        print(f"Finished {i+1} epochs")
        print(f"  loss: {more_losses[i]:.3f}")

# Save the trained weights to a checkpoint.
m.save('/tmp/model.ckpt')

Part 3:
Convert the model to Tflite version
signatures = [
  m.train.get_concrete_function(),
  m.infer.get_concrete_function(),
  m.save.get_concrete_function(),
  m.restore.get_concrete_function(),
  m.get_the_update.get_concrete_function(),
  m.update_control_variate.get_concrete_function()
]

converter = tf.lite.TFLiteConverter.from_concrete_functions(signatures, m)
converter.target_spec.supported_ops = [
    tf.lite.OpsSet.TFLITE_BUILTINS,  # enable TensorFlow Lite ops.
    tf.lite.OpsSet.SELECT_TF_OPS,  # enable TensorFlow ops.
    tf.lite.Optimize.DEFAULT
]
converter.target_spec.supported_types = [tf.float32]
converter.experimental_enable_resource_variables = True
converter.experimental_new_converter = True
converter.allow_custom_ops = True
tflite_model = converter.convert()

Failure in conversion

2022-01-27 11:53:08.600343: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:357] Ignored output_format.
2022-01-27 11:53:08.600385: W tensorflow/compiler/mlir/lite/python/tf_tfl_flatbuffer_helpers.cc:360] Ignored drop_control_dependency.
2022-01-27 11:53:08.600602: I tensorflow/cc/saved_model/reader.cc:43] Reading SavedModel from: saved_model
2022-01-27 11:53:08.647834: I tensorflow/cc/saved_model/reader.cc:78] Reading meta graph with tags { serve }
2022-01-27 11:53:08.647877: I tensorflow/cc/saved_model/reader.cc:119] Reading SavedModel debug info (if present) from: saved_model
2022-01-27 11:53:08.787707: I tensorflow/cc/saved_model/loader.cc:228] Restoring SavedModel bundle.
2022-01-27 11:53:09.230312: I tensorflow/cc/saved_model/loader.cc:212] Running initialization op on SavedModel bundle at path: saved_model
2022-01-27 11:53:09.631676: I tensorflow/cc/saved_model/loader.cc:301] SavedModel load for tags { serve }; Status: success: OK. Took 1031073 microseconds.
2022-01-27 11:53:10.288551: E tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.cc:207] SavedModel V1 import failed: FAILED_PRECONDITION: Graph does not contain node:

ConverterError Traceback (most recent call last)
/tmp/ipykernel_5933/617434638.py in
10 converter.experimental_new_converter = True
11 converter.allow_custom_ops = True
---> 12 tflite_model = converter.convert()

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/lite.py in convert(self)
1712 Invalid quantization parameters.
1713 """
-> 1714 return super(TFLiteConverterV2, self).convert()
1715
1716

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/lite.py in wrapper(self, *args, **kwargs)
801 def wrapper(self, *args, **kwargs):
802 # pylint: disable=protected-access
--> 803 return self._convert_and_export_metrics(convert_func, *args, **kwargs)
804 # pylint: enable=protected-access
805

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/lite.py in _convert_and_export_metrics(self, convert_func, *args, **kwargs)
787 self._save_conversion_params_metric()
788 start_time = time.process_time()
--> 789 result = convert_func(self, *args, **kwargs)
790 elapsed_time_ms = (time.process_time() - start_time) * 1000
791 if result:

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/lite.py in convert(self)
1371 """
1372 if self.experimental_lower_to_saved_model:
-> 1373 saved_model_convert_result = self._convert_as_saved_model()
1374 if saved_model_convert_result:
1375 return saved_model_convert_result

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/lite.py in _convert_as_saved_model(self)
1351 if self.saved_model_dir:
1352 self._validate_inputs(graph_def, input_tensors)
-> 1353 return self._convert_from_saved_model(graph_def)
1354 finally:
1355 shutil.rmtree(temp_dir, True)

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/lite.py in _convert_from_saved_model(self, graph_def)
965 converter_kwargs.update(quant_mode.converter_flags())
966
--> 967 result = _convert_saved_model(**converter_kwargs)
968 return self._optimize_tflite_model(
969 result, quant_mode, quant_io=self.experimental_new_quantizer)

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/convert_phase.py in wrapper(*args, **kwargs)
211 else:
212 report_error_message(str(converter_error))
--> 213 raise converter_error from None # Re-throws the exception.
214 except Exception as error:
215 report_error_message(str(error))

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/convert_phase.py in wrapper(*args, **kwargs)
204 def wrapper(*args, **kwargs):
205 try:
--> 206 return func(*args, **kwargs)
207 except ConverterError as converter_error:
208 if converter_error.errors:

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/convert.py in convert_saved_model(**kwargs)
787 model_flags = build_model_flags(**kwargs)
788 conversion_flags = build_conversion_flags(**kwargs)
--> 789 data = convert(
790 model_flags.SerializeToString(),
791 conversion_flags.SerializeToString(),

~/anaconda3/envs/tf_2.8/lib/python3.9/site-packages/tensorflow/lite/python/convert.py in convert(model_flags_str, conversion_flags_str, input_data_str, debug_info_str, enable_mlir_converter)
304 for error_data in _metrics_wrapper.retrieve_collected_errors():
305 converter_error.append_error(error_data)
--> 306 raise converter_error
307
308 return _run_deprecated_conversion_binary(

ConverterError: Graph does not contain node: