text:
Q: Bind a property, inside DataTemplateItem in ListBox, to an outside object in MainPage I got ListBox with DataTemplate, inside DataTemplate I got another ListBox, trying to bind it's Visibility to another object which is found in the MainPage
XAML:
<ListBox x:Name="RegistersListView" ItemsSource="{x:Bind registersList}">
    <ListBox.ItemTemplate>
        <DataTemplate x:DataType="structures:Register">
            <StackPanel>
                <ListBox x:Name="FieldsListView" ItemsSource="{x:Bind fields_list}" Visibility="{x:Bind SomeVisibilityObjectIMain}">
                    <ListBox.ItemTemplate>
                        <DataTemplate x:DataType="structures:Field">
                            <Button Content="{x:Bind name}"/>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

C#:
public sealed partial class HWTab : Page
{
    public ObservableCollection<Register> registersList = new ObservableCollection<Register>();

    public var SomeVisibilityObjectIMain;

    public HWTab()
    {
        InitializeComponent();
        InitData();
        this.DataContext = hwType;
    }

     ....
 }

I need to bind to "SomeVisibilityObjectIMain" somehow, I tried to bind with ElementName or even make object static, but could not succeed.
My bindable object is more complex than the example here but solve this will give me the way for solution.

A: You could use {Binding} instead of x:Bind. This way you could add a x:Name="Page" to your page and then use this name in the inner binding:
{Binding ElementName=Page, Path=MyProperty}

For {Binding} to work however, MyProperty must be actually a property. From your sample code (which uses var which is also invalid) it seems it is just a plain field, so you will need something like:
public string MyProperty {get;set;}

To also get PropertyChanged notifications, you will need to add a backing field and trigger PropertyChanged event.
However, overall a better solution would be to include all information a DataTemplate needs into the actual items which are bound to it. That means - you would create a custom view model type for the items, which would include the information that you need to control visibility.


text:
Q: Passing parameters and Custom Attributes I am not sure where to go with my issue. I want to create a custom authorization attribute for checking roles and permissions. Our permissions are not your standard this role has these permissions but more of a each role can have some permissions but not others.
I have overridden the AuthorizeCore method in the AuthorizeAttribute class:
 internal class RoleAttribute : AuthorizeAttribute
{
    private readonly IUserRepository _userRepository;
    private readonly IPermissionRepository _permissionRepository;

    public RoleAttribute(IUserRepository userRepository, IPermissionRepository permissionRepository)
    {
        _userRepository = userRepository;
        _permissionRepository = permissionRepository;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        User user = _userRepository.GetUsers();
        Permission permission = _permissionRepository.GetPermissions();
        return user.Permissions.Where(x => x.Id == permission.Id).Any();
    }
}

So that when I implement the attribute:
         private static IUserRepository _userRepository;
    private static IPermissionRepository _permissionRepository;

    public TopNavigationController(IUserRepository userRepository, IPermissionRepository permissionRepository)
    {
        _userRepository = userRepository;
        _permissionRepository = permissionRepository;
    }

    [Role(_userRepository, _permissionRepository)]
    public ActionResult MethodThatHasStuff()
    {
         //Do stuff return stuff if user has the permissions
    }

I cannot dependency inject into the overridden method because I cannot then pass the injections into the attribute.
I realize this is not a great way to approach the problem but until we can work something out with our customer that moves us towards better practices I need to develop accordingly.
My main question is: Is there a better way to create a custom authorization filter that would allow this type of behavior?

A: If you have the idea that just because you instantiate the repositories in the controller, that the same instances will be used for each request, you're mistaken. The controller will be instantiated each time. As a result, you're not saving yourself much by not simply just instantiating the repos in the attribute. Given the limitations of using an attribute, there's really no better way to give it access to the dependencies, and using statics on a controller is a hugely bad idea.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display sub-collection in flutter Firebase I want to display the data of a sub-collection named "Profile". I get it that we need to query it differently, and I tried it, but it is not working out for me. First, I displayed the information from the documents of the mother collection "mentors", using StreamBuilder. Then passed it's data to a Widget I created. Then on the Widget I created, I performed another streamBuilder query for the subcollection of each document of the Mother Collection "mentors".
This is the code I used to display the documents on "mentors" collection, and is working fine.
final mentors = Expanded(
  child: Container(
    height: 250,
    margin: const EdgeInsets.only(left: 20, right: 20),
    child: StreamBuilder<QuerySnapshot>(
        stream: db_mentors,
        builder: (
          BuildContext context,
          AsyncSnapshot<QuerySnapshot> snapshot,
        ) {
          if (snapshot.hasError) {
            Fluttertoast.showToast(msg: "An Error Occured");
          }

          if (snapshot.connectionState == ConnectionState.waiting) {
            Fluttertoast.showToast(msg: "Loading");
          }

          final data = snapshot.requireData;
          return ListView.builder(
            itemCount: data.size,
            itemBuilder: ((context, index) {
              return mentorsWidget(
                "${data.docs[index]["uid"]}",
                "${data.docs[index]['name']}",
                "${data.docs[index]['specialty']}",
              );
            }),
          );
        }),
  ),
);

This here is the code I used to display the data from the subcollection of each document named "Profile". Which is also the widget I created.
Widget mentorsWidget(String uid, String name, String specialty) {
  return Container(
    margin: const EdgeInsets.all(5),
    width: size.width,
    decoration: const BoxDecoration(
        color: Color.fromARGB(255, 3, 42, 134),
        borderRadius: BorderRadius.only(
            topRight: Radius.circular(20),
            bottomRight: Radius.circular(20))),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        StreamBuilder(
            stream: FirebaseFirestore.instance
                .collection("mentors")
                .doc(uid)
                .collection("Profile")
                .snapshots(),
            builder: (
              BuildContext context,
              AsyncSnapshot<QuerySnapshot> snapshot,
            ) {
              if (!snapshot.hasData) {
                return SizedBox(
                  width: 80,
                  child: Image.asset("assets/Navigatu-icon.ico"),
                );
              } else {
                return ListView.builder(
                  itemCount: snapshot.data!.docs.length,
                  itemBuilder: ((context, index) {
                    String url = snapshot.data!.docs[index]['downloadURL'];
                    return SizedBox(
                      width: 80,
                      child: Image.network(url),
                    );
                  }),
                );
              }
            }),
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: const EdgeInsets.only(top: 10, left: 5),
              child: Text(
                name,
                style: const TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontFamily: 'Roboto',
                    fontWeight: FontWeight.w500),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 15, bottom: 15, left: 5),
              child: Text(
                specialty,
                style: const TextStyle(
                  color: Colors.white,
                  fontFamily: 'Roboto',
                  fontWeight: FontWeight.w400,
                  fontSize: 12,
                ),
              ),
            ),
          ],
        )
      ],
    ),
  );
}

Here is the Collection Tree in my firebase:
Firebase Collection Tree
Here is the display I want to achieve. The boat picture here supposedly must be a Image.network, with the url that is in the sub-collection, named "Profile".
Mentor Field
As you can see in the code, I performed first the "final mentors", then performing streambuilder inside of it. So that I can get the datas of each document from the mother collection. Now I passed those data to the "mentorwidget" to display them in a proper way, but then I wanna use a Image.network, containing the data inside the sub-collection of each document in the mother collection. That's why I performed another streambuilder inside the mentorwidget to display the picture, or get the data of the sub-collection which is the url of the said picture.

A: If the data doesn't get frequently updated or if you don't need to display the constant changes of it's value to the users then use FutureBuilder instead of StreamBuilder to query the value you want only once.
class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<QuerySnapshot>(
        future: FirebaseFirestore.instance
            .collection('mentors')
            .doc('b23lt...[your desired document ID]')
            .collection('Profile')
            .get(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData) {
            return ListView.builder(
              itemCount: , // lenght of snapshot data,
              itemBuilder: (context, index) {
               //Here you can retrieve the data of each document
              },
            );
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

A: Update: I found the answer! thanks to Slender's answer, I managed to get the answer, here is the code.
FutureBuilder<QuerySnapshot>(
          future: FirebaseFirestore.instance
              .collection("mentors")
              .doc(uid)
              .collection("profile")
              .get(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.data!.docs.isEmpty) {
                return SizedBox(
                  width: 80,
                  child: Image.asset("assets/Navigatu-icon.ico"),
                );
              } else if (snapshot.hasData) {
                // print(snapshot);
                return SizedBox(
                  width: 80,
                  child: Image.network(
                      "${snapshot.data!.docs[0]['downloadURL']}"),
                );
              }
            }
            // print(snapshot.data!.docs[0]['downloadURL']);
            return const SizedBox(
              width: 80,
              child: Center(
                child: CircularProgressIndicator(),
              ),
            );
          },
        ),


text:
Q: How to show two ListView on the same screen with Flutter? I trying to make two listView in one screen, but the second listView only show half screen(lot of space at the bottom).
import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Flexible(
          child: Container(
            color: Colors.red,
            child: _showFirstListView(),
          ),
        ),
        Expanded(
          child: Container(
            color: Colors.blue,
            child: _showSecondListView(),
          ),
        )
      ],
    );
  }

  Widget _showFirstListView() {
    return ListView.builder(
      itemCount: 1,
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return Text("First ListView");
      },
    );
  }

  Widget _showSecondListView() {
    return ListView.builder(
        itemCount: 15,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 15,
                ),
                Text("FirstLine"),
                SizedBox(
                  height: 15,
                ),
                Text("SecondLine"),
                SizedBox(
                  height: 15,
                ),
                Text("ThirdLine"),
              ],
            ),
          );
        });
  }
}

I have posted it on dartpad.
https://dartpad.dev/950d274dc06deb127d91d77b539c5db5

A: Instead of Column, use another ListView to contain both _showFirstListView and _showSecondListView.
Then your ListView in _showFirstListView and _showSecondListView should have
shrinkWrap: true,
physics: ClampingScrollPhysics(),

