text:
Q: manipulation of XML textnode with xslt i want to delete some unwanted text from the following data with xslt
Address>
<Rowinfo>
<LocatorDesignator>Dwelling  (Part Of) Null</LocatorDesignator>
<LocatorName>Flat  - Buena Villa House</LocatorName>
</Rowinfo>
<Rowinfo>
<LocatorDesignator>Flat  - Buena Villa House 1</LocatorDesignator>
<LocatorName>Flat  3a  Anderson's House</LocatorName>
</Rowinfo>
<Rowinfo>
<LocatorDesignator>Offices Unit 2a Funlife Building 02a</LocatorDesignator>
<LocatorName>office Unit 2a   Funlife Building  <LocatorName>
 </Rowinfo>
 </Address>

to produce this
<LocatorDesignator>Dwelling(Part Of)</LocatorDesignator>
<LocatorName>Buena Villa House</LocatorName>

<LocatorDesignator>Flat 1</LocatorDesignator>
<LocatorName> Anderson's House</LocatorName>

<LocatorDesignator>office Unit 2a</LocatorDesignator>
<LocatorName> Funlife Building  <LocatorName>

In Locatorname: Extract

*

*Buena Villa House

*Anderson's House

*Funlife Building
in other words the part in double quotes are to be deleteed :
(row1) "Flat  -" Buena Villa House.
(row2) "Flat  3a"  Anderson's House .
(row3) "office Unit 2a"   Funlife Building.

In Locatordesignator: Delete

*

*NULL

*Buena Villa House

*Funlife Building
in other words the part in double quotes are to be deleted :
(row1) Dwelling  (Part Of) "Null"
(row2) Flat  " Buena Villa House" 1.
(row3) office Unit 2a   "Funlife Building 02a".

A: This complete transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <my:LocatornameDeletes>
  Flat  -
  Flat  3a
  office Unit 2a
 </my:LocatornameDeletes>

 <my:LocatordesignatorDeletes>
  Null
  Buena Villa House
  Funlife Building 02a
 </my:LocatordesignatorDeletes>

 <xsl:variable name="vLocNameDels" select="document('')/*/my:LocatornameDeletes/*"/>
 <xsl:variable name="vLocDesDels" select="document('')/*/my:LocatordesignatorDeletes/*"/>
 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="LocatorName/text()">
  <xsl:call-template name="makeDeletes">
   <xsl:with-param name="pDeletes" select="$vLocNameDels"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template match="LocatorDesignator/text()">
  <xsl:call-template name="makeDeletes">
   <xsl:with-param name="pDeletes" select="$vLocDesDels"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="makeDeletes">
  <xsl:param name="pText" select="."/>
  <xsl:param name="pDeletes"/>

  <xsl:variable name="vDelText" select="$pDeletes[contains($pText, .)][1]"/>
  <xsl:if test="$vDelText">
   <xsl:variable name="vRough">
     <xsl:value-of select="substring-before($pText, $vDelText)"/>
     <xsl:value-of select="substring-after($pText, $vDelText)"/>
   </xsl:variable>

   <xsl:value-of select="normalize-space($vRough)"/>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on (the corrected for malformedness) provided XML document:
<Address>
    <Rowinfo>
        <LocatorDesignator>Dwelling  (Part Of) Null</LocatorDesignator>
        <LocatorName>Flat  - Buena Villa House</LocatorName>
    </Rowinfo>
    <Rowinfo>
        <LocatorDesignator>Flat  - Buena Villa House 1</LocatorDesignator>
        <LocatorName>Flat  3a  Anderson's House</LocatorName>
    </Rowinfo>
    <Rowinfo>
        <LocatorDesignator>Offices Unit 2a Funlife Building 02a</LocatorDesignator>
        <LocatorName>office Unit 2a   Funlife Building  </LocatorName>
    </Rowinfo>
</Address>

produces the wanted, correct result:
<Address>
   <Rowinfo>
      <LocatorDesignator>Dwelling (Part Of)</LocatorDesignator>
      <LocatorName>Buena Villa House</LocatorName>
   </Rowinfo>
   <Rowinfo>
      <LocatorDesignator>Flat - 1</LocatorDesignator>
      <LocatorName>Anderson's House</LocatorName>
   </Rowinfo>
   <Rowinfo>
      <LocatorDesignator>Offices Unit 2a</LocatorDesignator>
      <LocatorName>Funlife Building</LocatorName>
   </Rowinfo>
</Address>

Explanation:

*

*The strings to be deleted in the text-node children of LocatorName are provided in the global-level element my:LocatornameDeletes.

*The strings to be deleted in the text-node children of LocatorDesignator are provided in the global-level element my:LocatordesignatorDeletes.

*The identity rule copies "as-is" every node for which it is selected for execution.

*There are two templates that overide the identity template -- one matching LocatorName/text() and the other matching LocatorDesignator/text(). Each of these templates simply calls the makeDeletes template, passing it as parameter the correct node-set containing the substrings to be deleted.

*The makeDeletes template performs the actual "deletion of the substrings that are passed in its $pDeletes parameter. This is done using a combination of the standard XPath functions substring-before() and substring-after() .

A: You can use these string functions in XSLT 1.0 to achieve your goals:

*

*contains()

*substring()

*substring-before()

*substring-after()

Google the function names together with XSLT to get the specification for each function.
If you can upgrade to XSLT 2.0, I would definitely recommend it. In XSLT 2.0, you will be able to use regex to achieve your goals much simpler.
Example
With this input document...
<t>
 <row>"Flat  -" Buena Villa House.</row>
 <row>"Flat  3a"  Anderson's House .</row>
 <row>"office Unit 2a"   Funlife Building.</row>
</t>

...when this XSLT 1.0 style-sheet is applied to said document, will remove the double-quoted text fragments...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
 <t>
   <xsl:apply-templates select="*/row"/>
 </t>
</xsl:template>

<xsl:template match="row">
 <row>
  <xsl:call-template name="remove-quoted-bit">
    <xsl:with-param name="raw-text" select="." />
  </xsl:call-template>
 </row>
</xsl:template>
<xsl:template name="remove-quoted-bit">
  <xsl:param name="raw-text" />
  <xsl:choose>
    <xsl:when test="contains($raw-text,'"')">
      <xsl:value-of select="concat(
        substring-before($raw-text,'"'),
        substring-after( substring-after($raw-text,'"'),'"')
        )" />
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$raw-text" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

</xsl:stylesheet>

...and produce this output...
<t>
  <row> Buena Villa House.</row>
  <row>  Anderson's House .</row>
  <row>   Funlife Building.</row>
</t>

Update
Grammar edited.


text:
Q: Interpretation of partial eta-squared in factorial designs I'm having troubles interpreting and comparing effect sizes in factorial designs based on partial eta squared values. E.g. in a 3x3-within-subjects design with:

*

*η²part, A = .2

*η²part, B = .4

*η²part, AxB = .1,

can it be concluded that:
Effect of Factor A is half (or twice) as strong on DV as Effect of Factor B (respectively Effect of Interaction)? How can this results be reported? I'm having cases where Factor A accounts for more percentage of total variance (in terms of generalized η²), so its kind of hard to comprehend for me.
I appreciate any help on how to get that together. Thank you very much on this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ getting only the middle part of data from an array I have an array like this:
string dates [5] = { "15-JAN-17", "15-JAN-17", "17-JAN-17",
                  "04-FEB-17", "04-FEB-17" };

string startDate = "15-JAN-17";
string endDate   = "04-FEB-17";

Is there a way to get the data in between the start date and end date? What I need to get is this:
"15-JAN-17", "17-JAN-17", "04-FEB-17"

I plan to use a for loop to do the search, and I will put all the results into another array called chosenDates. How can I get this result and also since there will be duplicated dates, how can I ensure that the program starts taking from the first result and ends at the last result as provided by startDate and endDate?
EDIT: I should also mention that even if the array gets larger, the dates will always be sorted.

A: Given the sorts of operations you're planning on performing on these strings, I think it makes the most sense to define some new custom type to represent dates. The constructor would parse the date string into an explicit year, month, and day, and you could provide read access to each field. Once you've done that, you could overload the relational operators on your date type so that you can compare and order dates into ascending order.
Once you have something like that, you have a number of options about how to proceed. One approach would be to throw everything into a std::set, which automatically eliminated duplicates and maintains sorted order, which would let you execute range queries like this:
std::set<Date> dates = /* ... */
for (auto itr = dates.lower_bound(Date{"15-JAN-17"}),
     end = dates.upper_bound(Date{"04-FEB-17"});
    itr != end; ++itr) {
    // Use *itr
}

You could also stash everything in a std::vector use std::unique to remove duplicates, then use std::lower_bound and std::upper_bound to select the range you'd like to work with.


text:
Q: Captcha insert from subfolder How can I insert generated captcha image from subfolder? In index.php there is include login.php and this login.php contains an insertion to display captcha image:

    <?php echo '<images src="captcha.php?w=110&h=40&c=6" >'; ?>
    <input type="text" name="captcha" />

The captcha.php generates the image, and if I call this php direct it displays the image. If I place all file next to index.php it works great, but I want separate all file in core folder except index.php.

A: You're referencing the file in an absolute location.  Use the relative path instead, then all files that use this code will adjust according to server rules instead of their geographical location.
So instead of
src="captcha.php..."

use
src="/root/path/captcha.php..."

with /root/path/ of course being wherever your documents are on the server relative to your $_SERVER['DOCUMENT_ROOT']


text:
Q: Please help me to write the function drawing code Please help me to write the function drawing code

*

*polynomial function f(x) = x^3 – 5*x.

*polynomial function f(x,y) = x^3 – 5*y^2.

A: pgfplot code for the first function to start:
\documentclass[border=3.14cm]{standalone}

\usepackage{pgfplots}

\begin{document}

    \begin{tikzpicture}
        \begin{axis}[xmin=-6,xmax=6,domain=-5:5]
            \addplot[red] {x^2 - 5*x };
        \end{axis}
    \end{tikzpicture}
\end{document}


text: Q: I created one transient model and wizard but not able to create a cron to clear data from transient model I try to find in schedule actions triggers in technical menu but it is not there...and also not able to create a new cron that can do the same.


text:
Q: how to clear the textbox text on page load in asp .net I need to clear the textbox text after page load when i run my application i will see a login page but the password is displayed in the form of dots and after getting logged out again it appears as dots i should display it empty instead of showing dots and this happens only for password text box i tried in many ways by taking txtpassword.text=""; in page load also i did txtpassword.text=string.empty; but nothing works for me how can i do this
<asp:TextBox ID="txtpassword" runat="server"  Width="180px" Height="20px"></asp:TextBox>