Demo: DartPad
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: <Widget>[
          _firstListView(),
          _secondListView(),
        ],
      ),
    );
  }

  Widget _firstListView() {
    return Container(
      color: Colors.green,
      child: ListView.builder(
        itemCount: 20,
        shrinkWrap: true,
        physics: ClampingScrollPhysics(),
        itemBuilder: (context, index) => ListTile(title: Text("FIRST $index")),
      ),
    );
  }

  Widget _secondListView() {
    return Container(
      color: Colors.red,
      child: ListView.builder(
        itemCount: 20,
        shrinkWrap: true,
        physics: ClampingScrollPhysics(),
        itemBuilder: (context, index) => ListTile(title: Text("Second $index")),
      ),
    );
  }
}

A: You want to remove the first ListView from a Flexible because you are already shrinking it to wrap and using both shrinkWrap and Flexible in the same list, will result on both lists sharing the same space 50/50, but you are actually shrinking the first one and the remaining space will be blank.
To avoid that, just let the list itself decide what space to use.
 @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          color: Colors.red,
          child: _showFirstListView(),
        ),
        Expanded(
          child: Container(
            color: Colors.blue,
            child: _showSecondListView(),
          ),
        )
      ],
    );
  }

A: I know it's already answered, but for what you are trying to achieve, I don't know why do you even want to use two listviews that scroll separately, why not use a single list view. Try this, might be better than what you want.
import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SingleChildScrollView(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
          Container(
             width: double.infinity,
            color: Colors.red,
            child: _showFirstListView(),
          ),
          Container(
            width: double.infinity,
            color: Colors.blue,
            child: _showSecondListView(),
          ),
      ],
    );
  }

  Widget _showFirstListView() {
    return Column(
    children: [
      ...[1].map((item) => Text("first listview")), //just in case you want to build from list of items as you would do in ListView.builder
    ],
    );
  }

  Widget _showSecondListView() {
    return Column(
    children: [
      //usually you already have a list of items you want to display
      ...[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].map((item) => Container(
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 15,
                ),
                Text("FirstLine"),
                SizedBox(
                  height: 15,
                ),
                Text("SecondLine"),
                SizedBox(
                  height: 15,
                ),
                Text("ThirdLine"),
              ],
            ),
          )), //just in case you want to build from list of items as you would do in ListView.builder
    ],
    );
  }
}


text:
Q: #{facesContext} EL expression not resolved at runtime I am working on JSF 1.x
On an example stated in JavaServer Faces in Action.
My EL expression of 'Faces Context' is not executing at run time in command button on retrieving the image.
My Project Structure is as follows:

I have not used any Java code in this example,
And it contains only one Login Page.
The login.jsp is as follows:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="stylesheet.css" />

    <script type="text/javascript">
        function set_image(button, image){
            button.src = img;
        }
    </script>

    <title><h:outputText value="ProjectTrack" /></title>
</head>

<body>

    <h:form>
        <h:panelGrid columns="2" border="0" cellpadding="3" cellspacing="3">

            <h:graphicImage url="/images/logo.png"
                    alt="Welcome to ProjectTrack" title="Welcome to ProjectTrack"
                    width="149" height="160" />

            <h:panelGrid columns="3" border="0" cellpadding="5" cellspacing="3" headerClass="login-heading">

                <f:facet name="header">
                    <h:outputText value="ProjectTrack" />
                </f:facet>

                <h:outputLabel for="userNameInput" >
                    <h:outputText value="Enter your user name: " />
                </h:outputLabel>

                <h:inputText id="userNameInput" size="20" maxlength="30" required="true">
                    <f:validateLength minimum="5" maximum="30"/>
                </h:inputText>

                <h:message for="userNameInput" />

                <h:outputLabel for="passwordInput">
                    <h:outputText value="Password"/>
                </h:outputLabel>

                <h:inputSecret id="passwordInput" size="20" maxlength="20" required="true">
                    <f:validateLength minimum="5" maximum="15" />
                </h:inputSecret>

                <h:message for="passwordInput" />

                <h:panelGroup>
                    <h:commandButton  action="success"
                                image="#{facesContext.externalContext.requestContextPath}/images/submit.gif"
                                onmouseover="set_image(this, '#{facesContext.externalContext.requestContextPath}/images/submit_over.gif');"
                                onmouseout="set_image(this, '#{facesContext.externalContext.requestContextPath}/images/submit.gif');"
                            />
                </h:panelGroup>

            </h:panelGrid>

        </h:panelGrid>
    </h:form>
</body>
</f:view>
    </html>

My Deployment Descriptor web.xml is as follows:
<web-app version="2.5"
      xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Project Track</display-name>
    <description>Sample Project</description>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>faces/login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

Faces-config.xml is as follows:
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
     "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
     "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>

    <application>
        <message-bundle>ptrackResources</message-bundle>
    </application>

    <navigation-rule>
        <from-view-id>/login.jsp</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/inbox.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>failure</from-outcome>
            <to-view-id>/login.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>

</faces-config>

My Maven Dependencies are as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.achutha.labs</groupId>
  <artifactId>03JsfExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>03JsfExample</name>
  <description>Project Track</description>

  <dependencies>

        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>1.2_14</version>
        </dependency>
        <dependency>
            <groupId>javax.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>1.2_14</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>

        <!-- EL -->
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>JavaServerFaces</finalName>

        <plugins>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <configuration>
                    <url>http://localhost:8090/manager/text</url>
                    <server>TomcatServer</server>
                    <path>/balaji</path>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

The Application Ran successfully. But the Image for submit button is not displaying which is retrieved through a run time expression.
Browser Display:

I have configured my JBoss tools, from which i can see the preview which evaluates the expression and displays the submit button before deployment:
Eclipse Screen Shot:

The EL expression used in  is not evaluating at runtime.
<h:commandButton  action="success"
                                image="#{facesContext.externalContext.requestContextPath}/images/submit.gif"
                                onmouseover="set_image(this, '#{facesContext.externalContext.requestContextPath}/images/submit_over.gif');"
                                onmouseout="set_image(this, '#{facesContext.externalContext.requestContextPath}/images/submit.gif');"
                            />

I have to use JSF 1.x and cannot upgrade it to JSF 2.
Please suggest me the solution, and help me know what is going wrong.
My problem is similar to the problem stated here in this link:
FacesContext not resolved at run-time
EDIT:
I just added a Debug statement in login.jsp which is as follows:
<h:outputText value=" Debug test for EL exp : #{facesContext.externalContext.requestContextPath}/images/submit.gif" />

Debug Result:

The expression is getting evaluated at runtime,
But I feel the result must not contain /balaji/images/submit.gif,
And it should only contain /images/submit.gif.

A: The implicit EL variable #{facesContext} is only available in JSF2. The shorthand #{request} as suggested in a comment is only available in Facelets.
You're using JSF1 on JSP. You should be using ${pageContext.request.contextPath} instead.

Unrelated to the concrete problem, the <h:commandButton image> is already context-relative. You don't need to specify it in there. It's only mandatory for your JS mouseover/out functions.