text:
Q: Ionic 4 custom environment file I am working with Ionic 4 project. I have different environments(test, testB, prob, dev ecc..). I have created all the file inside the environment folder: environment.dev.ts, environment.testA.ts, environment.testB.ts etc. Is there any way to set the correct environment while building or serving(on the browser) the project(maybe something like --env=testA like angular?)? Only thing I can find is --prod, which is only for the production environment, but in this case, I have more than 2 environments.

A: You should check your package.json file.
My package.json looks like the following:
  "name": "name",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e",
   "build-prod": "ng build --prod --progress false",
   "build-dev": "ng build --env=dev --aot=true --output-hashing=all --sourcemaps=false --extract-css=true --named-chunks=false --build-optimizer=true --progress false",
   "build-preprod": "ng build --env=preprod --aot=true --output-hashing=all --sourcemaps=false --extract-css=true --named-chunks=false --build-optimizer=true --progress false",
   "build-dev2": "ng build --env=dev2 --aot=true --output-hashing=all --sourcemaps=false --extract-css=true --named-chunks=false --build-optimizer=true --progress false"
},

In angular-cli.json there is an environment key:
"environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts",
    "preprod": "environments/environment.preprod.ts",
    "dev2": "environments/environment.dev2.ts"
  },

In Angular 8 you should check angular.json:
"configurations": {
        "production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "2mb",
              "maximumError": "5mb"
            },
            {
              "type": "anyComponentStyle",
              "maximumWarning": "6kb",
              "maximumError": "10kb"
            }
          ]
        }, "preprod": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.preprod.ts"
            }
          ],
          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "2mb",
              "maximumError": "5mb"
            },
            {
              "type": "anyComponentStyle",
              "maximumWarning": "6kb",
              "maximumError": "10kb"
            }
          ]
        }
      }
    },

A: I resolved after some testing! Solution for Ionic 4:

*

*Create all the files you need with environment variables inside the folder src/environments. Example environment.live.ts, environment.test1.ts, environment.test2.ts, etc

*Update angular.js file in the root folder;
  "configurations": {
       "production": { ... } // already there for production
       // Add for your custon environments files here
       "testA": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.testa.ts" //Name of your file
            }
          ]
       } ... // Do this for every environment on every build you need
  }

*Import environment file inside your project where you need:
import { environment } from '../../environments/environment';

*To pick a different environment while building or serving: ionic serve -- -c=testA same logic for build etc... This will automatically replace the environment file with the correct one, in this case with file related to testA environment.


text:
Q: Why won't Delphi XE2 let me embed a font resource as RCDATA? I would like to embed a .ttf font resource into my EXE and dynamically load it. This particular method expects the resource to be of type RCDATA. So, I go to Project > Resources and Images... press Add..., and pick my .ttf file. The resource type FONT is automatically selected with an identifier of just 1. I change the type to to RCDATA and type in my own resource name.
Problem: When I press Ok I get an error that the identifier of a FONT resource must be a numeric value. But it wasn't FONT type anymore, I had changed it to RCDATA.
How do I get past this problem?

A: (asking and answering together because I'm sure others have seen this problem)
It seems to be just a small bug in the IDE. When you first select your .ttf file in this resource screen, change the type, press Ok without changing the identifier (leave it 1). Then, open the same screen back up, change the identifier to your own, and press Ok. It only works if you close and re-open the Resources and Images screen.
You could of course also write your own .rc file and do everything manually without this screen.

A: Unlike Jerry says, you can simply "load" the font file in the Resources and Images... dialog. Once you selected it, you can change the type to RCDATA (combobox an the lower right) and if you have done that, you can change the name to whatever valid name you choose.
There is no need to close and re-open the dialog.
I tried this in XE2 and in XE7, and it works as expected. The FONT type is merely the default for, well, font files. That can easily be changed in the dialog.
This doesn't look like a bug to me. Just plain default behaviour when you load a font file. Just like there is default behaviour when you load a .pas file in the editor.

If you want to use an .rc file, it is quite easy to generate one in the editor (new text file with extension .rc) and then you can add it to your project. The IDE will take care of the rest. No need to do anything manually there either, except of course editing the .rc file.


text:
Q: Spring @Autowired annotation giving null for dozer mapping Here is my class I am trying to use this annotation and I am getting null for dozerBeanMapper. I also get null for other beans I am trying to use like Jaxb2Mapper, etc
@Service("Transformer")
@Scope("prototype")
public class Transformer {

@Autowired
private Mapper dozerBeanMapper;

public Object testMethod(Object wlpData) throws TransformerException {

    MbrReq destObject = null;

    destObject = dozerBeanMapper.map(request, MbrReq.class);

    return destObject;
}

Here is my configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
   http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<sws:annotation-driven />
<context:component-scan base-package="com.xxxxx.xxxx.srvc.membership,com.xxxxx.xxxx.interact.membership.request,com.xxxxx.membership.ws,com.xxxxxx.srvc.membership.generated,com.xxxxx.xxxx.service.transform" />

<!-- WSDL Exposed as memberService  -->
<bean id="searchMemDemographics" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
    <constructor-arg value="/WEB-INF/schema/MemSvc_Binding_HTTP_V0100.wsdl"/>
</bean>

<bean class="org.dozer.spring.DozerBeanMapperFactoryBean">
    <property name="mappingFiles">
        <list>
            <value>classpath:mapping/dozer-global-configuration.xml</value>
            <value>classpath:mapping/dozer-bean-mappings.xml</value>
        </list>
    </property>
</bean>

 <oxm:jaxb2-marshaller id="marshaller" contextPath="com.xxxxx.srvc.membership" />

 <oxm:jaxb2-marshaller id="reqMarshaller" contextPath="com.xxxxxx.membership.request" />

 <oxm:jaxb2-marshaller id="respMarshaller" contextPath="com.xxxxxx.membership.response" />

In web.xml I have this
   <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
           classpath:spring/membershipApplicationContext.xml
            </param-value>
</context-param>

Anything else I am missing ?

A: Try adding an id to the bean.
<bean id="dozerBeanMapper" class="org.dozer.spring.DozerBeanMapperFactoryBean">


text:
Q: Using repeater, take FK and display column from that table Using a repeater I run through the 'SelectedUtility' table and output where a match is made.
This works fine as it is, however it displays the 'Utility_Id' which is a foreign key to to 'id' in the Utility Table.
I actually want to display the 'name' column inside the Utility table. How Can i do this...
something like <%# Eval("Utility_Id.name") %>
or is it done in code behind...thanks for any response
aspx:
 <asp:Repeater id="rptSelectedUtilities" runat="server">
                <HeaderTemplate>

                            Utility

                </HeaderTemplate>
                <ItemTemplate>

                            <%# Eval("Utility_Id") %>

                </ItemTemplate>
                <FooterTemplate>

                </FooterTemplate>
            </asp:Repeater>

Code behind:
DBData db = new DBDatat();
        List<Select_Utility> SelectedUtility =
            (from SU in db.Select_Utilities
             where SU.Work_Id == 3
             select SU).ToList();

        rptSelectedUtilities.DataSource = SelectedUtility;

rptSelectedUtilities.DataBind();

EDIT:
   DBData db = new DBDatat();
    List<Utility_Company> Utility = new List<Utility_Company>();
    List<Select_Utility> SelectedUtility =
        (from SU in db.Select_Utilities
         join UTL in Utility on SU equals UTL.id
         where SU.Worksite_Id == 3
         select SU).ToList();

    rptSelectedUtilities.DataSource = SelectedUtility;
    rptSelectedUtilities.DataBind();

Throws the error 'the type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'join'
//shouldt the join be to the name..so  join UTL in Utility on SU equals UTL.Name //instead of UTL.id
Also tried join UTL in db.Utility_Companies on SU equals UTL.id...buit same error

SECOND EDIT:
 <%# Eval("Name") %>
throws error:DataBinding: 'Select_Utility' does not contain a property with the name 'Name'.
     DBData db = new DBData();

        List<Select_Utility> SelectedUtility =
            (from SU in db.Select_Utilities
             where SU.Worksite_Id == 3
             select SU).ToList();

        rptSelectedUtilities.DataSource = SelectedUtility;
        rptSelectedUtilities.DataBind();

   List<Utility_Company> Utility = new List<Utility_Company>();
        var query = from u in db.Utility_Companies
                    join su in db.Select_Utilities
                         on u.id equals su.Utility_Id
                    where su.Worksite_Id == 3
                    select u;

        rptSelectedUtilities.DataSource = query.ToList();
        rptSelectedUtilities.DataBind();

A: Query (you should select joined utilities):
DBData db = new DBDatat();
var query = from u in db.Utility
            join su in db.Select_Utilities
                 on u.Id equals su.Utility_Id
            where su.Work_Id == 3
            select u;

rptSelectedUtilities.DataSource = query.ToList();
rptSelectedUtilities.DataBind();

Page (display name of utility):
<%# Eval("Name") %>

A: Use Inner join the foreign table. and select that id .
DBData db = new DBDatat();
        List<Select_Utility> SelectedUtility =
            (from SU in db.Select_Utilities join UTL in Utility on SU equals UTL.Utility_Id
             where SU.Work_Id == 3
             select SU).ToList();


text:
Q: Django Filter - Paginate results I'm using django-filter to output filtered results of my model. No issues there.
Next step is adding a paginator.. though struggling for days now.
views.py:
def funds_overview(request):
 f = FundFilter(request.GET, queryset=Fund.objects.all()).qs
 paginator = Paginator(f, 5)
 page = request.GET.get('page')
 funds = paginator.get_page(page)
 return render(request, 'funds/funds.html', {'filter': funds})

funds.html:
<form method="get">

Search Criteria

    {{ filter.form.fund_name.label_tag }}
    {% render_field filter.form.fund_name class="form-control" %}

<button type="submit" class="btn btn-primary">
   Search
</button>

{% for fund in filter.qs %}

{{fund.name}}

{% empty %}

No funds match your search criteria

{% endfor %}

Result in the browser
The line "no funds match your search criteria"
..
can anyone help? i assume something is wrong with calling the GET request twice?
Thanks !

A: You're passing a new context where filter is now a page, so when using {% for fund in filter.qs %} your accessing a field that does not exist in a page object, so there will be a empty loop.
Try to change the filter.qs for just filter.
It will solve the pagination problem, but there is another one emerging with the context passed to the render function. As shown below you should add another context variable to keep your page showing the filtered form.
views.py:
def funds_overview(request):
 funds = FundFilter(request.GET, queryset=Fund.objects.all()).qs
 paginator = Paginator(f, 5)
 page = request.GET.get('page')
 fund_page = paginator.get_page(page)
 return render(request, 'funds/funds.html', {'filter': funds, 'page': fund_page})

funds.html:
<form method="get">

Search Criteria

    {{ filter.form.fund_name.label_tag }}
    {% render_field filter.form.fund_name class="form-control" %}

<button type="submit" class="btn btn-primary">
   Search
</button>

{% for fund in page %}

{{fund.name}}

{% empty %}

No funds match your search criteria

{% endfor %}
Page {{ page.number }} of {{ page.paginator.num_pages }}


text:
Q: PHP Text Area to MySQL query variables does not return all row results I am using a text area in order allow searching of multiple items at once and output the results to a table. Everything works fine when only one item is placed into the text area and searched, however the query results of the first line/search item are not returned if more than one item is searched. My code:
<textarea name="search_items" rows="2" cols="30"></textarea>

$input = $_POST['search_items'];
list($pc1, $pc2) = explode("\n", $input);

$desc = mysqli_query($my_connection,"SELECT PART_DESC FROM inventory WHERE PARTCODE = '$pc1' OR PARTCODE = '$pc2';");

$i=1;
while($row_desc = mysqli_fetch_assoc($desc)) {
    ${'pc_desc'.$i} = $row_desc['PART_DESC'];
    $i++;
}

        <?php echo "$pc1"; ?>
        <?php echo $pc_desc1; ?>

        <?php echo "$pc2"; ?>
        <?php echo $pc_desc2; ?>

$pc1 echos out line 1 of the text area and $pc2 echos out line 2 of the text area. I get the correct results echoed out for $pc_desc2 but $pc_desc1 is blank. If I manually assign $pc1 and $pc2 like this:
$pc1 = "ABC";
$pc1 = "XYZ";

both $pc_desc1 and $pc_desc2 return correctly. Please Help!

A: Without fixing your SQL injection problems, you'd be better off using something like this:
...
$parts = explode("\n", $input);
$sql = "SELECT ... PARTCODE IN (" . implode(',', $parts) . ");";
...
while($row_desc = mysqli_fetch_assoc($desc)) {
    $data[$row['PART_CODE']] = $row['PART_DESC'];
}

foreach($data as $code => $desc) {
    echo "
$code	$desc

}

With your code, you have NO guarantee which order the descriptions come back in, and could end up "crossing" things, so you have part #1 with description #2, and part #2 with description #1. The above code guarantees that codes/descriptions are always properly associated together. And also dispenses with dynamic variable names, which make for difficult-/impossible-to-debug code. As well, the above code could handle an arbitrary number of codes, while yours is limited to 2.


text:
Q: multi-field validation I have a simple form with email & password. I want to show the submit button once BOTH the email & password are valid. My thoughts were when I run my handleValidator function I can check some sort of value of the "valid" property for email & "valid" property of pass. How do I access the valid property of an item?
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
            >
<fx:Script>
    import mx.events.ValidationResultEvent;
    private function handleValidator ( eventObj:ValidationResultEvent ):void {

        if( eventObj.type==ValidationResultEvent.VALID
                          // what goes here?????
                          //  && emailValidator.valid = true ?????
                          //  && passValidator.valid = true  ??????

                          ){
            submit.visible = true;
        }
        else {
            submit.visible = false;
        }
    }

</fx:Script>

<fx:Declarations>

    <mx:EmailValidator id="emailValidator" source="{email}" property="text"
                       trigger="{email}" triggerEvent="change"
                       valid="handleValidator(event)" invalid="handleValidator(event)"
                       />
    <mx:StringValidator id="passValidator" source="{pass}" property="text"
                        trigger="{pass}" triggerEvent="change"
                        valid="handleValidator(event)" invalid="handleValidator(event)"
                        minLength="5" maxLength="10"
                        />
</fx:Declarations>
<s:VGroup>

<s:TextInput id="email" />
<s:TextInput id="pass" />
<s:Button id="submit" visible="false" />

</s:VGroup>
</s:Application>

A: Try with something like this. First put your validators into an array:
<mx:Array id="validators">
    <mx:EmailValidator id="emailValidator" source="{email}" property="text">

    <mx:StringValidator id="passValidator" source="{pass}" property="text"
        minLength="5" maxLength="10"/>
</mx:Array>

Add change event handler to both your inputs:
<s:TextInput id="email" change="validate()"/>
<s:TextInput id="pass" change="validate()"/>

Handler will trigger validation:
private function validate():void{
    //validate both your inputs simultaneously
    var errors:Array = Validator.validateAll(validators);
    if (errors.length>0){
        //hide submit button
    }else{
        //show submit button
    }
}

And that's all.

A: I would also go with 2DH for validation, also you can look into following two posts, which I often refer to when it comes to validation.
http://joelhooks.com/2009/02/01/form-validation-for-the-lazy-programmer-in-flex/
This explains the same technique given by 2DH
http:// aralbalkan.com/1125
this one adds a little more functionality for showing error tool tips in a better way.
Hope that helps.

A: in handleValidator , check the event.currentTarget id to find out whether the email or the password has been validated. React accordingly, namely if the email or password is valid, increment a variable , if not valid , dispatch some form of error message to the user.
If both fields are valid, your variable should be equal to the number of fields being validated ( provided that the default value for the variable was 0 ) , you can then show your submit button.


text:
Q: Random Sample by Group and Specific Probability Distribution for Groups I have data set with all dates in 2021 and I would like to create random samples of repeating dates in each month. The distribution of dates within each month should follow a certain pattern that mirrors a specific percentage of day of the week. For example, I would like to generate 1000 dates from January 2021 and approximately 8% or 80 of these days should be Mondays. Please consider the following working example:
dt2021 <-
  tibble(SalesDate = seq.Date(
    ymd("2021-01-01"),
    ymd("2021-12-31"), 1)) %>%
  mutate(
    wkDay=weekdays(SalesDate),
    year=year(SalesDate),
    month=month(SalesDate))
dt2021 %>% glimpse()

dtWkDays <- tibble(
  wkDay=c("Monday", "Tuesday", "Wednesday",
          "Thursday", "Friday", "Saturday",
          "Sunday"),
  Freq=c(0.08, 0.07, 0.09, 0.12, 0.31, 0.32,
         0.01))
dtWkDays

My pseudo script for what I am trying to do would look something like the following:
set.seed(123)
dt2021_01 <- dt2021 %>% filter(month==1) %>%
    # generate a random sample of 1000 dates
    # use the wkday in dtWkDays for the grouping (stratification)
    # use the Freq in dtWkDays for the weights
    # resample = T

If the solution is correct, the following R script should produce around 80 Mondays, 70 Tuesdays, 90 Wednesdays, 120 Thursdays, etc.
dt2021_01 %>% count(wkDay)

I have tried several combinations using slice_sample, sample_frac, and group_by, weight_by, etc., and nothing has generated the correct results for me.

A: I believe this might work. Join the frequency tibble with your date tibble. After filtering for the month of interest, a revised frequency can be calculated based on frequency for day of the week, adjusting for number of times that day of the week appears in that month. Finally, use slice_sample with this new frequency included as weight_by (weights add up to 1, though they otherwise would be standardized to add up to 1 anyways).
library(tidyverse)

set.seed(123)

dt2021 %>%
  filter(month == 1) %>%
  left_join(dtWkDays) %>%
  group_by(wkDay) %>%
  mutate(newFreq = Freq / n()) %>%
  ungroup() %>%
  slice_sample(n = 1000, weight_by = newFreq, replace = TRUE) %>%
  count(wkDay)

Output
  wkDay         n
  <chr>     <int>
1 Friday      312
2 Monday       81
3 Saturday    320
4 Sunday       10
5 Thursday    120
6 Tuesday      62
7 Wednesday    95


text:
Q: Letter Occurrences and Frequency python I need to create a list of letter occurrences from a list of words.
my list of words is    ['song', 'boom', 'pow']
I want to count the letter occurrences in each word and then put them in a list in alphabetical order. If there isn't a letter in my word list that matches each letter in the alphabet, I still want it to print a 0 in the list.
Instead of typing out a string of 26 characters in the alphabet, I am using string.ascii_lowercase
I'm not really sure how to go about doing this.
I then I need to find out the letter occurrences in each word and which word[s] the letter is shown in.
Then output should look like:
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
'o' in 'song', 'boom', 'pow'
etc.

A: The first part can be done like so:
In [12]: seq = ['song', 'boom', 'pow']

In [13]: c = collections.Counter(''.join(seq))

In [14]: [c.get(l, 0) for l in string.ascii_lowercase]
Out[14]: [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

As to the second part, here is a hint:
In [23]: [w for w in seq if 'o' in w]
Out[23]: ['song', 'boom', 'pow']

A: from collections import OrderedDict
from string import ascii_lowercase
l = ['song', 'boom', 'pow']
od = OrderedDict(((k,0) for k in ascii_lowercase)) # create dict from alph with initial val of 0
for word in l:
    for let in word:
        o[let] += 1 # increase value by 1 for each letter in the words
print(od.values()) # ordereddict keeps order so just print values
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

for k in od:
    for word in l:
        if k in word:
            print(k,word)
('b', 'boom')
('g', 'song')
('m', 'boom')
('n', 'song')
('o', 'song')
('o', 'boom')
('o', 'pow')
('p', 'pow')
('s', 'song')
('w', 'pow')

Process finished with exit code 0

A: Another way that seems natural to me:
>>> from string import ascii_lowercase
>>> words= ['song', 'boom', 'pow']
>>> s=''.join(words)
>>> [s.count(c) for c in ascii_lowercase]
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

For the second part, just use a nested loop:
for c in ascii_lowercase:
    li=[]
    for word in words:
        if c in word:
            li.append(word)
    if li:
        print '{} in {}'.format(c, ', '.join(li))

Prints:
b in boom
g in song
m in boom
n in song
o in song, boom, pow
p in pow
s in song
w in pow


text:
Q: Observable.switchMap doesn't work and doesn't have any errors I'm facing a bug(?) when using ngrx.store and states.
After I dispach for new state and the reducer returns the new state nothing heppends . The subscribe doesn't get any error massages.
If I remove switchMap, The code works and the subscriber get the values he shoud get.
I minimized my code as little as I could:
public a$:Observable<any>;
  constructor(private _userService:UserService, private _store:Store<any>)
  {
    this.a$=this._store
      .select(state=>state)
      .switchMap(state=>
      {
        return Observable.from(["1"]); //for simplicity.
      });
    this.a$.subscribe(
      something=>{
        console.log(something);
      },
      error=>{
        console.log(error);
      }
    );
  }

My reducer:
export const connectedUserReducer = (state = initialState, action:Action) =>
{
  if(action==null || action.type==null)
    return state;
  switch (action.type) {
    case updateConnectedUser:
      return Object.assign({},state);  <<<-- It comes here and then nothing  heppends.<<--
    default:
      return state;
  }
};

I did import switchMap as: "import 'rxjs/add/operator/switchMap';"

A: SwitchMap is a rxjs operator and therefor this if it were a bug would most likely not be a ngrx/store bug.
https://plnkr.co/edit/0Ul8S0VlRwuBUAOuYDKG?p=preview
this.userList = this.userListService.userList.switchMapTo(Observable.from([[new User(1, "Mr. Grant")]]));

I'm using a old plunker I already had set from another example but if you look in the component I added a switchMapTo(similar to a switchMap but it just doesn't pass in the value of the original Observable to the function).  Everything switches over to the new Observable fine.  I'm not sure of the rest of your code's setup but hopefully looking over this will give you some ideas of what might be wrong in your code.
Based off the code you've posted I honestly don't see why it wouldn't work.  The error may lay somewhere else in your app or setup.


text:
Q: How to detect lowercase letters in Python 3.2? Okay, I'm not really getting the answers I was looking for so I'll try rewording this.  I need to know if there is a function that detects the lowercase letters in a string.  Say I started writing this program:
s = input('Type a word')

Would there be a function that lets me detect a lowercase letter within the string s?  Possibly ending up with assigning those letters to a different variable, or just printing the lowercase letters or number of lowercase letters.
While those would be what I would like to do with it I'm most interested in how to detect the presence of lowercase letters.  The simplest methods would be welcome, I am only in an introductory python course so my teacher wouldn't want to see complex solutions when I take my midterm.  Thanks for the help!

A: Using a regular expression is probably the simplest way:
# Python 3 version

import re

txt = 'MarMaLadE'

# Replace uppercase with "" - an empty string
ltxt,n = re.subn(r'[A-Z]', "", txt)

print("lower case letters:"," ".join(set(ltxt)))
print("number of lc letters:", n)

The use of set removes duplicate lowercase letters, you might not want that.  You might also want to consider which characters are uppercase, is A-Z sufficient?  See also the re.LOCALE flag.

A: Hope this helps, keep in mind that python is wary of indentation. This is not a very good solution but it works.
def doWhatYouWantToDo(input):
 newString = ""
 alphabet = "abcdefghijklmnopqrstuvwxyz"
 for letter in input:
  if letter in alphabet:
   newString += letter
 return newString

yourString = 'MarMaLadE'
print doWhatYouWantToDo(yourString)
print len(doWhatYouWantToDo(yourString)


text:
Q: Receiving only a part of string which is passed as a parameter to http get command - Semicolon Perhaps? I am trying to pass this string as a get parameter. This string starts with the following characters :
string name is some_html it is basically some html

<span style=\"font-size: xx-large;

However I only get this
<p style=\\"-qt-block-indent: 0

This is how I am passing the string:
http://127.0.0.1:8000/service_SubmitResult?htmlstring=some_html

Any idea on what I might be doing wrong. I am sending the string via Qt and receiving it on Django endpoint? I believe its because of the semicolon . I am using the following function for encoding the url before sending it out
QUrl ServiceCalls::UrlFromUserInput(const QString& input)
{
   QByteArray latin = input.toLatin1();
   QByteArray utf8 = input.toUtf8();
   if (latin != utf8)
   {
      // URL string containing unicode characters (no percent encoding expected)
      return QUrl::fromUserInput(input);
   }
   else
   {
      // URL string containing ASCII characters only (assume possible %-encoding)
      return QUrl::fromUserInput(QUrl::fromPercentEncoding(input.toLatin1()));
   }
}

Why am I receiving only a part of the string. On django i am getting the parameter value in the following way
def service_foo(request):
    try:
        htmlResult = request.GET.get('htmlstring', '')
        ....
        return HttpResponse();
    except Exception as e:
        print(e)
    return HttpResponse("Error Service from sqlite")

Any suggestions on how I can fix this or what other options i can use ?

A: I think you must make string, html escaped before sending it
in qt there are some ways to do it.
Take a look at this issue.


text:
Q: Map three rows of data into a matrix I have a dataset of movies ratings that looks as follow:

I want to map this into a matrix where the index in the user id, columns are the moviesids and values are the ratings.
What I have done so far is:
movies = df['movieId'].unique()
users = df['userId'].unique()
data_set = pd.DataFrame({'userId':users})
data_set = data_set.set_index('userId')
for movie in movies:
    data_set[movie] = 0

So now I need to fill those spaces items with the corresponding ratings, but this is a messy and slow process.

A: Consider the dataframe df
df = pd.DataFrame([
        [1, 11, 1],
        [1, 12, 5],
        [2, 11, 3],
        [2, 13, 4]
    ], columns=['userid', 'movieid', 'rating'])

option 1
pivot
df.pivot('userid', 'movieid', 'rating')

option 2
set_index + unstack
df.set_index(['userid', 'movieid']).rating.unstack()

Both yield
movieid   11   12   13
userid
1        1.0  5.0  NaN
2        3.0  NaN  4.0

However, the unstack method has a fill_value parameter that allows to keep the integer dtype
df.set_index(['userid', 'movieid']).rating.unstack(fill_value=0)

movieid  11  12  13
userid
1         1   5   0
2         3   0   4


text:
Q: Plotting multiple graphs from one dataframe with a single x axis- Python I have searched every possible solution but it never seems to create the plots in a way that is legible for me. It should also work for potentially 100's of dataframe columns so a solution being in a loop or something of that nature would be preferred
My dataframe is roughly this
data=
Time    Pressure    Static Temperature    Stag Temperature
0       100         50                    75
10      105         55                    77
20      110         59                    81
30      106         57                    79

What I would like is 3 different graphs that plot Pressure, Static Temp, and Stag Temp vs Time which would be the X-axis.
My current code looks like
import pandas
data=pandas.read_csv(data.csv')
for header in data:
    data.plot(x='System Time',y=header)

I think I understand the problem which is that for my data.plot needs to have y="Something in quotes" but I thought because header is a string it should work.
Any solution to get multiple graphs would be absolutely wonderful!
Also I apologize if my formatting is messed up as this is my first time posting!

A: I think you're looking for this:
>>> data.plot(x="Time")

However, to achieve this, I had to reformat your data.csv file to replace white spaces with commas, as it is the default separator in a Comma Separated Values file. Maybe your original file is tabulated and in this case, your need to specify sep='\t' to the read_csv() call.

A: If anyone finds this in the future, I figured out my own problem!
The problem was an error was thrown every time and all it said was
KeyError: 'Time'

This issue arose because 'Time' was my x axis and then it became my y axis through the iteration of "data". Thus is would stop every single time on the first loop.
To fix this, all I had to do was add a statement that skipped the column which was my x-axis
import pandas
data=pandas.read_csv(r'data.csv')
for header in data:
    if header!="Time":
        data.plot(x='Time',y=header,legend=False)

This skipped the first column and allowed the rest of the headers to be plotted in separate graphs.
If headers confuses you (like it confused me at first), you can use a more general form
import pandas
data=pandas.read_csv(r'data.csv')
for i in list(data):
    if i!="Time":
        data.plot(x='Time',y=i,legend=False)

Good luck everyone!


text:
Q: How prove this inequality $x^3y+y^3z+z^3x\ge xyz(x+y+z)$
Let $x>0$, $y>0$ and $z>0$. Show that
  $$x^3y+y^3z+z^3x\ge xyz(x+y+z).$$

I known we can't WLOG: $x\ge y\ge z$, if this, I can use rearrangement inequality, But other I can't it. Thanks?

A: You can not assume $x\geq y\geq z$ because our inequality is cyclic and not symmetric,
but we can say that $(x^2,y^2,z^2)$ and $\left(\frac{1}{x},\frac{1}{y},\frac{1}{z}\right)$ are opposite ordered.
Thus, by Rearrangement
$$x^3y+y^3z+z^3x=xyz\left(\frac{x^2}{z}+\frac{y^2}{x}+\frac{z^2}{y}\right)=$$
$$=xyz\left(x^2\cdot\frac{1}{z}+y^2\cdot\frac{1}{x}+z^2\cdot\frac{1}{y}\right)\geq$$
$$\geq xyz\left(\frac{x^2}{x}+\frac{y^2}{y}+\frac{z^2}{z}\right)=xyz(x+y+z).$$
C-S also works because
$$\sum_{cyc}\frac{x^2}{z}\geq\frac{(x+y+z)^2}{x+y+z}=x+y+z,$$
but you wanted Rearrangement.
We can prove this inequality also by $uvw$, AM-GM, BW and more.

A: I don't know what is meant by rearrangement, so I'll offer another solution, fairly basic, but it works.
$$x^3y+y^3z+z^3x \geq xyz(x+y+z)$$
$$xy(x^2)+yz(y^2)+zx(z^2) - xyz(x+y+z) \geq 0$$
$$xy(x^2-2xz+z^2)+yz(y^2-2yx+x^2)+zx(z^2-2yz+y^2) \geq 0$$
$$xy(x-z)^2 + yz(y-x)^2+zx(z-y)^2 \geq 0$$
The last line consists of all positive values, and thus we can work backwords and show this inequality to be true.


text:
Q: How to Change VS Code Code.exe Path for Update? [Windows 10] I have "Microsoft VS Code (User Setup)" installed in a custom directory and whenever I try to update it this shows up:

and then this

Log Info

Dec 23 11:42:40.673 INFO Starting: C:\Users\jeremy\AppData\Local\Programs\Microsoft VS Code\Code.exe, false
Dec 23 11:42:40.674 ERRO Bad arguments: Code path doesn't seem to exist: C:\Users\jeremy\AppData\Local\Programs\Microsoft VS Code\Code.exe

How do I change the path to point it to the right directory where "Code.exe" exists?

A: I had the same problem recently. I ended up reinstalling VS Code.
Do I lose my settings?
No. Note that I did not uninstall VS Code, I just downloaded the installer from the website and installed VSCode. This won't hurt, as it does not touch your settings and extensions.

What I tried
I first tried to visit the path mentioned in the error log, and I noticed that the folder _ within that directory contained the new VS Code version, downloaded by the updater.
So the path should have been C:\Users\myusername\AppData\Local\Programs\Microsoft VS Code\_\Code.exe instead, perhaps.
I tried to move all files from _ to their parent directory, and then, in VS Code, Help » Restart to update. This opened the new version of VS Code, but after closing it and starting it from the original install location (or through a shortcut I have always been using), the old version was still loaded. So apparently, this "trick" didn't work.
Then I tried to make a symbolic link to Code.exe within the _ directory, so the VS Code updater would find Code.exe. This caused roughly the same things to happen. So, this didn't work either.
At last, I decided to just download VS Code from their website, and simply install it. This seemed the most simple option to me.

A: Create a hard link for Code.exe using mklink, works for me.
Command should look like this (depends where your custom installation is, my in C:/Program Files/Microsoft VS Code/):
mklink /H "C:/Users/$username/AppData/Local/Programs/Microsoft VS Code/Code.exe" "C:/Program Files/Microsoft VS Code/Code.exe"


text:
Q: How do you type vue-router meta attribute to be required? I have typed the vue-router meta fields according to the manual, for example:
declare module 'vue-router' {
  interface RouteMeta {
    // must be declared by every route
    requiresAuth: boolean
  }
}

These meta fields must be configured by the developer. Making it non-null ensures that typescript throws an error if meta is defined but requiresAuth isn't. However, it does not check if meta is defined and if it isn't, there are no errors.
How do I make sure that meta is defined for every route?

A: It's not a good practice to modify global behaviour for local purposes. Routes array can have custom type that fits the expectations. E.g. for routes with mandatory name and meta it's something like:
interface RouteCommonMeta {
  ...
}

interface RouteCommonDef {
  name: RouteRecordName;
  meta: IRouteCommonMeta;
  children?: RouteDef[];
}

export type RouteDef = RouteRecordRaw & RouteCommonDefinition;

const routes: RouteDef[] = [...];


text:
Q: Oracle - Date not between Multiple Rows I have a table with start and end dates. I want to make sure that no new dates will overlap any of the periods defined between the start and end date. Any ideas ?

A: You could check for existing rows for that new date before inserting:
SELECT COUNT(*) FROM THE_TABLE
  WHERE  (
    ? BETWEEN START_DATE AND END_DATE
  OR
    ? BETWEEN START_DATE AND END_DATE
  OR
    START_DATE BETWEEN ? AND ?
  ) AND ROWNUM<2

(where the ? are the start and end dates of the new period to be tested).
You probably need to synchronize this (for example with a LOCK TABLE) to avoid race conditions.

A: Further to what Thilo said, the following must also be handled
SELECT COUNT(*) FROM THE_TABLE
  WHERE  (
    DATE_1 BETWEEN START_DATE AND END_DATE
  OR
    DATE_2 BETWEEN START_DATE AND END_DATE
  OR
    START_DATE BETWEEN DATE_1 AND DATE_2
  OR
    END_DATE BETWEEN DATE_1 AND DATE_2
  )
AND ROWNUM<2


text:
Q: Adding more sound files to resource packs If I create a resource pack for Minecraft, am I able to have more natural sounds than there already are? For example, creeper sound files range from "creeper1" to "creeper4". If I were to add a file named "creeper5" will it play naturally, at random, just like all the other "creeper#" files? Or are only a certain range of files set to play?
Also, if I add a sound file that wouldn't overwrite sounds files that already exist (such as someone narrating an intro, named "intro.ogg"), would I be able to play that sound in a command block?

A: Yes, you are able to play custom sounds with Command Blocks using command:
playsound <sound> <player> [x] [y] [z] [Volume] [Pitch] [minimumVolume]

Minecraft Wiki has the following description:

Example: Sound located at .minecraft\assets\sound\mob\pig\death.ogg
  The value for sound would be written as mob.pig.death, as the
  command originates from the sound folder. For sequentially numbered
  files pertaining to the same event (like various walking sounds), the
  player must exclude the number of the sound (for example, sound
  located at .minecraft\assets\sound\mob\pig\say2.ogg). In this case,
  the command will play a randomly selected sound out of the three
  available. A player or area must be selected, and the player must be
  able to hear the sound from where it is played.

I have no knowledge on adding more numbered sounds, but the wording of the above description makes me think it should be handled OK by the game. Unless anyone else adds that information, you'll have to test yourself - just add a loud scream to zombie groans and walk around for some time :)


text:
Q: WebRTC NodeJS Server Architecture I'm interested in building a web application similar to TinyChat where multiple users can be in a room and broadcast their audio/video feeds to everyone else in the room. I've been looking at WebRTC and it looks pretty easy to get started with a P2P setup, but I'm having trouble finding out how to do WebRTC with a client/server architecure.
I've watched Google's presentation video on WebRTC and the different network topologies common in working with WebRTC. The one I'm most interested in is that in working with an MCU where the MCU is responsible for broadcasting the data to everyone else in the room, thus eliminating P2P.
My question is, how would I go about this? Are there any working examples? Prefferably, I'd like to work with NodeJS on the server-side but haven't found any libraries for handling it. The only two things I have found are Kurento and Licode, but they both appear to be more than I'm interested in at this point in time. I'm basically just wanting something that takes the WebRTC connection and then broadcasts it out to the appropriate users in the same room. I'm not worried about transcoding, muxing, or recording right now.


text:
Q: How to change main query based on post meta I would like to change the sort order of a query, based on meta in the returned posts.  Specifically, posts are events with an event date and I filter them as either future or past.  If all events are in the past, I want the most recent ones first, if all in the future, the next to happen needs to be first.  I've tried all sorts in a pre-get-posts function like:
function resort($query){
    if($query->is_main_query() && is_tax('event-category'){
        if($query->have_posts()){
            // do something based on the first post
            wp_reset_query();
        }
    }
}

The function is in functions.php and is firing but it doesn't get past have_posts(), even though the main query is returning lots of posts.  What am I missing?

*

*What is it that triggers the query, and can't it be triggered
anywhere? I tried query_posts() and failed.

*How can I construct a custom query which is exactly the main query?

*expense doesn't bother me - it's a small site.

A: Finally got it.  This code in functions.php:
function set_order_by_last_date($query){

$query->set( 'orderby', 'eventstart');
$query->set( 'order', 'DESC' );
$query->get_posts();
if ($query->have_posts()){
    if ( eo_get_the_end('Ymd',$query->posts[0]->ID,$query->posts[0]->occurrence_id) > date('Ymd') ){
        $query->set( 'event_end_after', 'today' );
        $query->set( 'orderby', 'eventstart');
        $query->set( 'order', 'ASC' );
    } else {
        $query->set( 'event_end_before', 'today' );
        $query->set( 'orderby', 'eventstart');
        $query->set( 'order', 'DESC' );
    }
}
return $query->query_vars;
}

Called from the template file with:
<?php query_posts(set_order_by_last_date(clone $wp_query));?>

The vars and eo_ functions are from the excellent event organiser plug-in.  Thanks @jack-johansson for the pointers.


text:
Q: How to use a Symfony2 Service Container for FOS-UserManager my Problem is I´m a Symfony Noobie.
I have the FOSUserBundle and I want simply to access UserManager with this code.
$userManager = $container->get('fos_user.user_manager');

But it does´t work. My error message is:

I tried to look weather the service is declared or not with the console commando:
php app/console container:debug but the service 'fos_user.user_manager' is declared/registered.
Is it possible that I forgot something with service container?
Greetings
Michael
PS: here is my full code of the controller class:
    <?php

namespace Main\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use FOS\UserBundle\Model\UserManagerInterface;

class ProfileController extends Controller
{
    /**
     * @Route("/listProfile")
     * @Template()
     */
    public function listProfileAction()
    {
       $user = $container->get('fos_user.user_manager');

        return array('user' => $user);

    }

A: You need to call the class property "container" using $this->container rather than a local variable which you are calling at the moment.
The next problem will be that you are just calling the user manager rather than the actual user.
To get the current user you should use...
$user = $this->container->get('security.context')->getToken()->getUser();

ALSO
As you are extending Symfony\Bundle\FrameworkBundle\Controller\Controller you could also use $this->get('something.something') but this is just a shortcut to the $this->container->get('something.something') method (see: Controller source). $this->get() is not available when extending ContainerAware.
For some reason I went code sample crazy....


text:
Q: TSQL Check Database Instance Online What is the best way to check if an instance of Microsoft SQL Server is up? I have a view that spans two instances of Microsoft SQL Server but before querying it in a stored procedure I would like to verify that the second instance of the server is up with a fallback option of just querying local data.
The second instance is a linked server.
Currently I'm considering a SQL CLR function that can attempt to open a connection with a shorter timeout but I'm wondering if it's something that can be done directly in Transact SQL.

A: How about just validating that the database you are interested in connecting to is online?
select
    name
from sys.databases
where name = 'DatabaseName'
    and state = 0 --Database is online

For the full reference of available columns for the sys.databases catalog view see Books Online: sys.databases
EDIT: Fix SQL query

A: Query sys.sysdatabases through the linked server (you need permissions), here are the values for the status column
1 = autoclose (ALTER DATABASE)

4 = select into/bulkcopy (ALTER DATABASE using SET RECOVERY)

8 = trunc. log on chkpt (ALTER DATABASE using SET RECOVERY)

16 = torn page detection (ALTER DATABASE)

32 = loading

64 = pre recovery

128 = recovering

256 = not recovered

512 = offline (ALTER DATABASE)

1024 = read only (ALTER DATABASE)

2048 = dbo use only (ALTER DATABASE using SET RESTRICTED_USER)

4096 = single user (ALTER DATABASE)

32768 = emergency mode

4194304 = autoshrink (ALTER DATABASE)

1073741824 = cleanly shutdown


text:
Q: PostgreSQL: indexes and partitions I have a PostgreSQL database and I noticed a weird behaviour while working with indexes and partitions. The engine version is 10.21.
Now, I have a table with this structure:
guid varchar(50) PK
guid_a varchar(50)
data text
part_key varchar(2)

There are other columns but they are irrelevant. The query I have to run on this table looks like this'
select * from mytable where guid_a = 'jxxxxx-xxxxxxx' and data like '%7263628%';

Let me explain a things:
The column guid_a contains a code that identifies a person in the format: 'jxxxx-xxxxxxx' where 'x' are numbers.
The first two digits goes from 00 to 99, so, for example:
j01xxx-xxxxxx
j02xxx-xxxxxx
...
j99xxx-xxxxxx

I created an index on this column and then I also created an index using trgm module on the data column. Launching the query I get a giant improvement on the performance. Everything's good until now.
I also decided to use partitions (the table has 6.4 million records) and I created 99 partitions (by list) on the column part_key, which contains the first two digits only of the guid_a value. I obtained 99 partitions with each an average of 65 thousand rows. Each partition has the same indexes I talked about before. Improved the performance again. Obviously le query has another condition for the part_key, so that the engine knows which partition should query.
Now the weird stuff. I removed the trgm index on the table without the partitions and, surprise surprise: it's faster. Even faster than the partitioned table. Even removing the trgm indexes on the partitioned table.
What I noticed on the explain is that the query on the non-partitioned table is forcing the engine go for a index scan only (shouldn't then also make another scan for the second condition on the data table?).
On the partitioned table, on the other hand, it goes for the hitman index scan, then it does a heap scan and then an append. This apparently costs more than indexing all the 6.4 million rows.
I made different tests with different values but same results.
Performance:
On average:
11 ms on the partitioned table
9 ms on the non-partitioned table with one index only on the guid_a
20 ms on the non-partitioned table with two indexes, the second on the data column using trgm.
What's going on here?


text:
Q: how use UTL_FILE package for write file on map drive? I use UTL_FILE package in my procedure for saving file on database server but i need to save file on another server for that i make a map drive but this UTL_FILE not saving files on my MAP Drive me also check manually drive Read and write the file but through procedure UTL_FILE not ABLE TO save the file on map drive and i got this error "Data Base Error: ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536 ORA-29283: invalid file operation "

A: If it is a directory on a server that is not the database server, option that used to work for me was to use UNC (Universal Naming Convention) while creating directory (as an Oracle object). For example:
No : Z:\files_4005
Yes: \\my-another-server\d$\home\gis\files_4005"


text:
Q: Can't Debugg using VS Code because it doesnt Find a local file Currently when I debbuging moves to my_proyect and run
/home/my_user/my_company/my_proyect/my_folder/my_code.py

However, I getting the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'data/my_data.csv'

I trying to change the cwd variable in launch.json inside .vscode as follows:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [

        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "env": {
                "ENVIROMENT_EXECUTION": "local",
                "LOGGING_LEVEL": "info",
                "ENVIROMENT_STAGE": "develop",
                "ENVIROMENT_DEBUG": "yes"
            },
            "cwd": "${workspaceFolder}/my_folder"
        }
    ]
}

The structure of the folders is:
my_proyect/my_folder/data/my_data.csv
my_proyect/my_folder/my_code.py

And inside the code I have the following lines:
import pandas as pd
my_data = pd.read_csv("data/my_data.csv")

I note that works perfect if I add my_folder to the path as follows:
import pandas as pd
my_data = pd.read_csv("my_folder/data/my_data.csv")

But I can't do that because when I deploy my code in AWS Lambda it works perfect. So, Any idea how to solve this issue?

A: VS Code takes the open folder as the workspace. I have tested according to your directory structure, and there is no problem.

I open the my_project folder with VS Code and VS Code uses it as a workspace.

Below is my launch.json
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true,
            "cwd": "${workspaceFolder}/my_folder",
        }
    ]
}

So, please modify your cwd configuration according to your workspace.

UPDATE:
Open the folder using File --> Open Folder...

Here is your directory:
/home/my_user/my_company/my_proyect/my_folder/my_code.py

If you have my_company turned on then "cwd" is
"cwd": "${workspaceFolder}/my_proyect/my_folder/"

If you have my_user turned on then "cwd" is
"cwd": "${workspaceFolder}/my_user/my_proyect/my_folder/"

${workspaceFolder} is just a variable that represents the path to the folder you are currently opening as a workspace.
Of course you can also use absolute path directly as "cwd":
"cwd": "/home/my_user/my_company/my_proyect/my_folder/my_code.py"


text:
Q: Confusion about the relationship between current, resistance and potential difference If the voltage of a component has dropped, what will happen to the resistance? My book says it will decrease but I don't understand the logic. How can current and resistance go down at the same time? Please explain in easy words. Question The dc power supply is set to 12 V and the ammeter reading is 1.5 A. The student changes the emf of the dc power supply to 6 V. The lamp dims and the ammeter reading changes. What happens to the resistance of the filament lamp?

A: The answer key is correct! The conductivity and resistivity of any metal is dependant on temperature. The resistivity at Celsius temperature $t$ is given by:
$$\rho=\rho_{20}[1+\alpha(t-20^\circ C)] \space ,$$
See the resistivities and temperature coefficients below:

Moreover, we have:
$$R=\frac{L}{A}\rho \space ,$$
where $L$ is the length of the wire, and $A$ is its cross-sectional area. When the voltage is dropped, the current reduces, then the LED filament becomes cooler and its resistance $R$ decreases.


text:
Q: MediaStore.Media.Images Android/ Kotlin: How to hide photos saved in gallery from user? I am using the following program to capture an image using the MediaStore.ACTION_IMAGE_CAPTURE cameraIntent.
Code:
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "New Picture")
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
//camera intent
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)