A: You have set an url-pattern containing /faces/*, you must access your JSF pages using this pattern or change to another pattern.
Example of other pattern:
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.face</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
    <param-value>.xhtml</param-value>
  </context-param>
  <security-constraint>
    <display-name>Disallow direct access to the XHTML Documents</display-name>
    <web-resource-collection>
      <web-resource-name>XHTML</web-resource-name>
      <url-pattern>*.xhtml</url-pattern>
    </web-resource-collection>
    <auth-constraint />
  </security-constraint>


text:
Q: Navigationpage NavigatedTo not working on IOS when go back - Maui I'm creating an app, where I want to know what page is currently shown. Some childpages should not be counted as currentpages, that's why I opted to not look at the last Item of the navigationstack as it wouldn't always be right in my case. Besides, I haven't found a way to subscribe to any collectionchanged event on the navigationstack.
The solution I tried to implement goes as follows: In my ViewModel I have a property (Currentpage) in which the current page is stored. This Property gets overwritten whenever the NavigatedTo event of a page is executed.
private void BasePage_NavigatedTo(object sender, NavigatedToEventArgs e)
{
    ViewModel.CurrentPage = this;
}

I was able to solve the problem with the childpages by not subscribing them to the event:
if (shouldChangeCurrentPage)
{
    ViewModel.CurrentPage = this;
    this.NavigatedTo += BasePage_NavigatedTo;
}

My problem now is, that on IOS, the NavigatedTo Event does not get called if you go back to the last page via the backbutton of the navigationpage. Is there any way to make this work?


text:
Q: C:\Users\B e B>upgrade pip 'upgrade' is not recognized as an internal or external command, operable program or batch file C:\Users\B e B>upgrade pip
'upgrade' is not recognized as an internal or external command,
operable program or batch file.

A: Try:
py -m pip install --upgrade pip

https://pip.pypa.io/en/stable/installation/#upgrading-pip

A: Check two possibilities:

*

*You are using a current version of pip while the old version of Python.
Go to your folder Python>>Python 310(or any other no.)>>Scripts, on the top address bar write cmd and then type pip, press Enter

*You may have installed Python in two different places


text:
Q: Prove the sequence $x_{n+1}=\frac{x_n}{1-e^{-x_n}}-a$ for $(0I encountered a elementary problem in a small calculus competition from local college. After a little study, yet I find it seems not that obvious to solve.
Given the sequence defined as
$$x_{n+1}=\frac{x_n}{1-e^{-x_n}}-a,\quad(0<a<1)$$
with $x_1=1-a$, prove its convergence and find the limit.
(Here I think the initial item $x_1$ may not important to the convergence or the limit, let $x_1=1-a$ is only for students to simplify their answer in such a test, a general proof may not need the value of $x_1$.)
Some simple attempt:
If the sequence converges, it is not difficult to find the limit is the root of function $f(x)$, which is
$$f(x)=\frac{x}{e^x-1}=a$$
and easy to show $f(x)$ is monotonic to $(0,1)$, which guarantees $f(x)=a$ always has the only root, as well the limit of sequence, denoting $x_0$.
A straight idea is the prove the sequence $\{x_n\}$ is monotonically increasing to their upper-bound $x_0$. (But it is only a guess, maybe my idea is wrong from the beginning).
To utilize induction, it is easy to check $1-a=x_1<x_2<x_0$. Now given $1-a=x_1<x_{n-1}<x_n<x_0$, the problem can be solved if we can prove $1-a=x_1<x_n<x_{n+1}<x_0$. The monotonicity $x_n<x_{n+1}$ is also easy to check if we already have $x_n<x_0$, however, $x_{n+1}<x_0$ is not that obvious to prove.
Maybe such simple idea is just not the right approach, so I am waiting for some further suggestion. Thanks in advance.

A: In fact, your idea is right. Your problem is how to prove that $x_n<x_0$. To see this, we shall use induction. Suppose we have $x_n<x_0$. Then
$$
\begin{align}
x_{n+1}&=\frac{x_n}{1-e^{-x_n}}-a\\
&=e^{x_n}\frac{x_n}{e^{x_n}-1}-a\\
&<e^{x_0}\frac{x_0}{e^{x_0}-1}-a\\
&=\left(\frac{x_0}{a}+1\right)a-a\\
&=x_0.
\end{align}
$$


text:
Q: Sequence of functions - computing sum of the series and showing convergence Consider the sequence of functions $f_n:[0,1]$,$f_n:=(-1)^n(1-x)x^n, n=0,1,2,....,0<=x<=1.$
a. Compute the sum of the series $f(x):=\sum_{n=0}^{\infty}f_n(x),$ x belongs to [0,1].
b. Show that the series  $f(x):=\sum_{n=0}^{\infty}f_n(x)$ converges to $f$ uniformly on [0,1].
I've been having difficulty solving this problem and would appreciate any help!

A: Part a) involves evaluation of geometric series:
$$\sum_{n=0}^{\infty} f_n(x) = (1-x) \sum_{n=0}^{\infty} (-1)^n x^n = \frac{1-x}{1+x}$$


text:
Q: Find most recent occurrence of an event for an individual My apologies for yet another question about finding the most recent date in an array.
Unfortunately, I have not had any luck finding any other posts that meet my particular needs.

*

*column 1 is a userid

*column 2 is the type of action that occurred and

*column 3 is the date time stamp that the action occurred at

My goal is to group by user_id and have the most recent for the different action types be their own column.
Example data:
+---------+--------+------------+
| user_id | source |  created   |
+---------+--------+------------+
|       1 | QT     | 2020-01-01 |
|       2 | QT     | 2020-01-02 |
|       3 | QT     | 2020-01-01 |
|       1 | QT     | 2020-01-03 |
|       2 | QT     | 2020-01-04 |
|       3 | QT     | 2020-01-05 |
|       1 | AT     | 2020-01-02 |
|       2 | AT     | 2020-01-02 |
|       3 | AT     | 2020-01-03 |
+---------+--------+------------+

Desired outcome:
+---------+------------+------------+
| user_id |   max QT   |   Max AT   |
+---------+------------+------------+
|       1 | 2020-01-03 | 2020-01-02 |
|       2 | 2020-01-04 | 2020-01-02 |
|       3 | 2020-01-05 | 2020-01-03 |
+---------+------------+------------+

My initial thought was:
```select
user_id
,case when source = 'QT' THEN max(created) END as "last_QT"
,case when source = 'AT' THEN max(created) END as "last_AT"
from analytics.all_tx_bars_all
group by user_id```

but that gives me the error:
Invalid operation: column "source" must appear in the GROUP BY clause or be used in an aggregate function
When I include "source" into the group by and select like:
```select
user_id
,source
,case when source = 'QT' THEN max(created) END as "last_QT"
,case when source = 'AT' THEN max(created) END as "last_AT"
from analytics.all_tx_bars_all
group by user_id,source```

I get something like:
+---------+--------+------------+------------+
| user_id | source |   max QT   |   Max AT   |
+---------+--------+------------+------------+
|       1 | QT     | 2020-01-03 |            |
|       2 | QT     | 2020-01-04 |            |
|       3 | QT     | 2020-01-05 |            |
|       1 | AT     |            | 2020-01-02 |
|       2 | AT     |            | 2020-01-02 |
|       3 | AT     |            | 2020-01-03 |
+---------+--------+------------+------------+

To add a little more color to my question, I'm using the SQL tool in metabase here

A: Assuming that you are running Postgres, as the error message seems to indicate, you can do conditional aggregation as follows:
select
    user_id,
    max(created) filter(where source = 'QT') max_qt,
    max(created) filter(where source = 'AT') max_at
from analytics.all_tx_bars_all
group by user_id

If your database does not support the filter syntax, then we can fallback on case expressions:
select
    user_id,
    max(case when source = 'QT' then created end) max_qt,
    max(case when source = 'AT' then created end) max_at
from analytics.all_tx_bars_all
group by user_id

A: You simply need aggregation:
select user_id,
       max(case when source = 'QT' then created end) as last_QT,
       max(case when source = 'AT' then created end) as last_AT
from analytics.all_tx_bars_all
group by user_id;

Note that I have removed source from both the select and the group by.


text:
Q: C++ Initializing an array with a variable and not a constant expression I am currently in the process of learning C++ and have been reading C++ Primer (5th Edition).
In chapter 3.5 which talks about arrays and initializing them, it says arrays must be initialized using a constant expression.
Here is an example from the book
unsigned cnt = 42; // not a constant expression
constexpr unsigned sz = 42; // constant expression
int arr[10]; // array of ten ints
int *parr[sz]; // array of 42 pointers to int
string bad[cnt]; // error: cnt is not a constant expression
string strs[get_size()]; // ok if get_size is constexpr, error otherwise"

Excerpt From: Stanley B. Lippman. "C++ Primer, Fifth Edition."

However when I try this using g++ -std=c++11 everything compiles just fine. So I am kind of confused as whether this is just a mistake in the book or has the standard been modified since the writing of the book even though the book states it uses C++ 11.
Here is the actual code I am using which compiles and runs perfectly fine
unsigned int cnt = 42; // not constant expression
constexpr unsigned int sz = 42; // constant expression

int arr[10]; // array of 10 ints
int *parr[sz]; // array of 10 int pointers
string bad[cnt];

I even tried something like this
int var = 2;
int size = var;
int int_arr[size];

And this also works.
If anyone has an explanation or just why this works even though it states it shouldn't I would appreciate it.
Thanks!

A: Variable length arrays are extensions that are built into the compiler for C++11 and are not standard, if you compile with the -Wvla flag you will see the compiler emit an error for your code.
You are better of using std::vector for dynamic arrays instead.  If you are not familiar with how to use those I would suggest looking around online.  There are plenty of good sources which go into detail about how to use std::vector and how it works.


text:
Q: Mongodb interface for high speed updates Are there any examples with source code for high speed (at least 10,000 read/write of record/s) mongodb read/update of a single record at a time ?
Alternatively where could I look in the mongodb server code for a way to say inject a customised put/get record for example with the "wired tiger" storage system ?
For example say that mongo C interface is similar to oracle's sql*net client, I'd need something similar to sqlldr bulk insert/update tool.
Thank you for any hint where to start from.

A: Raw performance is highly dependent on hardware. If the only requirement is "10,000 reads/writes of one document per second", then all of the following would help:

*

*Having an empty database.

*Storing the database in memory (tmpfs).

*Using linux rather than windows.

*Using a CPU with high clock speed, at the expense of core count.

*Using the fastest memory available.

You might notice that some of these conditions are mutually exclusive with many practical systems. For example, if you truly have an empty database or nearly-empty database that fits in memory, you could probably use something like redis instead which is much simpler (i.e. has WAY less functionality) and thus for a simple operation like read/write of a simple document would be way faster.
If you try to implement this requirement on a real database, things become way more complicated. For example, "10,000 reads/writes of one document which is part of a 10 GB collection which is also being used in various aggregation pipelines" is a very different problem to solve.
For a real-world deployment there are simply too many variables to account for, you need to look at your system and go through performance investigation or hire a consultant who can do this. For example, if you talk to your database over TLS (which is very common) that creates significant overhead in the wire protocol which would absolutely seriously affect your peak r/w performance of trivial document sizes.


text:
Q: Dell Inspiron n5110 syslog ACPI warnings on Ubuntu 13.04 I just installed Ubuntu 13.04 and got a bunch of warnings in syslog:
May  9 02:21:34 Dell kernel: [    9.689651] ACPI Warning: 0x0000000000000428-0x000000000000042f SystemIO conflicts with Region \PMIO 1 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689676] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver
May  9 02:21:34 Dell kernel: [    9.689688] ACPI Warning: 0x0000000000000540-0x000000000000054f SystemIO conflicts with Region \GPIO 1 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689703] ACPI Warning: 0x0000000000000540-0x000000000000054f SystemIO conflicts with Region \_SB_.PCI0.PEG0.PEGP.GPIO 2 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689717] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver
May  9 02:21:34 Dell kernel: [    9.689724] ACPI Warning: 0x0000000000000530-0x000000000000053f SystemIO conflicts with Region \GPIO 1 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689738] ACPI Warning: 0x0000000000000530-0x000000000000053f SystemIO conflicts with Region \_SB_.PCI0.PEG0.PEGP.GPIO 2 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689752] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver
May  9 02:21:34 Dell kernel: [    9.689758] ACPI Warning: 0x0000000000000500-0x000000000000052f SystemIO conflicts with Region \GPIO 1 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689772] ACPI Warning: 0x0000000000000500-0x000000000000052f SystemIO conflicts with Region \_SB_.PCI0.PEG0.PEGP.GPIO 2 (20121018/utaddress-251)
May  9 02:21:34 Dell kernel: [    9.689785] ACPI: If an ACPI driver is available for this device, you should use it instead of the native driver

and I would like to get rid of them, but have no clue on how...
what is ACPI and how do I get to know what device is ment from these lines?
thia,
morbus


text:
Q: Please help me simplify this Data Validation (IDataErrorInfo) I have a bunch of textboxes in my application that all have to be filled with numbers (doubles). I want to use Data Validation to make sure this happens and that a user doesnt enter strings. Currently in my XAML I have:
<TextBox x:Name="VoorzieningBerging"
         Text="{Binding Path=VoorzieningBerging, Source={StaticResource Gegevens},
         ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay,
         FallbackValue=0}"/>

And in my Resource I have the following class:
public class GegevensValidatie : IDataErrorInfo
{
    public string VoorzieningBerging
    {
        get;
        set;
    }

    public string Error
    {
        get { return null; }
    }

    public string this[string name]
    {
        get
        {
            string err = string.Empty;

            if (name == "VoorzieningBerging") {
                try
                {
                    double.Parse(VoorzieningBerging);
                }
                catch
                {
                    err = "error";
                }
            }

            return err;
        }
    }
}

However after a lot of messing around trying to get other DataValidations to work this has stopped working for me also. Please help me find an efficient way to check if all my textboxes have doubles for value.
Edit, when changing the DataBinding to:
Mode=OneWayToSource

It will work and show "error" when I fill in anything but a number in the textbox. But still, adding an "if" statement for every single textbox in my application is going to be very inefficient

A: Just for here above
if (name == "VoorzieningBerging")
        error = double.TryParse(val.ToString(), out result) ? null : "error";

If you want to suppress inputting double value you can handle PreviewTextInput event where you set object of EventArgs(e.Handled) to true if double came along.
 private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        double result;
        if (double.TryParse(((TextBox)sender).Text, out result))
            e.Handled = true;
    }

For many check this out
  <TextBox>
        <TextBox.Text>
            <Binding Path="Name" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <local:Validation2/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

public class Validation2 : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        double result;
        return double.TryParse(value.ToString(), out result) == true ? new ValidationResult(true, null) : new ValidationResult(false, "error");
    }
}

Comprehensive information may be found here


text:
Q: Improving upload speed by sending chunk of bytes I'm developing an android video uploading app and uploading large amounts of video is a problem, I get different type of exception sometimes (host not resolved, pipe broken), I do a multipart POST but I have a feeling if I upload chunk of bytes one at at time that'll increase upload speed as well as solve connection timeout and these type of problems.

A: If you have control of the server, think about using raw TCP/IP via sockets instead of http: http adds considerable overhead. In some circumstances, going down to the udp layer instead can improve performance even further: but be aware of the complexity of ensuring delivery and sequencing yourself.


text:
Q: TS stating that test() is not a property on a string? I have a simple RegEx pattern test that I'd like to run on a string; you can see this in the example below as the variable part.

When I do this, however, the red-squiggly line is indicating the error of:

Property 'test' does not exist on type 'string'.ts(2339)

I am using TS 3.2.2 and my tsconfig.json is rather unexciting:
{
  "compilerOptions": {
    "declaration": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es2017",
    "noImplicitAny": true,
    "outDir": "./lib",
    "preserveConstEnums": true,
    "removeComments": true,
    "typeRoots": ["./node_modules/@types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/*-spec.ts"]
}

Can anyone help me understand this? Clearly test IS a property on string!

A: Put it on chrome console and you will get this:

but you can do this:
if( /\s+-\s+-[0-9]/.test(part) ) return part;


text:
Q: Write the required code to create a dynamic one dimensional integer array I'm not sure how to answer this question or what it ask exactly for.

Q:Write the required code to create a dynamic one dimensional integer
  array.

So does it ask just to make dynamic 1D array like this:
new int [5]
or
new int [size]

or it ask for another answer like this one:
int size = 5;

int *ptr;

ptr = new int[size];

Thank you.

A: A vector is what you want.
#include <vector>
// some stuff
std::vector<int> A(size);


text:
Q: ignoring return value of 'scanf', declared with attribute warn_unused_result [-Wunused-result] -> scanf ("%d", &x); por favor podrían indicarme porque persiste el error si el scanf está validado. El error me da cuando uso libreria 'mpi'. Este es mi código:
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

int insertminimo ();

int main(int argc, char *argv[])
{
    int myid, numproc;
    int mystart, myend;
    int n = 100;

    /* Inicializa */
    MPI_Init(&argc, &argv);

    /* conseguir rank y # de procesadores size */
    MPI_Comm_size(MPI_COMM_WORLD,&numproc);
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);

    int minimo;
    minimo = insertminimo ();

    /*Aqui va el resto de MPI ....*/
    return 0;
}
int insertminimo ()
{
        int x;
        printf ("Cuál es la longitud mínima?\n=> ");
        //scanf ("%d", &x);
        if (scanf("%d", &x) != 1)
        {
           fprintf( stderr, "Previsto el ingreso de longitud mínima como entrada\n");
           exit(1);
        }

        if(x <=-1)
        {
            printf("\n\n**El numero insertado excede la capacidad,"
                    "por favor ingrese la longitud mínima mayor a cero**\n\n");
            printf ("Cuál es la longitud mínima?\n");
            scanf ("%d", &x);
        }

        return x;
}

A: El mismo mensaje de error lo indica, el valor de retorno de scanf() no debe ser ignorado, esto es por el compilador, podrías trata validando:
...
...
if(x <=-1)
    {
     printf("\n\n**El numero insertado excede la capacidad, por favor ingrese la longitud mínima mayor a cero**\n\n");
     printf ("Cuál es la longitud mínima?\n");
    if (scanf("%d", &x) <= 0) {
        printf("%d", x);
    } else {
        printf("valor de longitud mínima es incorrecto.\n");
    }
}

return x;
...
...


text:
Q: MongoDb C# driver - serializing List as string[] I have a class with a property of type List<SomeEnum>. Something like this:
public enum MyEnum
{
  A,
  B
}

public class MyClass
{
    public string Id { get; set; }
    public List<MyEnum> Values { get; set; }
}

I'm already using the EnumRepresentationConvention in this way:
ConventionRegistry.Register("EnumStringConvention", new ConventionPack { new EnumRepresentationConvention(BsonType.String) }, t => true);

Still, the Values property gets serialized as an array of ints (simple enum properties are correctly handled as ints). It seem the convention is not used in the context of the list serialization.
How can I enforce the serializer to write strings instead of ints?

A: Instead of calling ConventionRegistry.Register(), add data annotation [BsonRepresentation(BsonType.String)] to the property Values of MyClass.
public class MyClass
{
    public string Id { get; set; }

    [BsonRepresentation(BsonType.String)]
    public List<MyEnum> Values { get; set; }
}

After that change collection.InsertOne(obj); is saving this:
{
    "_id" : "1",
    "Values" : [
        "A",
        "B"
    ]
}

A: Alas this PR has been closed as won't fix. https://github.com/mongodb/mongo-csharp-driver/pull/305#issuecomment-731475503.
Good reasons are given for this, but it is the kind of thing that I think people want to do, so depending on your appetite for jumping through hoops you can try this (.NET 5):
using System;
using System.Collections.Generic;
using System.Reflection;

using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;

public sealed class EnumWrapper<TEnum>
    where TEnum : struct, Enum
{
    [BsonConstructor]
    public EnumWrapper(TEnum value) => this.Value = value;

    public TEnum Value { get; }

    public static readonly IBsonSerializer<EnumWrapper<TEnum>> Serializer = new BsonSerializerImpl();

    public static implicit operator TEnum(EnumWrapper<TEnum> wrapper) => wrapper.Value;

    public static implicit operator EnumWrapper<TEnum>(TEnum value) => new(value);

    public override bool Equals(object obj) =>
        obj is EnumWrapper<TEnum> wrapper
        && EqualityComparer<TEnum>.Default.Equals(this.Value, wrapper.Value);

    public override int GetHashCode() => HashCode.Combine(this.Value);

    public override string ToString() => this.Value.ToString();

    private class BsonSerializerImpl : IBsonSerializer<EnumWrapper<TEnum>>
    {
        public Type ValueType => typeof(EnumWrapper<TEnum>);

        public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, EnumWrapper<TEnum> value) =>
            context.Writer.WriteString(((TEnum)value).ToString());

        public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value) =>
            this.Serialize(context, args, (EnumWrapper<TEnum>)value);

        object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) =>
            this.Deserialize(context, args);

        public EnumWrapper<TEnum> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) =>
            Enum.Parse<TEnum>(context.Reader.ReadString());
    }
}

public class EnumWrapperBsonSerializationProvider : IBsonSerializationProvider
{
    public IBsonSerializer GetSerializer(Type type)
    {
        if (!type.IsGenericType)
        {
            return null;
        }

        var typeDefinition = type.GetGenericTypeDefinition();
        if (typeDefinition != typeof(EnumWrapper<>))
        {
            return null;
        }

        var field = type.GetField(nameof(EnumWrapper<Hack>.Serializer), BindingFlags.Public | BindingFlags.Static);
        return (IBsonSerializer)field.GetValue(null);
    }

    private enum Hack { }
}

Now you can use EnumWrapper<TEnum> mostly wherever you would normally use TEnum and it will do what you want. If you don't register the serialization provider it will serialize as nested objects, so before doing anything you should call this:
BsonSerializer.RegisterSerializationProvider(new EnumWrapperBsonSerializationProvider());


text:
Q: Can't get ag-grid to display I have a basic ag-grid with some simple dummy data, but it only displays when I don't import the .css files provided with the library, and even then it displays incorrectly.
Excerpted from my package.json:
"ag-grid": "10.0.1",
"ag-grid-react": "10.0.0",
"react": "15.4.2"

From my React component:
constructor:
this.state = { columnDefs: [{headerName: 'Product', field: 'product'},{headerName: 'Country', field: 'country'}], rowData: [{product: 'IOL', country: 'US'}, {product: 'Suture', country: 'IN'}]}

from render():
return (

            {/*
*/}

                Here's the grid...

            <AgGridReact

                // listen for events with React callbacks
                onGridReady={this.onGridReady.bind(this)}
                // onRowSelected={this.onRowSelected.bind(this)}
                // onCellClicked={this.onCellClicked.bind(this)}

                // binding to properties within React State or Props
                showToolPanel={this.state.showToolPanel}
                quickFilterText={this.state.quickFilterText}
                icons={this.state.icons}

                // column definitions and row data are immutable, the grid
                // will update when these lists change
                columnDefs={this.state.columnDefs}
                rowData={this.state.rowData}

                // or provide props the old way with no binding
                rowSelection="multiple"
                enableSorting="true"
                enableFilter="true"
                rowHeight="22"
            />

)

If I run this code without importing any .css I get a jumbled grid like:

Now if I import the css per the getting started guide:
import 'ag-grid-root/dist/styles/ag-grid.css'  // see webpack config for alias of 'ag-grid-root'
import 'ag-grid-root/dist/styles/theme-fresh.css'