I have the following questions:

*

*The image that has been captured is being shown in the gallery. How do I hide that from the user?

*After taking the image, I am setting the photo in a ImageView that is lagging the activity. How can I compress the image when I am setting it to the ImageView?

*Is there a way to click photos only in potrait mode?

I tried changing the EXTERNAL_CONTENT_URI to INTERNAL_CONTENT_URIbut that gives me the following warning: Writing to internal storage is not supported android

A: As soon as you use the media store they are in 'the gallery'.
So you have to use getFilesDir() and classic file methods to save them for your eyes only.

A:
The image that has been captured is being shown in the gallery. How do
I hide that from the user?

As blackapps have said, and in accordance to this documentation, which states that MediaStore API uses shared storage, you can't use MediaStore API to store in app-specific storage (Not the Gallery).
This documentation provides an example of storing photos to app specific storage using getExternalFileDir().

After taking the image, I am setting the photo in a ImageView that is
lagging the activity. How can I compress the image when I am setting
it to the ImageView?

Try Glide, a fast and efficient image loading library for Android. In addition, as I'm typing this, CommonsWare has also recommended other Image loading libraries such as Picasso and Coil.

Is there a way to click photos only in portrait mode?

Perhaps this SO Q&A might help. You can set theclickable attribute of the ImageView programmatically or declaratively.


text:
Q: GDB from NetBeans 7.1 on OSX Leopard not stopping at breakpoints in library projects This is my first question in StackOverflow since I joined some weeks ago and I wish someone could shed some light to this issue that drives me nuts! I've already searched thru the web, but I cannot find a successful solution to this problem.
I'm having some trouble with debugging with Netbeans 7.1 on Mac OSX 10.5.8 (Leopard) using GNU GDB. My problem is that I can't easily debug my own static or dynamic libraries from a test application because the debugger doesn't stop at breakpoints set in the source code of that libraries. However I've noticed that I can "step into" the library functions and, once I'm in them, breakpoints in those functions do fire!
My testbench consists on 2 simple projects: "mylib" (a C static library) and "mylib-test" (a C application). 'mylib' simply contains a header and a c file that define the function:
int sum(int a, int b) {
    return a+b;
}

On the other hand, the mylib-test source simply uses that function:
int main(int argc, char** argv) {
    printf("Result=%d\n", sum(111, 222));
    return (EXIT_SUCCESS);
}

Both projects compile and execute successfully. For your convenience, below I put down the output of compiling/linking both projects:
Output of compiling mylib:
gcc    -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/m.o.d -o build/Debug/GNU-MacOSX/m.o m.c
mkdir -p dist/Debug/GNU-MacOSX
rm -f dist/Debug/GNU-MacOSX/libmylib.a
ar -rv dist/Debug/GNU-MacOSX/libmylib.a build/Debug/GNU-MacOSX/m.o
ar: creating archive dist/Debug/GNU-MacOSX/libmylib.a
a - build/Debug/GNU-MacOSX/m.o
ranlib dist/Debug/GNU-MacOSX/libmylib.a