... then no part of the grid displays (only my div before the grid).  With the css imported, it doesn't matter if I have assigned a theme to the grid or not, nothing shows.

A: I had a similar problem with the rows of data not showing, just the pagination. Setting a fixed div height worked to make the rows display, but adding domLayout: 'autoHeight' to the gridOptions means its always the right height to display correctly.


text:
Q: TypeError: Cannot read property 'belongsTo' of undefined I'm trying to Associations many to many, between 2 models "Trainer & Course" so I do third models "CourseTrainer" to try relation 1 to many.
but I'm getting this error:
C:\Users\DELL\Downloads\graphql-12.18.2020\graphql-12.18.2020\graphql-12.18.2020\serverapp\database\database.js:54
db.trainer.belongsTo(db.tblCourseTrainer, {
^
TypeError: Cannot read property 'belongsTo' of undefined
at Object. (C:\Users\DELL\Downloads\graphql-12.18.2020\graphql-12.18.2020\graphql-12.18.2020\serverapp\database\database.js:54:14)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object. (C:\Users\DELL\Downloads\graphql-12.18.2020\graphql-12.18.2020\graphql-12.18.2020\serverapp\graphql\resolvers\user.js:6:12)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
DB Code:
const Sequelize = require('sequelize');
const db = {};
const sequelize =  new Sequelize("firstDB"," "," ", {
  //from the DB amazom
  host: '  ',
    dialect: 'mysql',
    define: {
      timestamps: false,
      freezeTableName: true
    },
    operatorsAliases: false,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
  });

  db.sequelize = sequelize
  db.Sequelize = Sequelize
  db.Sequelize = sequelize
  db.Sequelize = sequelize
  db.Sequelize = sequelize
  db.Sequelize = sequelize
  db.Sequelize = sequelize

  db.tblUser = require("./models/user")(sequelize, Sequelize);
  db.vewStudentCourseTrainer = require("./models/studentCourseTrainer")(sequelize, Sequelize);
  db.tblTrainer = require("./models/trainer")(sequelize, Sequelize);
  db.tblCourse = require("./models/course")(sequelize,Sequelize);
  db.tblStudent = require("./models/student")(sequelize,Sequelize);
  db.tblCourseTrainer = require("./models/courseTrainer")(sequelize, Sequelize);
  db.tblStudentCourse = require("./models/studentCourse")(sequelize, Sequelize);

  db.tblCourseTrainer.hasMany(db.tblTrainer, { as: "trainer" });
  db.trainer.belongsTo(db.tblCourseTrainer, {
    foreignKey: "intTrainerID",
    as: "trainerID",
  });

  module.exports = db

Models code for CourseTrainer
module.exports = (sequelize,DataTypes)=>{
    const CourseTrainer  = sequelize.define("tblCourseTrainer",{
      intCourseTrainerID: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      intCourseID: {
        type: DataTypes.INTEGER,
        foreignKey: true,
    },
    intTrainerID: {
        type: DataTypes.INTEGER,
        foreignKey: true,
    },
},)
    return CourseTrainer
  }

Models code for Trainer
module.exports = (sequelize,DataTypes)=>{
    const Trainer  = sequelize.define("tblTrainer",{
      intTrainerID: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      strTrainerName: {
        type: DataTypes.STRING
    },

    },)
    return Trainer
  }

Models code for Course

module.exports = (sequelize,DataTypes)=>{
    const Course  = sequelize.define("tblCourse",{
      intCourseID: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      strCourseName: {
        type: DataTypes.STRING
    },
    },)
    return Course
  }

A: The problem for me was that I had my belongsTo associations defined in different files.
The solution was to move the associations to the same file where the query was being done. For example
Grid.belongsToMany(Link, { through: GridLink, foreignKey: 'gridId'})
Link.belongsToMany(Grid, { through: GridLink, foreignKey: 'linkId'})

exports.listLinksInGrid = (gridId) => {
  return Grid.findOne({
    where: {
      id: gridId
    },
    include: Link
  });
};

instead of

Grid.belongsToMany(Link, { through: GridLink, foreignKey: 'gridId'})

exports.listLinksInGrid = (gridId) => {
  return Grid.findOne({
    where: {
      id: gridId
    },
    include: Link
  });
};

Link.belongsToMany(Grid, { through: GridLink, foreignKey: 'linkId'})

A: When you call this:
db.trainer.belongsTo(...)

There is no .trainer object in the db object and thus db.trainer is undefined and you get the error telling you that you can't access a property .belongsTo() on an undefined value.
We can see where you declare the db object here:
const db = {};

And, then follow the code down to where you try to do db.trainer.belongsTo(...) and nowhere in there do you define db.trainer.  You do have this:
db.tblTrainer = require("./models/trainer")(sequelize, Sequelize);

so, perhaps you meant to be using this?
db.tblTrainer.belongsTo(...)


text: Q: An Issue with Multiple ASP:Update Panel (Both are updated) I have two update panels in my aspx page. I want to show progress using javascript code. But when I click the triggered button for one specific update panel, both of the update panels are updating. I want just one to be updated when I click button.


text:
Q: MFC / C#.NET mixed mode localization (multi language / multilingual application) we have a complex application here which is written in MFC and C# and running in mixed-mode. We're now trying to set up a multi-lingual version of this application. So I created English resource files (in the .NET part) for every existing resource file and translated all necessary strings. E. g.: MyResource.resx and MyResource.en.resx. Original language is German.
Now if I start the solution containing only the .NET-Projects with the Thread.CurrentThread.CurrentUICulture set to 'en-US' all the dialogs and texts appear in English as expected. The MFC part (the compiled code in the .exe file) is translated with a tool called Lingobit which replaces the strings in that .exe file and it works fine. So far, so good.
But when it comes to start the full mixed-mode application all the English resource files of the .NET part are ignored and it falls back to the German ones.
I additionally tried to use Lingobit to translate the .NET-DLLs. Lingobit creates a separate mylib.resource.dll of my original mylib.dll which seems to be ignored, too.
I'm running out of ideas here how to create an English version of this application. Any suggestion how to make my mixed-mode application use the English resource files?
Thanks in advance.

A: The solution itself was quite simple, but it took me a while to find it. If you compile the .Net project Visual Studio creates a "en"-Folder in your output folder (e. g.: bin/Debug/). This folder is not created with the compilation of the mixed mode version, so just copy it from your .Net output folder to your mixed mode output folder.
In addition I'll create a little script to copy it to the needed location after the build.
Have a good one everybody.


text:
Q: Django/Nginx - 403 on Static Files I've recently uploaded a django project to an Ubuntu 22.04 DigitalOcean droplet. Nginx, gunicorn, and postgres have all been set up without a hitch, but the static files are all being 403'd.
In both development and production, I never used collectstatic. The reason being, I always put all my static files in a static folder in the root of my project, so I figured I didn't have to do it. I'm not sure if collectstatic needs to be done in order for static files to be shown in production, but it seems that other people have still encountered this problem even when they've done collectstatic.
My project on the server is called pyapps, and in that folder there are the static and media folders. The static folder is further broken down into css, js, and images folders. The media folder is further broken down into photos, then folder by year, month, then day, all of which correlate to the time the photos were uploaded.
Below are my settings.py, urls.py and /etc/nginx/sites-available/ files' code.
settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))]

MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py
urlpatterns = [
    ...
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

/etc/nginx/sites-available/Car-terra
server {
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        alias /home/djangoadmin/pyapps/Car-terra/static/;
    }

    location /media/ {
        alias /home/djangoadmin/pyapps/Car-terra/media/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }

server {
    if ($host = www.carterrarfw.online) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
}

    if ($host = carterrarfw.online) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name 146.190.210.138 carterrarfw.online www.carterrarfw.online;
    return 404; # managed by Certbot
}

What I've Tried

*

*chmod 777 on the static folder (in retrospect not a good choice, but it didn't work nonetheless)

*changing root /home/djangoadmin/pyapps/Car-terra; to alias /home/djangoadmin/pyapps/Car-terra/static/ and media;

*changing debug to True just to see if there was a difference (there wasn't)

I'm not sure if this is a problem with collectstatic, or if I'm telling nginx to look in the wrong place.
Is running collectstatic absolutely mandatory?
Thank you for your help.


text:
Q: Failed to login from TTY1 (from recovery mode) cannot execute /bin/bash/: no such file or directory I was trying to install wine to run a Windows program on Ubuntu 20.04. There was a problem installing wine because of dependency packages. I followed some instructions to manually install the dependency packages but while installing the first package (which I don't remember now) I realized that something big/fatal is about to happen in my Ubuntu and I tried to halt the installation. Afterwards my computer took a while trying to shutdown with a message "Unattended upgrade in progress during shutdown, please don't turn off the computer".
When I tried to turn it on again, it didn't boot. I went to the GRUB menu and selected Ubuntu to boot, it leads me to the tty1 terminal and I can't log in from it. I went to the GRUB menu again and tried to open the recovery mode for diagnostics/fixing and this directs me to the tty1 terminal too. When I try to login with my user name and password, I get this message: Cannot execute /bin/bash/: No such file or directory
I don't know what went wrong and I don't know how to fix/diagnose it. What should I do to fix this?


text:
Q: sqlalchemy.exc.OperationalError: stack depth limit exceeded I'm getting a sqlalchemy.exc.OperationalError error when I perform the following query:
    present_keys = self.engine.execute(
        _sql.select(
            [self.table.columns.qid, self.table.columns.did],
            _sql.tuple_(self.table.columns.qid, self.table.columns.did).in_(
                [(row['qid'], row['did']) for row in rows]
            )
        )
    ).fetchall()

The thing is, the query works for small amounts of rows like ~5k, but when I try to run it with around 50~100k I get this error.
I guess the query itself is a really bad way to do what I want. (I'm just checking which rows are already in the database, so I can separate the ones I need to insert from the ones I need to update).
What is my best option to solve this? Make a different query? Increase some kind of setting inside PostgreSQL/psycopg2?


text:
Q: Finding Subgroups Of $S_{15}$
Find subgroups of order 45 and 39 in $S_{15}$

For order of $49$ I know that a permutation in $S_n$ can be written as two disjoint cycles and the order of two disjoint cycles $a,b$ is $lcm(a,b)$
so I am looking for $a,b<15$ such that $lcm(a,b)=45$ now $lcm(a,b)=\frac{a\cdot b}{gcd(a,b)}$ so I should look for $a,b$ such that $gcd(a,b)=1$ and $a\cdot b=45$ which are $5$ and $9$
In this case we can say that $|\langle a \rangle|=o(a)$?
For subgroup of order $39$ the answer is that it can not be as 1. we can not find a cycle of $39$ with $15$ elements 2. there are no $2$ disjoint cycles with $lcm=39$ but how can we conclude this?

A: For order $45$ we can indeed find an element of that order. We take, as you say, disjoint cycles of length $5$ and $9$. (Note that we need $5+9\leqslant 15$ to fit them in. So $$a=(1 2 3 4 5)(6 7 8 9 A B C D E)$$ generate the subgroup we need.
For a subgroup of order $39$ things are less straightforward. The only possibilities for a cyclic subgroup would be to find a $39$ cycle, or to find disjoint $3$ and $13$ cycles: neither will fit into $S_{15}$.
But there is also the possibility of a non-abelian group of order $39$. This has a normal cyclic subgroup of order $13$, generated by $x$, say; extended by a cyclic subgroup of order $3$, generated by $y$ such that $y^{-1}xy=x^3$. [This group exists because $3|(13-1)$.]
So we want to find such a subgroup of $S_{15}$. For a start we can take
$$ x= (1 2 3 4 5 6 7 8 9 A B C D)$$
as all the elements of order $13$ look the same.
Then we have
$$x^{3}= (1 4 7 A D 3 6 9 C 2 5 8 B)$$
and can now read off an appropriate $y$, $$y=(1)(2 4 A)(3 7 6)(5DB)(89C)$$
to give our required subgroup $\langle x, y\rangle$.


text:
Q: Integrate between Shelly and Telegram via Webhook I have tried to integrate between Shelly and Telegram.
In Telegram there is an option called webhook that mean , if Telegram bot received an message that message will automatically move to another server :
To open my Shelly relay I can send a POST ( doc ):
curl -X POST https://shelly-54-eu.shelly.cloud/device/relay/control -d "channel=0&turn=on&id=<Shelly_id>&auth_key=<Shelly_auth_key>"

I tried to implement with wehbook a redirection for Shelly cloud , so when my telegram bot received an message my Shelly will open the relay.
I have tried set set the webhook like that :
curl -X POST https://api.telegram.org/bot<telegam_bot_token>/setWebhook --data-urlencode "url=https://shelly-54-eu.shelly.cloud/device/relay/control?channel=0&turn=on&id=<Shelly_id>&auth_key=<Shelly_auth_key>"

But When I watch at getWebhookInfo URL :
https://api.telegram.org/bot<Tlegram_token>/getWebhookInfo:
I saw :
{"ok":true,"result":{"url":"https://shelly-54-eu.shelly.cloud/device/relay/control?channel=0&turn=on&id=<Shelly_id>&auth_key=<Shelly_auth_key>","has_custom_certificate":false,"pending_update_count":5,"last_error_date":1670102630,"last_error_message":"Wrong response from the webhook: 401 Unauthorized","max_connections":40,"ip_address":"<Shelly_ip>"}}

.
If I replace --data-urlencode with -d :
curl -X POST https://api.telegram.org/bot<telegam_bot_token>/setWebhook -d "url=https://shelly-54-eu.shelly.cloud/device/relay/control?channel=0&turn=on&id=<Shelly_id>&auth_key=<Shelly_auth_key>"

So https://api.telegram.org/bot<Tlegram_token>/getWebhookInfo return
{"ok":true,"result":{"url":"https://shelly-54-eu.shelly.cloud/device/relay/control?channel=0","has_custom_certificate":false,"pending_update_count":1,"last_error_date":1670263360,"last_error_message":"Wrong response from the webhook: 401 Unauthorized","max_connections":40,"ip_address":"<Shelly_ip>"}}

Apparently the problem is that Shelly server expected to get  channel=0&turn=on&id=<Shelly_id>&auth_key=<Shelly_auth_key> as "data" and not through URL ,
Is there any way to pass this data using Telegram webhook?


text:
Q: Indexing for BINARY LIKE operations in MySQL I know that varchar_pattern_ops exists in Postgresql for fast, index-based searches in a LIKE query, but is there any similar functionality for MySQL?
I currently have a Django-MySQL setup where I have this query which runs on a non-indexed field and with a BINARY LIKE operation, and it takes over a minute to complete.
My query is a partial search from the beginning of the text - text%.
This is the table structure. The table actually contains over 20 fields, but I've included just the primary key and the field I'm searching on
+---------+---------------+------+-----+---------+-------+

| Field   | Type          | Null | Key | Default | Extra |

+-------------------------+---------------+------+-----+--

| id      | varchar(255)  | NO   | PRI | NULL    |       |

| mid     | varchar(255)  | NO   | MUL | NULL    |       |

And this is the query -
select count(*) from table where mid binary like 'text%';

These are the indexes -
PRIMARY KEY index has cardinality 102820460
mid index has cardinality 756032

A: Do the fact that   MySQL indexes the left side of a string.
Then a string column can use the index if the query use wildcard right side :
 SELECT * FROM your_table WHERE field LIKE "text%" # can use an index

but remember that for index there is a limit of 767 bytes
From Mysql DOC

A B-tree index can be used for column comparisons in expressions that
  use the =, >, >=, <, <=, or BETWEEN operators. The index also can be
  used for LIKE comparisons if the argument to LIKE is a constant string
  that does not start with a wildcard character.

https://dev.mysql.com/doc/refman/8.0/en/index-btree-hash.html


text:
Q: I want to upload audio files into S3 bucket using python api I want to upload files to S3 bucket and download files from S3 bucket using python api connected to html pages

A: There is a library for this 'boto3', that upload files in S3. For quick setup of boto3 follow:
boto3 quickstart
To upload a file :
import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file('filename', 'bucketname', 'desired filename in s3')


text:
Q: Allowing Hindi fonts in html text area I have a desktop application in java that converts from literal hindi text to corresponding english translitration. I am using jTextArea in desktop application. Now I want to make a web application for doing the same. My end goal is to have two text areas in html in one of which I can type hindi characters and in other one would show translitration result in english characters at the same time. For Hindi I want to use kruti dev font and Times new roman for english.

A: Take a look at Cufon: http://cufon.shoqolate.com/generate/
Keep in mind any license issues regarding font usage before making use of a font.
If you want a safe approach, try and find a font you're happy with here: https://www.google.com/fonts


text:
Q: How to assign the value passed to a bootstrap modal dialogue to php variable? I am passing value to a bootstarp modal form like this -
echo '<a data-toggle="modal" data-id="ISBN564541" data-toggle="modal" title="Add this item" class="open-AddBookDialog" href="#addBookDialog">';
javascript:
<script>
 $(document).on("click", ".open-AddBookDialog", function () {
 var myBookId = $(this).data('id');
 $(".modal-body #bookId").val( myBookId );
 $('#addBookDialog').modal('show');
});
</script>

And receiving it in a text area like this -
echo '<textarea name="bookId" id="bookId"></textarea>';
Now my question is how to get this value into a php variable say $receivedValue?

A: You have to POST it to your PHP script using AJAX-request or plain form submission.

A: The only way that I can think about is to use post or get method threw the '$.ajax' method.
Here is the code that you need:
.ajax({
    url : "URL of the php script",
    type: "POST",
    data : //The data that you want to pass
    success: function(res)
    {
         //code if everything passed fine
     }
     });


text:
Q: First and last facets using facet_wrap with ggplotly are larger than middle facets Using sample data:
library(tidyverse)
library(plotly)

myplot <- diamonds %>% ggplot(aes(clarity, price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, ncol = 8, scales = "free", strip.position = "bottom") +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())

ggplotly(myplot)

Returns something like:

Where the inside facets are horribly scaled compared to the first and last and there is a lot of extra padding. I tried to find a solution from these questions:
ggplotly not working properly when number are facets are more
R: facet_wrap does not render correctly with ggplotly in Shiny app
With trial and error I used panel.spacing.x = unit(-0.5, "line") in theme() and it looks a bit better, with a lot of the extra padding gone, but the internal facets are still noticeably smaller.

Also as an extra question but not as important, the strip labels are the top in the ggplotly() call, when I set them at the bottom. Seems like an ongoing issue here, does anyone have a hacky workaround?
Edit: in my real dataset I need y-axis labels for each of the facets as their scales are quite different so I kept them in the example and is why I need facet_wrap. Screenshot of my real dataset for explanation:

A: Updated answer (2): just use fixfacets()
I've put together a function fixfacets(fig, facets, domain_offset) that turns this:

...by using this:
f <- fixfacets(figure = fig, facets <- unique(df$clarity), domain_offset <- 0.06)
...into this:

This function should now be pretty flexible with regards to number of facets.
Complete code:
library(tidyverse)
library(plotly)

# YOUR SETUP:

df <- data.frame(diamonds)

df['price'][df$clarity == 'VS1', ] <- filter(df['price'], df['clarity']=='VS1')*2

myplot <- df %>% ggplot(aes(clarity, price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, scales = 'free', shrink = FALSE, ncol = 8, strip.position = "bottom", dir='h') +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())
fig <- ggplotly(myplot)

# Custom function that takes a ggplotly figure and its facets as arguments.
# The upper x-values for each domain is set programmatically, but you can adjust
# the look of the figure by adjusting the width of the facet domain and the
# corresponding annotations labels through the domain_offset variable
fixfacets <- function(figure, facets, domain_offset){

  # split x ranges from 0 to 1 into
  # intervals corresponding to number of facets
  # xHi = highest x for shape
  xHi <- seq(0, 1, len = n_facets+1)
  xHi <- xHi[2:length(xHi)]

  xOs <- domain_offset

  # Shape manipulations, identified by dark grey backround: "rgba(217,217,217,1)"
  # structure: p$x$layout$shapes[[2]]$
  shp <- fig$x$layout$shapes
  j <- 1
  for (i in seq_along(shp)){
    if (shp[[i]]$fillcolor=="rgba(217,217,217,1)" & (!is.na(shp[[i]]$fillcolor))){
       #$x$layout$shapes[[i]]$fillcolor <- 'rgba(0,0,255,0.5)' # optionally change color for each label shape
       fig$x$layout$shapes[[i]]$x1 <- xHi[j]
       fig$x$layout$shapes[[i]]$x0 <- (xHi[j] - xOs)
       #fig$x$layout$shapes[[i]]$y <- -0.05
       j<-j+1
    }
  }

  # annotation manipulations, identified by label name
  # structure: p$x$layout$annotations[[2]]
  ann <- fig$x$layout$annotations
  annos <- facets
  j <- 1
  for (i in seq_along(ann)){
    if (ann[[i]]$text %in% annos){
       # but each annotation between high and low x,
       # and set adjustment to center
       fig$x$layout$annotations[[i]]$x <- (((xHi[j]-xOs)+xHi[j])/2)
       fig$x$layout$annotations[[i]]$xanchor <- 'center'
       #print(fig$x$layout$annotations[[i]]$y)
       #fig$x$layout$annotations[[i]]$y <- -0.05
       j<-j+1
    }
  }

  # domain manipulations
  # set high and low x for each facet domain
  xax <- names(fig$x$layout)
  j <- 1
  for (i in seq_along(xax)){
    if (!is.na(pmatch('xaxis', lot[i]))){
      #print(p[['x']][['layout']][[lot[i]]][['domain']][2])
      fig[['x']][['layout']][[xax[i]]][['domain']][2] <- xHi[j]
      fig[['x']][['layout']][[xax[i]]][['domain']][1] <- xHi[j] - xOs
      j<-j+1
    }
  }

  return(fig)
}

f <- fixfacets(figure = fig, facets <- unique(df$clarity), domain_offset <- 0.06)
f

Updated answer (1): How to handle each element programmatically!
The elements of your figure that require some editing to meet your needs with regards to maintaining the scaling of each facet and fix the weird layout, are:

*

*x label annotations through fig$x$layout$annotations,

*x label shapes through fig$x$layout$shapes, and

*the position where each facet starts and stops along the x axis through fig$x$layout$xaxis$domain
The only real challenge was referincing, for example, the correct shapes and annotations among many other shapes and annotations. The code snippet below will do exatly this to produce the following plot:

The code snippet might need some careful tweaking for each case with regards to facet names, and number of names, but the code in itself is pretty basic so you shouldn't have any problem with that. I'll polish it a bit more myself when I find the time.
Complete code:
ibrary(tidyverse)
library(plotly)

# YOUR SETUP:

df <- data.frame(diamonds)

df['price'][df$clarity == 'VS1', ] <- filter(df['price'], df['clarity']=='VS1')*2

myplot <- df %>% ggplot(aes(clarity, price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, scales = 'free', shrink = FALSE, ncol = 8, strip.position = "bottom", dir='h') +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())
#fig <- ggplotly(myplot)

# MY SUGGESTED SOLUTION:

# get info about facets
# through unique levels of clarity
facets <- unique(df$clarity)
n_facets <- length(facets)

# split x ranges from 0 to 1 into
# intervals corresponding to number of facets
# xHi = highest x for shape
xHi <- seq(0, 1, len = n_facets+1)
xHi <- xHi[2:length(xHi)]

# specify an offset from highest to lowest x for shapes
xOs <- 0.06

# Shape manipulations, identified by dark grey backround: "rgba(217,217,217,1)"
# structure: p$x$layout$shapes[[2]]$
shp <- fig$x$layout$shapes
j <- 1
for (i in seq_along(shp)){
  if (shp[[i]]$fillcolor=="rgba(217,217,217,1)" & (!is.na(shp[[i]]$fillcolor))){
     #fig$x$layout$shapes[[i]]$fillcolor <- 'rgba(0,0,255,0.5)' # optionally change color for each label shape
     fig$x$layout$shapes[[i]]$x1 <- xHi[j]
     fig$x$layout$shapes[[i]]$x0 <- (xHi[j] - xOs)
     j<-j+1
  }
}

# annotation manipulations, identified by label name
# structure: p$x$layout$annotations[[2]]
ann <- fig$x$layout$annotations
annos <- facets
j <- 1
for (i in seq_along(ann)){
  if (ann[[i]]$text %in% annos){
     # but each annotation between high and low x,
     # and set adjustment to center
     fig$x$layout$annotations[[i]]$x <- (((xHi[j]-xOs)+xHi[j])/2)
     fig$x$layout$annotations[[i]]$xanchor <- 'center'

     j<-j+1
  }
}

# domain manipulations
# set high and low x for each facet domain
lot <- names(fig$x$layout)
j <- 1
for (i in seq_along(lot)){
  if (!is.na(pmatch('xaxis', lot[i]))){
    #print(p[['x']][['layout']][[lot[i]]][['domain']][2])
    fig[['x']][['layout']][[lot[i]]][['domain']][2] <- xHi[j]
    fig[['x']][['layout']][[lot[i]]][['domain']][1] <- xHi[j] - xOs
    j<-j+1
  }
}

fig

Initial answers based on built-in functionalities

With many variables of very different values, it seems that you're going to end up with a challenging format no matter what, meaning either

*

*facets will have varying width, or

*labels will cover facets or be too small to be readable, or

*the figure will be too wide to display without a scrollbar.

So what I'd suggest is rescaling your price column for each unique clarity and set scale='free_x. I still hope someone will come up with a better answer. But here's what I would do:
Plot 1: Rescaled values andscale='free_x

Code 1:
#install.packages("scales")
library(tidyverse)
library(plotly)
library(scales)

library(data.table)
setDT(df)

df <- data.frame(diamonds)

df['price'][df$clarity == 'VS1', ] <- filter(df['price'], df['clarity']=='VS1')*2

# rescale price for each clarity
setDT(df)
clarities <- unique(df$clarity)
for (c in clarities){
  df[clarity == c, price := rescale(price)]
}

df$price <- rescale(df$price)

myplot <- df %>% ggplot(aes(clarity, price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, scales = 'free_x', shrink = FALSE, ncol = 8, strip.position = "bottom") +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())

p <- ggplotly(myplot)
p

This will of course only give insight into the internal distribution of each category since the values have been rescaled. If you want to show the raw price data, and maintain readability, I'd suggest making room for a scrollbar by setting the width large enough.
Plot 2: scales='free' and big enough width:

Code 2:
library(tidyverse)
library(plotly)

df <- data.frame(diamonds)

df['price'][df$clarity == 'VS1', ] <- filter(df['price'], df['clarity']=='VS1')*2

myplot <- df %>% ggplot(aes(clarity, price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, scales = 'free', shrink = FALSE, ncol = 8, strip.position = "bottom") +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())

p <- ggplotly(myplot, width = 1400)
p

And, of course, if your values don't vary too much accross categories, scales='free_x' will work just fine.
Plot 3: scales='free_x

Code 3:
library(tidyverse)
library(plotly)

df <- data.frame(diamonds)

df['price'][df$clarity == 'VS1', ] <- filter(df['price'], df['clarity']=='VS1')*2

myplot <- df %>% ggplot(aes(clarity, price)) +
  geom_boxplot() +
  facet_wrap(~ clarity, scales = 'free_x', shrink = FALSE, ncol = 8, strip.position = "bottom") +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())

p <- ggplotly(myplot)
p

A: sometimes it is helpful to consider a different plot altogether if you struggle with the selected plot. It all depends on what it is that you wish to visualise. Sometimes box plots work, sometimes histograms work and sometime densities works.
Here is an example of how a density plot can give you a quick idea of data distribution for many parameters.
library(tidyverse)
library(plotly)
myplot <- diamonds %>% ggplot(aes(price, colour = clarity)) +
  geom_density(aes(fill = clarity), alpha = 0.25) +
  theme(axis.ticks.x = element_blank(),
        axis.text.x = element_blank(),
        axis.title.x = element_blank())


text:
Q: What's the cheapest way to draw horizontal and vertical lines in HTML5/CSS/Js? I'd like to find the cheapest (CPU-wise) way to draw arbitrary-length and -width lines in HTML/CSS/Js. I have a case where my page will render 50-200 lines of this kind on a page in addition to other HTML elements. Approaches that have occured to me are:

*

*SVG. One for a horizontal line, one for a vertical one. Use Javascript to inject and render them by parameters.

*Canvas. One canvas that covers the entire screen with transparent background.

*DIV-tags with border-left/border-top. Abstract through Javascript-methods.

Other suggestions? Which one would perform best? Any compatibility issues with either of these approaches?

A: Quoted from HTML5 Canvas vs. SVG vs. div

*

*SVG is probably better for applications and apps with few items (less than 1000? Depends really)

*Canvas is better for thousands of objects and careful manipulation, but a lot more code (or a library) is needed to get it off the ground.

*HTML Divs are clunky and do not scale, making a circle is only possible with rounded corners, making complex shapes is possible but involves hundreds of tiny tiny pixel-wide divs. Madness ensues.

A lot of DOM objects(thousands range) with events attached is going to be very painful for some machines to handle. Since it's only 200 here, it may not be a problem. Still performance increases when using canvas over SVG and over compositing images using the DOM.

A: For 200 lines? I wouldn't worry about the CPU all that much. This isn't like you're rendering a First Person Shooter or anything.
It depends on context, of course, but the default thought is to use the borders on divs.
If, on the other hand, this is one visual object that can stand on its own, an SVG makes a lot of sense as it is, after all, an image format.
There are a lot of libraries out there for manipulating SVG in the browser. Here's but one: http://snapsvg.io/


text:
Q: Invalid object name error in DbContext subclass I'm building an mvc application and using code first. But when I'm try access the table, the mvc throw this error:
Invalid object name 'dbo.Membro'.

My Context is:
public class JethroContext : DbContext
    {
        public DbSet<Area> Areas { get; set; }
        public DbSet<BaseIgreja> BaseIgrejas { get; set; }
        public DbSet<Igreja> Igrejas { get; set; }
        public DbSet<Celula> Celulas { get; set; }
        public DbSet<Membro> Membros { get; set; }
        public DbSet<Distrito> Distritos { get; set; }
        public DbSet<Setor> Setores { get; set; }
        public DbSet<Usuario> Usuarios { get; set; }
        public DbSet<Ministerio> Ministerios { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

Searching on Google I found the solution, but not worked for me.
Database.SetInitializer<JethroContext>(null);

EDIT I:
Membro class
Public class Membro
{
    public int Id {get;set;}
    public String Name {get;set;}
    public DateTime DateCreate {get;set;}
}

A: Invalid object name 'dbo...'.
I just realised I had the wrong Catalog selected in my Connection string. Master Blunder!!!


text:
Q: Spring 3.2 Test, com.jajway not included as dependency My tests were failing because of a class not found exception on
import com.jayway.jsonpath.InvalidPathException;
within
org.springframework.test.util.JsonPathExpectationsHelper;

Manually adding the jayway dependency to my maven pom removed this error and my test ran as expected.
Have I found a bug, or do I need to add a different spring jar as well as spring test ?

A: In my case
Having test code what contained jsonPath usage:
 mockMvc.perform(get("/api/userDetails").header("Authorization", base64ForTestUser).accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(jsonPath("userName").value("testUser"));

I was getting
java.lang.NoClassDefFoundError: com/jayway/jsonpath/InvalidPathException

and
java.lang.ClassNotFoundException: com.jayway.jsonpath.InvalidPathException

This error was directly caused by lack of such dependencies
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path-assert</artifactId>
    <version>0.8.1</version>
    <scope>test</scope>
</dependency>

A: Adding this dependency worked
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path-assert</artifactId>
    <version>0.8.1</version>
    <scope>test</scope>
</dependency>

If you want to use another version of json-path-assert you can review the following repository:
http://mvnrepository.com/artifact/com.jayway.jsonpath/json-path

A: External dependencies (e.g., JUnit, Mockito, Easy Mock, JayWay, etc.) are not included in Spring, so it is necessary to explicitly add them (Ant/Maven/Ivy dependency, or jar files) to the project's classpath.


text:
Q: search in mysql, php, find all words that contain 'str' What I'm trying to do is to display all possible variations in the table on the screen. If $search = str, to search in the table for every word which contains 'str' in it. I tried a lot of variations to do it, but without success yet. What is wrong, and can i use something like "SELECT * FROM table WHERE * LIKE '[[:<:]]\"$search\"[[:>:]]' " ?
$string = "SELECT * FROM table

WHERE (column1 = '[[:<:]]\"$search\"[[:>:]]')
OR (column2 = '[[:<:]]\"$search\"[[:>:]]')
OR (column3 = '[[:<:]]\"$search\"[[:>:]]')
OR (column4 = '[[:<:]]\"$search\"[[:>:]]')
OR (column6 = '[[:<:]]\"$search\"[[:>:]]')
OR (column7 = '[[:<:]]\"$search\"[[:>:]]')";

Question: find all words that contain 'str'

A: EDIT
First, get all the columns in database who contains $strlike this :
"SELECT * FROM your_table WHERE UPPER(your_field) LIKE UPPER('%" . $str . "%')";
After,
Parse this results to find the $str in words.
Like this :
$explode = explode($results);
Then you use strpos(); and strstr(); combined to match $str in your array
Some function like this :
function getMultiPos($haystack, $needles, $sensitive=true, $offset=0){
    foreach($needles as $needle) {
        $result[$needle] = ($sensitive) ? strpos($haystack, $needle, $offset) : stripos($haystack, $needle, $offset);
    }
    return $result;
}
Source

A: Try to use column1 LIKE '%str%' as condition


text:
Q: Show that $A' \cup B' \cong A'' \cup B''$
Show that if $A' \cong A''$ and $B' \cong B''$, and further $A' \cap B' = \emptyset$ and $A'' \cap B'' = \emptyset$, then $A' \cup B'  \cong A'' \cup B''$

$\cong$ denotes bijection.
Suppose $|A'| = x.$ Then $|A''| = x$ by hypothesis. Similarly, $|B'| = |B''| = y.$ Since $A'$ and $B'$ are disjoint, $|A' \cup B'| = x + y.$ Similarly, $|A''\cup B''| = x + y.$ Thus the conclusion follows.
Does this argument make sense?

A: If $f:A'\to A''$ and $g:B'\to B''$ are bijections then under these conditions the function $h:A'\cup B'\to A''\cup B''$ prescribed by $x\mapsto f(x)$ if $x\in A'$ and $x\mapsto g(x)$ if $x\in B'$ is well defined and is also a bijection.


text:
Q: I want to change jquery function to pure javascript function this code already working but i want to jquery fucntion convert to pure JavaScript

jQuery(document).ready(function($){
  $('.product-addon-add-mattress option').hide();
  $('#pa_bed-size').change(function(){

  var bedSize = $(this).val();

  $('.addon option').each(function() {
      if ($(this).val().indexOf(bedSize) == 0) {
        $(this).show();
      } else {
        $(this).hide();
      }
  })

  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pa_bed-size" class="" name="attribute_pa_bed-size" >
    <option value="">Choose an option</option>
    <option value="single" class="attached enabled">Single</option>
    <option value="small-double" class="attached enabled">Small Double</option>
    <option value="double" class="attached enabled">Double</option>
    <option value="king" class="attached enabled">King</option>
    <option value="super-king" class="attached enabled">Super King</option>
</select>

<select class="addon addon-select" name="addon-2696-add-mattress-0">
    <option value="">Select an option...</option>
    <option>Not Required</option>
    <option  value="single">(Single) 3ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="single">(Single) 3ft Spring Orthopedic Foam Mattress (£185.00)</option>
    <option  value="single">(Single) 3ft Pocket 1000 Mattress (£185.00)</option>
    <option  value="small-double">(Small Double) 4ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="small-double">(Small Double) 4ft Spring Orthopedic Foam Mattress (£185.00)</option>
    <option  value="double">(Double) 4ft6 Spring Memory Foam Mattress (£145.00)</option>
    <option  value="king">(King) 6ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="super">(Super King) 6ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="super">(Super King) 6ft Spring Orthopedic Foam Mattress (£185.00)</option>
</select>

please help me how to change pure javascript and im doing  click the first select box and changing another select box.

A: Check it out:
https://jsfiddle.net/65ysvqb7/
JS Code
 var pa_bed_size = document.getElementById("pa_bed-size");

 pa_bed_size.addEventListener("change", function(){
   var bedSize = pa_bed_size.value;
   var addon_select = document.getElementById("addon_select");

   var addon_options_length = addon_select.options.length;
   for(var i = 0; i < addon_options_length; i++){
     if(addon_select.options[i].value != bedSize){
      addon_select.options[i].disabled =  true;
    }
   }
});

HTML Code:
  <select id="pa_bed-size" class="" name="attribute_pa_bed-size" >
   <option value="">Choose an option</option>
   <option value="single" class="attached enabled">Single</option>
   <option value="small-double" class="attached enabled">Small Double</option>
   <option value="double" class="attached enabled">Double</option>
   <option value="king" class="attached enabled">King</option>
   <option value="super-king" class="attached enabled">Super King</option>
  </select>

 <select class="addon addon-select" id="addon_select" name="addon-2696-add-mattress- 0">
  <option value="">Select an option...</option>
  <option>Not Required</option>
  <option  value="single">(Single) 3ft Spring Memory Foam Mattress (£145.00)</option>
  <option  value="single">(Single) 3ft Spring Orthopedic Foam Mattress (£185.00)
  </option>
  <option  value="single">(Single) 3ft Pocket 1000 Mattress (£185.00)</option>
  <option  value="small-double">(Small Double) 4ft Spring Memory Foam Mattress
 (£145.00)</option>
  <option  value="small-double">(Small Double) 4ft Spring Orthopedic Foam Mattress
 (£185.00)</option>
  <option  value="double">(Double) 4ft6 Spring Memory Foam Mattress (£145.00)</option>
  <option  value="king">(King) 6ft Spring Memory Foam Mattress (£145.00)</option>
  <option  value="super">(Super King) 6ft Spring Memory Foam Mattress (£145.00)
  </option>
  <option  value="super">(Super King) 6ft Spring Orthopedic Foam Mattress (£185.00)
  </option>
  </select>

A: Made a couple tweaks to https://stackoverflow.com/a/60446496 to make it actually work:
https://jsfiddle.net/dcanning/xfghazdu/3/
HTML
<select id="pa_bed-size" class="" name="attribute_pa_bed-size" >
    <option value="">Choose an option</option>
    <option value="single" class="attached enabled">Single</option>
    <option value="small-double" class="attached enabled">Small Double</option>
    <option value="double" class="attached enabled">Double</option>
    <option value="king" class="attached enabled">King</option>
    <option value="super" class="attached enabled">Super King</option>
</select>

<select class="addon addon-select" id="addon_select" name="addon-2696-add-mattress-0">
    <option value="">Select an option...</option>
    <option>Not Required</option>
    <option  value="single">(Single) 3ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="single">(Single) 3ft Spring Orthopedic Foam Mattress (£185.00)</option>
    <option  value="single">(Single) 3ft Pocket 1000 Mattress (£185.00)</option>
    <option  value="small-double">(Small Double) 4ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="small-double">(Small Double) 4ft Spring Orthopedic Foam Mattress (£185.00)</option>
    <option  value="double">(Double) 4ft6 Spring Memory Foam Mattress (£145.00)</option>
    <option  value="king">(King) 6ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="super">(Super King) 6ft Spring Memory Foam Mattress (£145.00)</option>
    <option  value="super">(Super King) 6ft Spring Orthopedic Foam Mattress (£185.00)</option>
</select>

CSS
select option[disabled] {
    display: none;
}

Javascript
var pa_bed_size = document.getElementById("pa_bed-size");

pa_bed_size.addEventListener("change", function(){
   var bedSize = pa_bed_size.value;
   console.log(bedSize);
   var addon_select = document.getElementById("addon_select");

   var addon_options_length = addon_select.options.length;
   for(var i = 0; i < addon_options_length; i++){
   console.log('option:' + addon_select.options[i].value)
    if(addon_select.options[i].value != bedSize){
      addon_select.options[i].disabled =  true;
    } else {
      addon_select.options[i].disabled =  false;
    }
   }
});