Output of compiling mylib-test:
gcc    -c -g -I../mylib -MMD -MP -MF build/Debug/GNU-MacOSX/main.o.d -o build/Debug/GNU-MacOSX/main.o main.c
mkdir -p dist/Debug/GNU-MacOSX
gcc     -o dist/Debug/GNU-MacOSX/mylib-test build/Debug/GNU-MacOSX/main.o ../mylib/dist/Debug/GNU-MacOSX/libmylib.a

By examining the Debugger Console, I've noticed that breakpoints placed in the library's source code are marked as "PENDING" when I load the application on the debugger (see line starting by 12^done, field addr):
11-break-insert -f "/Users/claudi/dev/mylib-test/main.c:16"
12-break-insert -f "/Users/claudi/dev/mylib/m.c:5"
7^done,line="7",file="main.c",fullname="/Users/claudi/dev/mylib-test/main.c",time={wallclock="0.00065",user="0.00032",system="0.00029",start="1345544547.505531",end="1345544547.506184"}
(gdb)
13-break-insert -t main
&"cd /Users/claudi/dev/mylib-test\n"
8^done
(gdb)
9^done,time={wallclock="0.00002",user="0.00002",system="0.00000",start="1345544547.530991",end="1345544547.531013"}
(gdb)
&"set environment DYLD_LIBRARY_PATH=../mylib/dist/Debug/GNU-MacOSX\n"
10^done
(gdb)
11^done,bkpt={number="1",type="breakpoint",disp="keep",enabled="y",addr="0x00001fb3",func="main",file="main.c",line="16",shlib="/Users/claudi/dev/mylib-test/dist/Debug/GNU-MacOSX/mylib-test",times="0"},time={wallclock="0.00058",user="0.00030",system="0.00029",start="1345544547.532421",end="1345544547.533003"}
(gdb)
12^done,bkpt={number="2",type="breakpoint",disp="keep",enabled="y",addr="<PENDING>",pending="/Users/claudi/dev/mylib/m.c:5",times="0"},time={wallclock="0.00040",user="0.00018",system="0.00022",start="1345544547.533140",end="1345544547.533542"}
(gdb)
13^done,bkpt={number="3",type="breakpoint",disp="del",enabled="y",addr="0x00001fb3",func="main",file="main.c",line="16",shlib="/Users/claudi/dev/mylib-test/dist/Debug/GNU-MacOSX/mylib-test",times="0"},time={wallclock="0.00017",user="0.00016",system="0.00001",start="1345544547.552190",end="1345544547.552362"}

It seems that GDB is not loading the symbols of the library, yet it is actually linked statically (I mean, there are no dynamic libraries to load)!!
However, if I step into function sum from the main() function, and then place the breakpoint, then it is successfully resolved:
21-break-insert -f "/Users/claudi/dev/mylib/m.c:5"
21^done,bkpt={number="4",type="breakpoint",disp="keep",enabled="y",addr="0x00001fea",func="sum",file="m.c",line="5",shlib="/Users/claudi/dev/mylib-test/dist/Debug/GNU-MacOSX/mylib-test",times="0"},time={wallclock="0.00099",user="0.00039",system="0.00060",start="1345544947.877096",end="1345544947.878088"}

I hope I've given enough information... Does anybody have an idea of what's going on? Thank you in advance!
Further info:
GCC version: 686-apple-darwin9-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5577)
GDB version: GNU gdb 6.3.50-20050815 (Apple version gdb-967)
Netbeans version:  7.1 (Build 201112071828)
////////////// EDIT //////////////////////////////////////////////////
So far I thought the problem was GDB, but today I've noticed it is not true: I've been able to debug the application directly using GDB from the command line, i.e., I could set breakpoints to my sum function and the debugger successfully stopped at them without the need to step into the function. So, I'm sure I'm having some issue with how NetBeans starts/initializes GDB. I've also noticed that NetBeans is trying to get features from GDB without success. From the debugger console:
~"GNU gdb 6.3.50-20050815 (Apple version gdb-967) (Tue Jul 14 02:11:58 UTC 2009)\n"
~"Copyright 2004 Free Software Foundation, Inc.\n"
~"GDB is free software, covered by the GNU General Public License, and you are\nwelcome
to change it and/or distribute copies of it under certain conditions.\nType \"show
copying\" to see the conditions.\nThere is absolutely no warranty for GDB.  Type \"show
warranty\" for details.\n"
~"This GDB was configured as \"i386-apple-darwin\"."
~"\n"
(gdb)
2-list-features
3-gdb-set print repeat 0
4-gdb-set backtrace limit 1024
5-gdb-set print elements 0
6-file-exec-and-symbols  "/Users/claudi/dev/mylib-test/dist/Debug/GNU-MacOSX/mylib-test"
2^error,msg="Undefined MI command: list-features"

A: I have no answer for this issue but I have some clues that could help finding solution.
I belive it's not NetBeans' fault. It's something with gdb. Probably it has to be compiled with some special configuration flag(s).
I was using gdb 7.4 (downloaded while ago with MinGW) with NetBeans 7.0-7.2 and Eclipse Juno on Windows 7 and everything was working as expected - gdb was stopping when entering breakpoints in my libraries (static or dynamic).
Lately I wanted to migrate to gdb compiled with Python support to get pretty-printing of complex STL structure in Eclipse. So I've downloaded latest gdb 7.5 sources and I've compiled it with "--with-python" flag:
./configure --with-python
make && make install

Pretty pretting works. Not even on Eclipse but with NetBeans as well (you only need to point to .gdbinit file in Project's Debug settings). The problem is my own compiled version of gdb has no ability to stop on breakpoints in my libraries (on NetBeans 7.2 and Eclipse Juno).
My conclusion is that gdb should be compiled with some flag(s) to get this ability. Or maybe it would be just sufficient to run it with some flag(s). I would also be grateful for help with this issue.
I'm attaching some possible useful informations:
Screenshots with correct stack trace on gdb 7.4
Screenshots with incorrect stack trace on gdb 7.5
Correct gdb:
C:\MinGW\bin>gdb  --version
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.

C:\MinGW\bin>gdbserver --version
GNU gdbserver (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
gdbserver is free software, covered by the GNU General Public License.
This gdbserver was configured as "i686-pc-mingw32"

Incorrect gdb:
C:\MinGW\bin>gdb --version
GNU gdb (GDB) 7.5
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.

C:\MinGW\bin>gdbserver --version
GNU gdbserver (GDB) 7.5
Copyright (C) 2012 Free Software Foundation, Inc.
gdbserver is free software, covered by the GNU General Public License.
This gdbserver was configured as "i686-pc-mingw32"

A: I've checked at my work if absence of libexpat is causing gdb problem you described. And it seem that this is the case :) Try to compile and install expat first and then compile gdb from soruces.
Be sure to have:
checking for libexpat... yes
checking how to link with libexpat... <some_path>/libexpat.a

in your logs (somewhere after "make" command. not after "./configure").
To compile gdb I used gcc 4.6.2 from MinGW under Windows 7 and gdb-7.5 sources. I also added two additional configure flags but for sure they aren't necessery:
./configure --with-python --without-auto-load-safe-path


text:
Q: Backbone populating collection dynamically based on JSON response from another URL I am generally a backend guy working on J2EE (servlet/ejb) frameworks and libraries. Completely new to front-end and especially Backbone. Hence, the question is somewhat a noob one. I would appreciate any opinions/tutorials/examples for that matter. I will try to explain my objective/requirement as clearly and elaborately as possible.
This is my first SO question and hence apologies in advance for breaking any rules.
Q. I have a backend eCommerce engine which exposes REST URLs as part of product catalog API.
API 1 - /rest/repository/atg/commerce/catalog/ProductCatalog/product/.
API 1 responds back with a list of products as a single JSON array. The interesting bit here is that it sends only the individual REST URLs for each product. Sample Response:
{"product": [
  "http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/prod90004",
  "http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/prod90005",
  "http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/prod100027"
  "http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/prod70011",
  "http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/prod70013"
]}

API 2 - http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/productId viz. http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product/prod90004
Basically one of the individual product URL from API 1's response
Sample Response:
{
  "dateAvailable": "2000-05-04 15:51:42.521",
  "displayName": "Warm Black Gloves ",
  "longDescription": "Protects you from the elements and keeps you looking good, these durable gloves won't let you down.",
  "repositoryId": "prod90004"
}

Required objective: If API 1 responds back with a JSON array containing 4 URLs i.e 4 products, then I need to display the attributes of 4 products in a view and so on. The attibutes can be retreived by making 4 calls to API 2; in other words making 4 requests to the URLs received in API 1.
Issue:
I have looked into a few tutorials and examples. I could not somehow get anything on this specific use case. The examples that I have seen baically assume that there will be one REST API which would respond back with a JSON array containing all models (products in this case) and their attributes in one single JSON response. However, that is not the case here as I have to first make a call to API 1 to get the list of product URLs and then call all these URLs (retrieved in API 1's response) to get attributes of the corresponding model. Hence, I am somehow not able to decide as to how to define the models, collections and url properties etc.
I have given a try as below:
(function ($) {

    var ProductView = Backbone.View.extend({

        tagName:"div",
        className:"bookContainer",
        template:$("#bookTemplate").html(),

        render:function () {
            console.log("inside render of ProductView");
            var tmpl = _.template(this.template);
            this.$el.html(tmpl(this.model.toJSON()));
            return this;
        }
    });

    var ProductModel = Backbone.Model.extend({

        defaults:{
            displayName:"displayName",
            longDescription:"longDescription",
            dateAvailable:"dateAvailable",
            repositoryId:"repositoryId",
        },

        initialize: function(){
            this.on("reset", this.renderModelView, this);
            this.fetch({
                reset:true,
                error:function () {
                    console.log(arguments);
                }
            });

        },

        renderModelView: function(){
            var that = this;
            new ProductView.render({
                    model: that
                });

        }
    });

    var ProductCollection = Backbone.Collection.extend({
        model: ProductModel,

        initialize: function(){
            this.on("reset", this.debugTempfunc, this);
            this.fetch({
                reset:true,
                error:function () {
                    console.log(arguments);
                }
            });
        },

        debugTempfunc: function(){
            console.log("collection length: "+this.length);
        }
    });

    var ProductURLModel = Backbone.Model.extend({

        defaults:{
            product: "ProductCatalogProductURLs"
        }

    });

    var ProductURLCollection = Backbone.Collection.extend({
        model: ProductURLModel,

        url: "http://example.com/rest/repository/atg/commerce/catalog/ProductCatalog/product",

        initialize: function(){
            this.on("reset", this.populateModels, this);
            this.fetch({
                reset:true,
                error:function () {
                    console.log(arguments);
                }
            });
        },

        populateModels: function(){
            var ProductCollectionIns = new ProductCollection();

            var that = this;
            console.log("inside populateModels of ProductURLCollection: "+that);
            _.each(that.models[0].attributes.product,function(item){
                console.log("populateModels, item value: "+item);
                ProductCollectionIns.url=item;
                ProductCollectionIns.fetch();

            });

        }

    });

    var ProductURLCollectionTestIns = new ProductURLCollection();

})(jQuery);

My plan was to first define a ProductURLCollection as a collection with the URL set to API 1's URL. This collection will have a single model ProductURLModel, which will have n number of ProductURLModel(s)... n being number of URLs retrieved in API 1 which is also equivalent to number of products. This indicates that now I have to make n number of API 2 calls. For this I decided to make another collection ProductCollection containing n number of ProductModel(s). ProductCollection's url property will be dynamically set while iterating ProductURLCollection models' as in below code:
populateModels: function(){
            var ProductCollectionIns = new ProductCollection();

            var that = this;
            console.log("inside populateModels of ProductURLCollection: "+that);
            _.each(that.models[0].attributes.product,function(item){
                console.log("populateModels, item value: "+item);
                ProductCollectionIns.url=item;
                ProductCollectionIns.fetch();

            });

        }

With this I hoped that I could make n ProductModel(s) dynamically each time changing ProductCollectionIns url. However, I am getting "Error: A "url" property or function must be specified". Does this mean that ProductCollectionIns url property is not being set?
I believe there must be an easier way to achieve the above in Backbone. Please any solution or better implementation would be appreciated.

A: Let me explain how Backbone's AJAX system works, first with a Model (but I'll get to Collections in a minute).  In short, Backbone was designed for you to be able to do:
var FooModel = Backbone.Model.extend({url: 'www.example.com'});

var someModel = new FooModel({id: 5});
someModel.fetch().done(function() {
    // Now someModel should be populated with the AJAX data for model #5
});

Behind the scenes what happens there is when you call fetch Backbone looks for the URL associated with the Model.  Since you never defined one (or a urlRoot), you get the error you're having, because Backbone doesn't know where to make the AJAX call to.
Once you tell Backbone where to find the data for that type of model via a url property, Backbone will make a call to 'www.example.com/5' (because the model has an id of 5).  Backbone will then expect that URL to return a response that looks something like:
{id: 1, someAttribute: 2, someOtherAttribute: 'spam'}

That JSON will become someModel's attributes, so you'll be able to do:
someModel.get('someAttribute'); // == 2

Collections work almost the same way, except they expect a JSON response of:
[{id: 1, someAttribute: 2, someOtherAttribute: 'spam'},
 {id: 2, someAttribute: 55, someOtherAttribute: 'eggs'}]

and they convert each member of the returned array in to a Model.
As you surmised, there is an easier way than your populateModels method: if you just follow the pattern I described, your collection should create models automatically with no extra effort.  If you do need to customize things (eg. you want to change the "foo" attribute that comes from the server to a "bar" attribute) you can overwrite either the Model's or Collection's parse method, which takes the "raw" AJAX data and returns your converted version:
var someModel = new FooModel({
    id: 5,
    parse: function(raw) {
        raw.bar = raw.foo;
        delete raw.foo;
        return raw;
    }
});

Hope that helps.


text:
Q: working with expressions: how to minimize runtime construction time I have two classes, a single expression (SE) and a bundle of two expressions (ME). The bundle is an expression itself, hence it can be an element of another bundle.
struct SE {
    SE(char id, char n) : id(id), n(n) {}

    size_t size() const { return n; }
    char *eval(char *b) const { b[0]=id; return b+1; }

    char id, n;
};

template <typename LHS>
struct ME {
    ME(const LHS& l, const SE& r) : lhs(l), rhs(r) { }

    size_t size() const { return rhs.size(); }
    char *eval(char *b) const { *b++='('; b=lhs.eval(b); *b++=','; b=rhs.eval(b); *b++=')'; return b; }

    LHS lhs;
    SE rhs;
};

The construction of the bundle performs a simple validity check based on the data member n, accessible in ME via the method size. An eval method does some claculations using the data member id. Neither n nor id are known at compile time.
For both classes I override the comma operator, so that it performs the recursive bundling of multiple single expression into a nested bundle.
auto SE::operator,(const SE& r) { return ME<SE>(*this, r); }
auto ME<LHS>::operator,(const SE& r) { return ME<ME<LHS>>(*this, r); }

I want that, after the whole bundle has been constructed, the method eval is triggered on the whole bundle. Example:
SE('a',1);                        // prints 'a'
SE('a',1), SE('b',1);             // prints '(a,b)'
SE('a',1), SE('b',1), SE('c',1);  // prints '((a,b),c)'

A possible way to achieve that is to use the destructors of the classes and add a flag is_outer which is updated appropriately during contruction of SE and ME. When any of these class is destructed, if the flag indicates this is the outermost class, then eval is triggered. A full demo is given below.
Testing on godbolt the simple demo function below, it seems to me the compiler generates more code than strictly necessary. Although id and n are not known at compile time, the final type of the expression should be. I would expect the entire construction of the bundle to reduce to just moving a few numbers in the correct place, then check the assertions, but it seems to actually do much more copies.
Is it possible to obtain that more of the contruction part is produced at compile time?
#include <iostream>
#include <cassert>
#include <string>
#include <sstream>
using namespace std;

// forward declaration
template <typename LHS> struct ME;

struct SE {
    SE(char id, char n) : id(id), n(n), outer(true)  {}
    SE(const SE& expr) : id(expr.id), n(expr.n), outer(false) {}

    ME<SE> operator,(const SE& r);

    size_t size() const { return n; }
    char *eval(char *b) const { b[0]=id; return b+1; }

    ~SE() { if(outer) { char b[20] = {}; char *p=eval(b); *p++='\n'; cout << b; } }

    char id, n;
    mutable bool outer;
};

template <typename LHS>
struct ME {
    ME(const LHS& l, const SE& r)
        : lhs(l), rhs(r), outer(true)  // tentatively set to true
    { l.outer = r.outer = false;  assert(l.size() == r.size()); } // reset flag for arguments
    ME(const ME<LHS>& expr)
        : lhs(expr.lhs), rhs(expr.rhs), outer(false) {}

    size_t size() const { return rhs.size(); }
    char *eval(char *b) const { *b++='('; b=lhs.eval(b); *b++=','; b=rhs.eval(b); *b++=')'; return b; }

    auto operator,(const SE& r) { return ME<ME<LHS>>(*this, r); }

    ~ME() { if(outer) { char b[20] = {}; char *p=eval(b); *p++='\n'; cout << b; } }

    LHS lhs;
    SE rhs;
    mutable bool outer;
};

ME<SE> SE::operator,(const SE& r) { return ME<SE>(*this, r); }

void demo(char a, char na, char b, char nb, char c, char nc) {
    SE(a, na), SE(b,nb), SE(c,nc);   // prints '((a,b),c)'
}

int main() {
    demo('a',1,'b',1,'c',1);
    return 0;
}

A: The general pattern you are following is expression templates.  Reading up on how others do it will help.
Usually expression templates use CRTP heavily, and do not store copies.
I believe I see bugs due to the copies.
Generally take T&& and store T& or T&&.
Usually expression templates terminate (and execute) when they are assigned to a target; you don't want to that.  As C++ lacks move-from-and-destroy, you have to check the "should not be executed" at (nominally) runtime.
Instead of references/values and a bool, you could store pointers and use null as the "don't run" case.
I cannot figure out how to make the work to determine what to run constexpr.  It might be possible however.


text:
Q: Php code symbols escaped after execution (Sublime editor) I am aware that this might be a question with an obvious answer but I for a php-newbie it is SO not!
I am writing php code with Sublime inside a file together with html and after I execute the files my code changes. The <and > is written with its escaping characters. Help..please..
<?php
$username= trim($_POST['username']);
$pass= trim($_POST['pass']);
$userExist= trim($_POST['userExist']);
$passExist= trim($_POST['passExist']);

// print_r($username);
// print_r($pass);

$conn= mysqli_connect('localhost','neli','','yogies');

// if(!$conn){
//  echo "No database";
//  exit;
// }else {
// //   echo "Done";
// // }

if(isset($username) && isset($pass)){
    $usernameCheck = mysqli_query($conn, 'SELECT username FROM users WHERE username="'.$username.'"');
    // print_r('SELECT username FROM users WHERE username="'.$username.'"');
    if( $usernameCheck && $usernameCheck->num_rows ){
        $check= 1;
    } else {
        $check=0;
    }
}

if($check==0){

    $userToEnter =$username;
    $userToEnter = mysqli_real_escape_string($conn, $userToEnter);

    $passToEnter = $pass;
    $passToEnter = mysqli_real_escape_string($conn, $passToEnter);

    $sql = 'INSERT INTO users (username,password) VALUES ("'.$userToEnter.'","'.$passToEnter.'")';
    // print_r($sql);

    if(mysqli_query($conn, $sql)){

        session_start();

        // print_r('here');
        // print_r($_POST['url']);

        $doc = new DOMDocument();
        // html5 problems with tags
        // libxml_use_internal_errors(true);
        $doc->loadHTMLFile('header_nav.php');
        // html5 problems with tags
        // libxml_clear_errors();

        $doc->getElementById('sign')->setAttribute('display','none');
        $doc->getElementById('logout')->setAttribute('display','block');
        $doc->saveHTMLFile('header_nav.php');

        // header('Location: '.$_POST['url']);

    }

}else{
    print_r('Nope');
}

?>

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./styles/css.css">
<title><?php echo $pageTitile ?></title>

        Log in
        Log out

Yoga Poses

                Yoga Levels

All levels

Level 1

Level 2

Level 3

Level 4

Healthy and Delicious

                <form id="loginForm" name="login" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

                    <fieldset id="bordered"><legend>Register:</legend>

Username:<input type="text" name="username">

Password:<input type="password" name="pass">

Repeat pass:<input type="password" name="pass2">

                    </fieldset><fieldset><legend>Log in:</legend>

Username:<input type="text" name="userExist">

Password:<input type="password" name="passExist">

                </fieldset>

                <button id="btnSubmit" class="btn" type="button" value="Submit">Submit</button>
                <button class="btn" type="button" value="Cancel">Cancel</button>

        </form>

A: It looks like this script is modifying itself, and using DOMDocument to do it. PHP scripts aren't valid HTML/XML, so DOMDocument mangles the code up - it's not Sublime's fault :)
The way to make the code do what you expect here is put the header HTML into a separate file (like header_nav.html), manipulate that instead, and then make your script output it to the user rather than save it.
But modifying a file with DOMDocument is probably way over the top for what you need, and there are other problems with that approach too. That file gets given to everyone, so as soon as one person logs in, everyone gets that header_nav. It also writes to disk when you only really need to change the code in memory and pass it to just that user.
Something much more simple would be to have two header html files (like header_logged_in.php and header_logged_out.php) and then make your header_nav.php just include('header_logged_in.php') if the user is logged in, or include('header_logged_out.php') if they're not.
Some other notes:

*

*Never take something from $_POST and put it straight into an SQL query - you trim it, but that's no safety at all. The safe way to do it is by using prepared statements. Have a look at PHP The Right Way on how to do that (the examples use PDO which is what I'm more familiar with, but mysqli is okay too if you prefer it).

*If either $username or $pass are empty, then $check is never set, so you'd get a PHP strict error telling you that $check is undeclared. You could just add $check = 0 before the if ($check == 0)… line to solve that. Also, use true and false instead of 1 and 0, and === instead of == - though it's a matter of taste in this instance, if you do it elsewhere too then it'll bite you eventually.

*It's commented out, but a later line does header("Location: ".$_POST['url']) which is also kinda bad - anyone could put any URL into that and redirect your users to their site. It'd be better to build the URL yourself or use an array of valid URLs and point to the right key in the array or something.

*You start the session, but you don't put anything in it (like… whether the user is logged in, and what their username is).

A: Make sure the doc type is .php and not HTML.
Click the syntax highlighting menu and choose PHP, the language chosen is HTML, make sure PHP is checkmarked.
Otherwise:
To edit the preferences:
1) - Preferences ==> Browse Packages...
2) - Go to the HTML folder & Open "HTML.tmLanguage" with a text editor
3) - Find :
firstLineMatch
<string><!(?i:DOCTYPE)|<(?i:html)|<\?(?i:php)</string>

And replace it with :
firstLineMatch
<string><!(?i:DOCTYPE)|<(?i:html)</string>

4) - Restart Sublime Text.


text:
Q: Laravel 4 - Queueing a cookie forever In Laravel 4, is there a way to set a queue a cookie that last forever?
Basically I want to mix the functionality of:
Cookie:queue()

and
Cookie:forever()

A:  Cookie::queue(Cookie::forever($name, $value));
 return $response;

or
$response = Response('hello');
$response->withCookie(Cookie::forever($name, $value));
return $response;

A: Cookie::queue($name, $value, 2628000)

If you look at the Cookie::forever() code, it defines "forever" as 2628000 (five years)


text:
Q: How to save a gtk treeview (sorting order and position)? I have a program displaying a gtk Treeview with 5-6 columns and a great number of rows, therefore there is a scrollbar on the side.
I would like to ensure that if you quit the program and restart it, the position and sort order that was in the last state before closing is loaded up again.
So:

*

*how do I store the selected item position in the treeview?

*how do I store the sorted order ?

*and how do I bring them back when displaying the treeview again, so that it would display the list just like it was when closing the program ?

I have seen some answers on SO on how to store the selected item position but not how to display it again in the same way.
I'd appreciate if you have any tips on how to do that.

A: I'm afraid I'm answering in C rather than Python as that's what I'm familiar with. You should be able to translate the function names easily enough. You can get and retrieve the selected row with gtk_tree_view_get_cursor and gtk_tree_view_set_cursor If you store the path it should be the same when you reload the data. You can use gtk_tree_view_get_columns and g_list_find to find which column is selected. Setting the cursor will scroll the window so it is visible. This will restore the view to roughly what it was when saved. If you want to be more precise try looking at gtk_scrollable_get_vadjustment and gtk_scrollable_get_hadjustment To store the sort order you can use gtk_tree_sortable_get_sort_column_id and set it with gtk_tree_sortable_set_sort_column_id
I hope that gets you started, it's well worth spending some time familiarising yourself with the tree view documentation.I t can be a bit overwhelming at first but it is worth the effort in the long run.