text:
Q: Display version, build date and environment of Blazor webassembly application I am trying to display the version, build date and environment variable on the NavMenu of a Blazor Webassembly application. Here is what i have tried but in vain
NavMenu.razor.cs
protected static Version AppVersion => Assembly.GetExecutingAssembly().GetName().Version?? throw new NullReferenceException();

protected DateTime BuildDate => new DateTime(2000, 1, 1).AddDays(AppVersion.Build).AddSeconds(AppVersion.Revision * 2);

protected string DisplayEnvironment => Environment.GetEnvironmentVariable(EnvironmentVariableTarget.Process) ?? throw new NullReferenceException()

When i run the app i get null reference exception possibly on DisplayEnvironment property.
I would appreciate any help.

A: According to this link, environment variables aren't available to Blazor WebAssembly.
You can obtain the app's environment in a component by injecting IWebAssemblyHostEnvironment and reading the Environment property.
@using Microsoft.AspNetCore.Components.WebAssembly.Hosting
@inject IWebAssemblyHostEnvironment HostEnvironment

Environment example

Environment: @HostEnvironment.Environment

Reference link: ASP.NET Core Blazor environments
Update:
Version:
protected static Version AppVersion => System.Reflection.Assembly.GetExecutingAssembly().GetName().Version ?? throw new NullReferenceException();

Build Date:
You can add the AssemblyTitle (or any other attribute you like) to your csproj file:
<PropertyGroup>
    <AssemblyTitle>$([System.DateTime]::Now)</AssemblyTitle>
</PropertyGroup>

If you want to format the date, you can do like this:
<AssemblyTitle>$([System.DateTime]::Now.ToString(yyyyMMdd-HHmm))</AssemblyTitle>

Then in your Blazor code:
string BuildInfo;
protected override void OnInitialized()
{
    Assembly curAssembly = typeof(Program).Assembly;
    BuildInfo = $"{curAssembly.GetCustomAttributes(false).OfType<AssemblyTitleAttribute>().FirstOrDefault().Title}";
}


text:
Q: Плывет верстка в Safari/iOS Ребят, купил шаблон, изначально тестировал на десктопе/андроиде и косяка не видел. В iphone же, и на маках верстка оказалась в хлам. Знания кой-какие имеются, но что-то не могу найти решение. Гляньте на сайт
в чем проблема? Ведь мобильная верстка есть, но в продуктах Apple она игнорируется. Разрабы шаблона молчат как рыбы...(

A: Вобщем, вопрос решил сам, пришло озарение :) Но большое спасибо sergski  за отклик и указание направления, покопаться в валидаторе. пока копался и нашел баг. Суть в том, что в шаблоне была анимированная предзагрузка, так вот она была убрана, но часть кода осталась. И сафари как Хатико, ждал, ждал когда пройдет предзагрузка, игнорируя все стили :) Уфф... Камень с плеч!
Спасибо за минусы, Интернет!Вы как всегда в своем репертуаре! :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add external JS file in component to render images in browser with Angular 2 I make a site with Angular 2 and will add a JavaScript file to the component. This script must render the height of some images equal to the height of the window of the browser.
How could I add this script to the component?
The solutions I found on SO or anywhere else, looks like this:
import './home.component.js';

But it's not what I need! I need this in my home.component.ts file:
@Component({
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss'],
    jsUrls: ['./home.component.js']
})

or something...
Update 1: In my site I use Angular CLI and TypeScript.
Update 2: You could find my project on GitHub: https://github.com/WatchFriends/Web

A: This works, and works well:
In the angular-cli.json file, there is a section, "scripts". Add the path to your script in that array (as a double-quoted string).
Here's a frag from that file:
  "mobile": false,
  "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.css",
    "../node_modules/font-awesome/css/font-awesome.css",
    "styles.css"
  ],
  "scripts": ["./app/my_script.js"],
  "environments": {
    "source": "environments/environment.ts",
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
  }

my_script is this:
function sayHello ( ) {
   console.log ( 'I am saying hello' );
}

Then just call it like you'd expect from anywhere. To beat the annoying "not found" error you may get in your IDE, you can either just do this:
window [ 'sayHello' ] ( );

Or create a utility class that contains a reference to that function, such that you can import the class and call the function as usual (you are basically just providing a framework facade for your "my_script.js" functions).
I tried both, it worked just fine, no errors (you are using ng serve or ng build of course etc).


text:
Q: AMP Carousel :: Dynamically add item I am using AMP, Onclick of Add slide, I need to add slide to the carousel dynamically.
Carousel is not working:

jQuery(document).on('click', '#addNewSlide', function(){
  jQuery('amp-base-carousel').prepend('<amp-img src="https://source.unsplash.com/Ji_G7Bu1MoM/600x400" width="600" height="400" layout="responsive"></amp-img>')
})

Add slide
<amp-base-carousel loop="true"  width="300" height="400"></amp-base-carousel>

A: Add slide
<amp-live-list layout="container" data-poll-interval="15000" data-max-items-per-page="5" id="amp-live-list-insert-blog>
 <button update on="tap:amp-live-list-insert-blog.update">You have updates</button>

</amp-live-list >

For the HTML update the update on
jQuery(document).on('click', '#addNewSlide', function(){
  jQuery('amp-live-list').prepend('<amp-img src="https://source.unsplash.com/Ji_G7Bu1MoM/600x400" width="600" height="400" layout="responsive"></amp-img>')
})

Update the apm-base-coursel to amp-live-list


text:
Q: Floating text in XELaTeX I have the following section header which uses two different font sizes.

I'd like to add a series of 2-3 vertical lines of text off to the far right, anchored to the top of the section's bounding box, and completely independent of the font sizes used on the far left.
Something like this (note the lines edited into the left of the render screenshot):

How might I achieve this?
Apologies for the inelegance of the TeX; I've only been using it for a couple of days. (I'm using XƎLaTeX.)
\documentclass{article}

\usepackage{lipsum}
\usepackage[a4paper, margin = 0.4in]{geometry}
\usepackage{fontspec}
\usepackage{changepage}
\usepackage{mdframed}

\newcommand*{\sepline}{%
  \par
  \vspace{0.5mm}
    \begingroup
      \color{gray!55}%
      \hrule width\linewidth height 0.1mm
    \endgroup
  \vspace{3mm}
}

\pagenumbering{gobble}
\pagestyle{empty}

\setmainfont[Mapping=tex-text]{DejaVu Sans}

\begin{document}

\color{gray!185}

\setlength{\parindent}{3em}

\begingroup
    \setmainfont{DejaVu Sans ExtraLight}
    \setlength{\parindent}{0.5mm}
    {\color{gray!160}\fontspec[Scale=1.55]{DejaVu Sans ExtraLight}Subject\par\vspace{0.4mm}}
    {
        \setlength{\parindent}{1.7mm}
        \color{gray!200}
        \begin{tabular}{ l l }
            To: & {\hspace{1mm}DEF} \\
            From: & {\hspace{1mm}ABC} \\
            Sent: & {\hspace{1mm}Tue 24th Oct 2014 12:56:04PM}
        \end{tabular}
    }
    \vspace{0mm}
\endgroup

\sepline

\noindent Test content

\end{document}

A: EDITED to line up top of right stack with top of "Subject"
Following "Subject" in the header, I used a right-aligned \Longunderstack for the right-hand text, pushing it to the right with an \hfill.  I had to \smash it so that it did not affect the vertical spacing on the left.  Also, because the word "Subject" was scaled up by a factor of 1.55, I had to vertically raise the \Longunderstack by 0.55\baselineskip to line up the tops of those two quantities (otherwise the bottom of "Subject" aligned with bottom of "Line 1").
\documentclass{article}

\usepackage{lipsum,xcolor}
\usepackage[usestackEOL]{stackengine}
\usepackage[a4paper, margin = 0.4in]{geometry}
\usepackage{fontspec}
\usepackage{changepage}
\usepackage{mdframed}

\newcommand*{\sepline}{%
  \par
  \vspace{0.5mm}
    \begingroup
      \color{gray!55}%
      \hrule width\linewidth height 0.1mm
    \endgroup
  \vspace{3mm}
}

\pagenumbering{gobble}
\pagestyle{empty}

\setmainfont[Mapping=tex-text]{DejaVu Sans}

\begin{document}

\color{gray!185}

\setlength{\parindent}{3em}

\begingroup
    \setmainfont{DejaVu Sans ExtraLight}
    \setlength{\parindent}{0.5mm}
    {\color{gray!160}{\fontspec[Scale=1.55]{DejaVu Sans ExtraLight}Subject}
    \hfill
    {\footnotesize\smash{\raisebox{0.55\baselineskip}{\Longunderstack[r]{
      Line one\\
      Line two\\
      Line three\\
      Line four
    }}}}
\par\vspace{0.4mm}}
    {
        \setlength{\parindent}{1.7mm}
        \color{gray!200}
        \begin{tabular}{ l l }
            To: & {\hspace{1mm}DEF} \\
            From: & {\hspace{1mm}ABC} \\
            Sent: & {\hspace{1mm}Tue 24th Oct 2014 12:56:04PM}
        \end{tabular}
    }
    \vspace{0mm}
\endgroup

\sepline

\noindent Test content

\end{document}


text:
Q: Why Can't I use Modules in VS Code After I Install One With Pip I'm new to python and VS Code and have been playing around recently for both fun and an attempt to raise my skills. However, when working on certain projects I haven't had default access to the modules I've needed such as dearpygui, so to install them I've used pip
pip install dearpygui

However, after having done this I still seemingly don't have access to them in VS code or at my terminal. In VS code I get a warning telling me
Import "dearpygui" could not be resolved Pylance(reportMissingImports)

What exactly am I doing wrong when importing these modules? If anybody could give me a hand I'd greatly appreciate it.


text:
Q: Backtransform Scale() function in R I have a question concerning the scale() function.
I scale a matrix and I want to understand how to scale back, so I tried to make in the following way:
datatest <- read.xls("training.xlsx")
data_train<-as.matrix(datatest)

scaled.data_train <- scale(data_train, center= TRUE, scale=TRUE)
training <- sample(nrow(scaled.data_train), 80)

Xtraining <- scaled.data_train[training, ] # keeps 80 from 98 records
Xtest <- scaled.data_train[-training, ]
afterwards I made a prediction based on Xtraining and I obtain Predicted_Xtest
How can I unscale Predicted_Xtest?
Thanks in advance

A: has been answered before backtransform `scale()` for plotting
t(apply(scaled.data_train, 1, function(r)r*attr(scaled.data_train,'scaled:scale') + attr(scaled.data_train, 'scaled:center')))

Need to apply scaling across each column.


text:
Q: expl3 property list values as `clist` vs token lists I have a (potentially) long property list, which values, at the moment, are just token lists. Now, I want to implement that some of the keys may have multiple values. I will store these multiple values in clists.
So, for each key I have to test if the value is a clist or just a token list.
The case where the key may have just only one value can be seen as a special case of the clist, where just only one value can be inserted in the list.
I ask for advice, which approach will be easier to program:

*

*values that can be either token lists or clists? or

*values that all are clists, but some of them can only have one element?

(key, value) pairs will be set usually just once, and the value will be retrieved a few times (some of them several times, but I don't spect more than five times). I don't foresee a big difference in running time for both approaches. I an not sure if memory efficiency will be an issue with the "all clist approach."
EDIT
egreg's answwr is great (as usual). But I did not explain the problem at full. At the time to set the (key, value) pair for the first time, I don't have all the elements of list (if it is a list). So, I would have to:

*

*Retrieve the value,

*Check if it a list,

*Insert the new value in the list

several times until the list type keys are filled. If I define all the values as clists. I can skip step number 2.  But them, when retrieved I guess I have to check if the key is a list or not.
The question boils down to the point if skipping step 2 make programming easier or not.
(After a deeper thought, it probably is equally easy/complicated because it is just moving the harder part to the setting or the retrieving of the values)

A: \prop_put:Nnn is agnostic about the data you store in the sense that it does no interpretation to it; it's much like \tl_set:Nn in this respect, so in a sense a property list (plist) is a collection of token lists (tl) indexed by name.
Can this be a collection of clists? Yes, why not?
You can store the value as usual
\prop_put:Nnn \l_textnik_test_prop { a } { 1,2,3,4 }

and then retrieve it by assigning it to a tl variable:
\cs_new_protected:Nn \textnik_prop_get_clist:NnN
 {
  \prop_get:NnN #1 {#2} \l__textnik_prop_get_clist_tl
  \clist_set:NV #3 \l__textnik_prop_get_clist_tl
 }

so that
\textnik_prop_get_clist:NnN \l_textnik_test_prop { a } \l_textnik_test_clist

will do the same as
\clist_set:Nn \l_textnik_test_clist { 1,2,3,4 }

If you want to extract the value as a tl, use \clist_get:NnN.

Here's a different implementation: each property refers to a clist.
\documentclass{article}
\usepackage{expl3}

\ExplSyntaxOn
% Define a new data type pcl, only local settings.
% Add variants as needed and support for global setting.
\cs_new_eq:NN \textnik_pcl_new:N \prop_new:N
\cs_new_eq:NN \textnik_pcl_clear_new:N \prop_clear_new:N
\cs_new_eq:NN \textnik_pcl_clear:N \prop_clear:N
\cs_new_eq:NN \textnik_pcl_set_eq:NN \prop_set_eq:NN
\cs_new_eq:NN \textnik_pcl_remove:NN \prop_remove:NN

% a global counter
\int_new:N \g__textnik_pcl_serial_int

\cs_new_protected:Nn \__textnik_pcl_check:Nn
 {
  \prop_if_in:NnF #1 { #2 }
   {% the property doesn't already exist
    \int_gincr:N \g__textnik_pcl_serial_int
    \prop_put:Nnx #1 { #2 } { \int_to_arabic:n { \g__textnik_pcl_serial_int } }
    \clist_new:c { l__textnik_pcl_ \int_to_arabic:n { \g__textnik_pcl_serial_int } _clist }
   }
 }

% adding items to a pcl
\cs_new_protected:Nn \textnik_pcl_put:Nnn
 {
  \__textnik_pcl_check:Nn #1 { #2 }
  \clist_set:cn { l__textnik_pcl_ \prop_item:Nn #1 { #2 } _clist } { #3 }
 }
\cs_new_protected:Nn \textnik_pcl_put_left:Nnn
 {
  \__textnik_pcl_check:Nn #1 { #2 }
  \clist_put_left:cn { l__textnik_pcl_ \prop_item:Nn #1 { #2 } _clist } { #3 }
 }
\cs_new_protected:Nn \textnik_pcl_put_right:Nnn
 {
  \__textnik_pcl_check:Nn #1 { #2 }
  \clist_put_right:cn { l__textnik_pcl_ \prop_item:Nn #1 { #2 } _clist } { #3 }
 }

% retrieving items from a pcl
\cs_new_protected:Nn \textnik_pcl_get:NnN
 {
  \clist_set_eq:Nc #3 { l__textnik_pcl_ \prop_item:Nn #1 { #2 } _clist }
 }

% showing a pcl
\cs_new_protected:Nn \textnik_pcl_show:N
 {
  \prop_map_function:NN #1 \__textnik_pcl_show:nn
 }
\cs_new_protected:Nn \__textnik_pcl_show:nn
 {
  \clist_show:c { l__textnik_pcl_ #2 _clist }
 }

%%%% Test

\textnik_pcl_new:N \l_textnik_test_pcl
\textnik_pcl_put:Nnn \l_textnik_test_pcl { A } { A1,A2,A3 }
\textnik_pcl_put_right:Nnn \l_textnik_test_pcl { A } { A4,A5 }
\textnik_pcl_put_left:Nnn \l_textnik_test_pcl { A } { A0 }
\textnik_pcl_put:Nnn \l_textnik_test_pcl { B } { B1,B2,B3 }
\textnik_pcl_put_right:Nnn \l_textnik_test_pcl { B } { B4,B5 }
\textnik_pcl_put_left:Nnn \l_textnik_test_pcl { B } { B0 }

\clist_new:N \l_textnik_test_clist
\textnik_pcl_get:NnN \l_textnik_test_pcl {A} \l_textnik_test_clist
\clist_show:N \l_textnik_test_clist
\textnik_pcl_get:NnN \l_textnik_test_pcl {B} \l_textnik_test_clist
\clist_show:N \l_textnik_test_clist

%\textnik_pcl_show:N \l_textnik_test_pcl

A pcl is actually a prop, but the properties stored are just numbers that refer to an array of clists.
The output is
The comma list \l_textnik_test_clist contains the items (without outer
braces):
>  {A0}
>  {A1}
>  {A2}
>  {A3}
>  {A4}
>  {A5}.
<recently read> }

l.71 \clist_show:N \l_textnik_test_clist

?
The comma list \l_textnik_test_clist contains the items (without outer
braces):
>  {B0}
>  {B1}
>  {B2}
>  {B3}
>  {B4}
>  {B5}.
<recently read> }

l.73 \clist_show:N \l_textnik_test_clist


text:
Q: Approximating a volume along a submersion Here is the setup. I have a submersion $f:X \to T$, where $X$ is manifold and $T$ is a torus (you can chose a circle for the beginning if it is simpler). The manifold $X$ has a volume form $\alpha$ that is can be locally decomposed as $\alpha' \wedge f^* \alpha_S$ where $\alpha_S$ is the standard volume form of the torus (its Haar measure). I want to compute the volume of $X$.
To do this, I look at $T_k \subset T$ the subset of $k$-torsion points (or roots of unity if we take the simplified case of a circle) for all $k\geq 1$. I write $X_k=f^{-1}(T_k)$. Then it happens that $T_k$ has a finite volume (for the transverse volume form $\alpha'$) and that $vol(X_k)/k^{dim(T)}$ converges as $k$ goes to $\infty$.
Can I conclude with this fact that the volume of $X$ is finite? and that it is equal to $lim(vol(X_k))$?
PS: beware that I do not know a priori if $f^{-1}(t)$ has a finite volume for a general $t\in T$.


text:
Q: Considering for developing code for managed package I have a question in managed package.
Let say I am writing a SOQL query in Apex class as
/* Apex */
[SELECT Id, custom1__c, custom2__c, custom3__c FROM CustomObject__c];

/* VF or Aura */
<input value="{obj.custom1__c}" />

/*Script */
var a = obj.custom1__c;

Here let's say I am creating a Managed package along with this Class and has NameSpace as abc__
Once installed in an org how does the above field or object behaves? Will I get the correct data without Error.
What are the components (Like Aura components, VF page, Apex) that get affected when installed and If NameSpace was not considered while developing the code?
What is the consideration for this?

Dynamic query with the namespace method is the correct option?

A: Generally speaking the managed package code base does not need to explicitly provide namespace prefixing (for Apex classes, custom objects, custom fields, field sets etc.). The Salesforce runtime understands the context of the class/object/field reference and will automatically apply the namespace prefix transparently when done within the package's code base.
LWCs have to be written using the "c-" namespace prefix "placeholder". LWCs in a managed package can be set "exposed" and thus can be dropped into Lightning Pages using the Lightning App Builder, but you cannot use a custom LWC from a package in the template of an LWC not in that package. In terms of accessing SObject data directly within LWC components using uiRecordApi's getRecord (for example) you would need to use namespaced access. You could do it like:
const field = data.fields.namespace__FieldName__c || data.fields.FieldName__c;
const value = field.value;

This allows the LWC to work with or without namespacing. However, that's not important if you plan to permanently namespace the code.
Aura is a slightly different issue; if you want to reference your components (e.g. using LightningOut and Visualforce, or when referencing another component from a component's cmp markup) you have to write reference your Aura components using the package's namespace prefix. Thus, if you wrote your code with two Aura components, "parent" and "child", and had the parent markup like:
<aura:component ...>
    <c:child ...></c:child>
</aura:component>

This will fail when you package it. You must change it to use the namespace prefix (e.g. "prefix") thus:
<aura:component ...>
    <prefix:child ...></prefix:child>
</aura:component>

Thus, your SOQL, VF and Apex will work as-is, but you have to namespace your Aura components and consider how SObject data access works in LWC. Any use of the (global) classes, objects or fields etc. outside the package will, however, need to include the namespace prefix in order to work.
UPDATE: With the recent (2022) introduction of Lightning Web Security as a replacement for the Locker Service, cross-namespace LWC usage becomes possible. See this overview comparison documentation for details. This means you should be able to use a component from a package in the template markup for a component outside that package. There are documented limitations.


text:
Q: Autoscaling Stateless MIG while retaining instance names We have a process that needs to be auto-scaled and new instances need to be of a specific format.  I've found documentation that says this can be done via an MIG but very little information on how to accomplish this:
Basically right now each of our instances in our stateless MIG pops up as -xxxx where the xxxx is a 4 digit random alphanumeric string.  We would like to create a pool of instance names it can pull from when auto-scaling.
The section of documentation which I believe shows that stateless instances can retain their instance name.
(From https://cloud.google.com/compute/docs/instance-groups/stateful-migs)
Screenshot of the section of documentation which gives some more information but no specific instructions.  I've tried working with this but new instances that are added via auto-scaling are still given generic names.
(From https://cloud.google.com/compute/docs/instance-groups/working-with-managed-instances#adding_instances_with_specific_names)

A: You're right, the documentation related to name specification during a managed instance creation can be found here
Do not hesitate if you have a specific question.


text:
Q: Solid coloured wallpaper for Home Screen on my iPhone I had a wallpaper on my iPhone (running iOS 12), which I had to change (because details were incorrect). So far so good, but I made the mistake of changing both.
How can I get a plain background on the Home Screen without any distracting graphics?
I seem to be able to select a Black background, but nothing else from the default wallpaper set. I am sure there were more options on older iOS versions.

A: I'm assuming you are selecting from the official backgrounds that are under Settings > Wallpaper > Choose a New Wallpaper menu. There used to be more plain backgrounds available, but Apple keeps removing the older ones after each iOS update. If you want to access older iOS wallpapers, check out this gallery (there are some plain backgrounds under iOS 7):

*

*iOS Wallpapers
In case you want to set your own wallpaper, simply save the image to your gallery, tap the share icon on the bottom left, and select the Use as Wallpaper option.

A:
How can I get a plain background on the home screen without any distracting graphics?

By default, iOS 12 contain only one solid colored image for wallpaper which is Black.
It is not possible via built-in iOS Wallpaper setting to generate random solid color for use as Home Screen and/or Lock Screen background. To get a plain background on your Home screen, you simply need to obtain/generate a solid colored image with the desired background colour.
The same is illustrated below step-by-step:

*

*Obtain/generate an image with the desired background colour. It's not mandatory, but generally a good idea to match the image resolution with the device screen resolution or get a higher resolution one. One is attached for example below. It's an image with the color code #767676 with 3360 × 2100 resolution.

*Now save it in the Photos app on your iPhone. There are multiple ways to do so, you can AirDrop it from your another device, transfer via a messenger app, email it to yourself, or simply host it somewhere, open it in Safari and save it in Photos. You should have the image appear in your Camera Roll.

*Select the image or tap to view it. Tap on the Share button at the bottom left of the screen to open the Share sheet and tap Use as Wallpaper option in the bottom row.

*You'll be shown a preview of the screen with the image set as wallpaper. Select Still (as there's no point in selecting Perspective as its a solid image) and tap on Set button.

*Now you'll be prompted to set the image as wallpaper for either Lock Screen, Home Screen or both. Since you require plain background only on the Home Screen, tap on Set Home Screen.

*Voila, your new Home Screen background is set with the solid color of your choosing. I personally like this color as it lets me clearly see all the app icons along with their names.


text:
Q: Oracle Apex pass multiple Values to another page I want to pass the value of two items from an sql select to two page items in another page within my CARD_LINK. I want to do this with the apex.page.get_url() function.
It looks like:
apex_page.get_url(p_page => 360, p_items => 'P360_PERSON_ID,P360_PERSON_TYPE', p_values => 'e.id,e.type') CARD_LINK
That's the recommended way to do this, but in the other page (360) the values for the items are e.id and e.type, not the real values given by the sql select.
Does anybody know help?
Thanks

A: You can do like this:
apex_page.get_url(
  p_page => '11',
  p_clear_cache => '11',
  p_items => 'p11_id,p11_parent_id',
  p_values =>  table.id||','||parent_table.id
) as some_link


text:
Q: Trying to setText() crashes Android app When I try to populate the 'lightName' TextView in the code below this works fine, but when I try to do the same with the 'pressureName' then my app crashes
public class ViewSensorData extends ActionBarActivity {

    TextView lightName;
    TextView pressureName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sensor_data);

        lightName = (TextView) findViewById(R.id.sensor_name_1);
        lightName.setText(R.string.display_light);

        pressureName = (TextView) findViewById(R.id.sensor_name_4);
        pressureName.setText(R.string.display_pressure);
    }
}

The activity_sensor_data.xml file looks ilke this
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mycompany.myfirstapp.ViewSensorData">

    <TextView
        android:layout_width="211dp"
        android:layout_height="wrap_content"
        android:id="@+id/sensor_name_1"
        android:layout_row="1"
        android:layout_column="1" />

    <TextView
        android:layout_width="211dp"
        android:layout_height="wrap_content"
        android:id="@+id/sensor_name_4"
        android:layout_row="4"
        android:layout_column="1" />
</GridLayout>

Finally, my logcat looks like this
02-19 23:44:39.071    2685-2685/com.mycompany.myfirstapp I/PersonaManager﹕ getPersonaService() name persona_policy
02-19 23:44:39.101    2685-2685/com.mycompany.myfirstapp D/AndroidRuntime﹕ Shutting down VM
02-19 23:44:39.101    2685-2685/com.mycompany.myfirstapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418afda0)
02-19 23:44:39.101    2685-2685/com.mycompany.myfirstapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mycompany.myfirstapp, PID: 2685
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.myfirstapp/com.mycompany.myfirstapp.ViewSensorData}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.mycompany.myfirstapp.ViewSensorData.onCreate(ViewSensorData.java:32)
            at android.app.Activity.performCreate(Activity.java:5426)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
02-19 23:49:39.173    2685-2685/com.mycompany.myfirstapp I/Process﹕ Sending signal. PID: 2685 SIG: 9

A: You should get resource by its id and than set it
lightName.setText(getResources().getString(R.string.display_light));

A: Hanging my head in shame here. I had changed the minimum SDK to 14, which in turn had generated an additional activity_sensor_data.xml(v14) file. As soon as I edited this file, the pressureName TextView populates as expected.


text:
Q: Turn off hot reload on project started with vue-cli 3 (webpack 4.15.1) It looks like this configuration has changed for each version of webpack, and the project created with vue-cli changes the way the webpack configuration is specified. I've tried all the solutions I've found on this site and they all appear to be targeting different versions of webpack.
I would like to completely turn off automatic reloading of my webpage when I make a change to a js file. I really don't mind hitting refresh myself, and the automatic reloading is often getting in the way.
I created my project with:

npm install -g @vue/cli
vue create my-project

and I start my dev server with:

npm run serve

which calls:

vue-cli-service serve

It looks like I should be able to pass something in my vue.config.js file, but I can't figure out what. There is a section in there configureWebpack, but I tried putting various solutions in there, but my page still refreshes continually.
Thanks for any pointers! I have had a hard time finding up to date documentation on this.
EDIT:
I created a new project and I have the following vue.config.js file:
module.exports = {
  lintOnSave: false
}

I see by the instructions that I need to use:
module: {
  rules: [
    {
      test: /\.vue$/,
      loader: 'vue-loader',
      options: {
        hotReload: false // disables Hot Reload
      }
    }
  ]
}

But I'm not sure where that goes. I think that is describing a different config file.
Also, if I'm reading that correctly, that will only affect .vue files. What if I change a .js file?

A: Got this from a conversation on reddit:
NOTE: This works if you are not using the Vue dev server (Node express server). If you are using the Vue dev server, it may prevent the initial load of your app. In my case I am using a Tomcat server, so I have no problems with this method:
Put this in your vue.config.js
chainWebpack: config => {

    config.plugins.delete('hmr');
},

See: https://www.reddit.com/r/vuejs/comments/9njfl5/having_some_pain_disabling_the_hot_reloading/
edit:
For the record, here is how I am running the Vue build in watch mode, using the "devw" script in my package json as shown below.  This way vue rebuilds the pacakge after every code update, and I reload in my browser with Ctrl-F5. I am not using the "serve" script (which launches the Express server).
  "scripts": {
    "dev": "vue-cli-service build --mode development",
    "devw": "vue-cli-service build --mode development --watch ",  //USE THIS
    "serve": "vue-cli-service serve",   //DON'T USE
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

[vue-cli-3]

A: See https://github.com/vuejs/vue-cli/issues/4368#issuecomment-515532738
module.exports = {
  devServer: {
    hot: false,
    liveReload: false
  }
}

A: You can disable hot reload by defining the following param in your config:
hotReload: false

Detailled instructions can be found in the official manual:


text:
Q: Flex: How to define a term to be the first one at the beginning of a line(exclusively) I need some help regarding a problem I face in my flex code.
My task: To write a flex code which recognizes the declaration part of a programming language, described below.
Let a programming language PL. Its variable definition part is described as follows:
At the beginning we have to start with the keyword "var". After writing this keyword we have to write the variable names(one or more) separated by commas ",". Then a colon ":" is inserted and after that we must write the variable type(say real, boolean, integer or char in my example) followed by a semicolon ";". After doing the previous steps there is the potentiality to declare into a new line new variables(variable names separated by commas "," followed by colon ":" followed by variable type followed by a semicolon ";"), but we must not use the "var" keyword again at the beginning of the new line( the "var" keyword is written once!!!)
E.g.
var number_of_attendants, sum: integer;
ticket_price: real;
symbols: char;

Concretely, I do not know how to make it possible to define that each and every declaration part must start only with the 'var' keyword. Until now, if I would begin a declaration part directly declaring a variable, say x (without having written "var" at the beginning of the line), then no error would occur(unwanted state).
My current flex code below:
%{
#include <stdio.h>
%}
VAR_DEFINER "var"
VAR_NAME [a-zA-Z][a-zA-Z0-9_]*
VAR_TYPE "real"|"boolean"|"integer"|"char"
SUBEXPRESSION [{VAR_NAME}[","{VAR_NAME}]*":"[ \t\n]*{VAR_TYPE}";"]+
EXPRESSION {VAR_DEFINER}{SUBEXPRESSION}
%%
^{EXPRESSION}                 {
                                  printf("This is not a well-syntaxed expression!\n");
                                  return 0;
                            }
{EXPRESSION}                        printf("This is a well-syntaxed expression!\n");
";"[ \t\n]*{VAR_DEFINER}    {
                                  printf("The keyword 'var' is defined once at the beginning of a new line. You can not use it again\n");
                                  return 0;
                            }
{VAR_DEFINER}                  printf("A keyword: %s\n", yytext);
^{VAR_DEFINER}                 printf("Each and every declaration part must start with the 'var' keyword.\n");
{VAR_TYPE}";"                     printf("The variable type is: %s\n", yytext);
{VAR_NAME}                        printf("A variable name: %s\n", yytext);
","/[ \t\n]*{VAR_NAME}            /* eat up commas */
":"/[ \t\n]*{VAR_TYPE}";"         /* eat up single colon */
[ \t\n]+                          /* eat up whitespace */
.                           {
                                  printf("Unrecognized character: %s\n", yytext);
                                  return 0;
                            }
%%
main(argc, argv)
int argc;
char** argv;
{
++argv, --argc;
if (argc > 0)
yyin = fopen(argv[0],"r");
else
yyin = stdin;
yylex();
}

I hope to have made it as much as possible clear.
I am looking forward to reading your answers!

A: You seem to be trying to do too much in the scanner. Do you really have to do everything in Flex? In other words, is this an exercise to learn advanced use of Flex, or is it a problem that may be solved using more appropriate tools?
I've read that the first Fortran compiler took 18 staff-years to create, back in the 1950's. Today, "a substantial compiler can be implemented even as a student project in a one-semester compiler design course", as the Dragon Book from 1986 says. One of the main reasons for this increased efficiency is that we have learned how to divide the compiler into modules that can be constructed separately. The two first such parts, or phases, of a typical compiler is the scanner and the parser.
The scanner, or lexical analyzer, can be generated by Flex from a specification file, or constructed otherwise. Its job is to read the input, which consists of a sequence of characters, and split it into a sequence of tokens. A token is the smallest meaningful part of the input language, such as a semicolon, the keyword var, the identifier number_of_attendants, or the operator <=. You should not use the scanner to do more than that.
Here is how I woould write a simplified Flex specification for your tokens:
[ \t\n] { /* Ignore all whitespace */ }
var { return VAR; }
real { return REAL; }
boolean { return BOOLEAN; }
integer { return INTEGER; }
char { return CHAR; }
[a-zA-Z][a-zA-Z0-9_]* { return VAR_NAME; }
. { return yytext[0]; }

The sequence of tokens is then passed on to the parser, or syntactical analyzer. The parser compares the token sequence with the grammar for the language. For example, the input var number_of_attendants, sum : integer; consists of the keyword var, a comma-separated list of variables, a colon, a data type keyword, and a semicolon. If I understand what your input is supposed to look like, perhaps this grammar would be correct:
program : VAR typedecls ;
typedecls : typedecl | typedecls typedecl ;
typedecl : varlist ':' var_type ';' ;
varlist : VAR_NAME | varlist ',' VAR_NAME ;
var_type : REAL | BOOLEAN | INTEGER | CHAR ;

This grammar happens to be written in a format that Bison, a parser-generator that often is used together with Flex, can understand.
If you separate your solution into a lexical part, using Flex, and a grammar part, using Bison, your life is likely to be much simpler and happier.


text:
Q: Cant access apprtc from another machine in same network Iam new in webRtc. I need to run appRtc application on my local machine. I got the codebase from github and successfully run on my local ubuntu machine.
these are logs when try with browser on my pc
INFO     2017-11-30 09:00:18,966 api_server.py:205] Starting API server at: http://localhost:51242
WARNING  2017-11-30 09:00:18,976 inotify_file_watcher.py:196] There are too many directories in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
INFO     2017-11-30 09:00:18,976 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO     2017-11-30 09:00:18,978 admin_server.py:116] Starting admin server at: http://localhost:8000
INFO     2017-11-30 09:00:43,290 apprtc.py:93] Applying media constraints: {'video': {'mandatory': {}, 'optional': [{'minWidth': '1280'}, {'minHeight': '720'}]}, 'audio': True}
WARNING  2017-11-30 09:00:43,299 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
INFO     2017-11-30 09:00:43,370 module.py:788] default: "GET / HTTP/1.1" 200 8616
INFO     2017-11-30 09:00:43,430 module.py:788] default: "GET /callstats/callstats.min.js HTTP/1.1" 304 -
INFO     2017-11-30 09:00:43,433 module.py:788] default: "GET /css/main.css HTTP/1.1" 304 -
INFO     2017-11-30 09:00:43,491 module.py:788] default: "GET /js/apprtc.debug.js HTTP/1.1" 304 -
INFO     2017-11-30 09:00:47,736 apprtc.py:417] Added client 02588444 in room 490664053, retries = 0
INFO     2017-11-30 09:00:47,738 apprtc.py:93] Applying media constraints: {'video': {'mandatory': {}, 'optional': [{'minWidth': '1280'}, {'minHeight': '720'}]}, 'audio': True}
WARNING  2017-11-30 09:00:47,746 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
INFO     2017-11-30 09:00:47,748 apprtc.py:560] User 02588444 joined room 490664053
INFO     2017-11-30 09:00:47,751 apprtc.py:561] Room 490664053 has state ['02588444']
INFO     2017-11-30 09:00:47,902 module.py:788] default: "POST /join/490664053 HTTP/1.1" 200 1199
INFO     2017-11-30 09:00:49,820 apprtc.py:485] Saved message for client 02588444:{True, 1} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,833 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,880 apprtc.py:485] Saved message for client 02588444:{True, 2} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,894 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,930 apprtc.py:485] Saved message for client 02588444:{True, 3} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,958 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:49,970 apprtc.py:485] Saved message for client 02588444:{True, 4} in room 490664053, retries=0
INFO     2017-11-30 09:00:49,982 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21
INFO     2017-11-30 09:00:50,074 apprtc.py:485] Saved message for client 02588444:{True, 5} in room 490664053, retries=0
INFO     2017-11-30 09:00:50,084 module.py:788] default: "POST /message/490664053/02588444 HTTP/1.1" 200 21

I can open apprtc application on my browser. But i canot access from any other machine in same network.
these are the logs when try with browser on any other pc in same network.
INFO     2017-11-30 08:55:06,749 api_server.py:205] Starting API server at: http://localhost:55410
    WARNING  2017-11-30 08:55:06,758 inotify_file_watcher.py:196] There are too many directories in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
    INFO     2017-11-30 08:55:06,759 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
    INFO     2017-11-30 08:55:06,760 admin_server.py:116] Starting admin server at: http://localhost:8000
    INFO     2017-11-30 08:55:10,582 apprtc.py:93] Applying media constraints: {'audio': True, 'video': {'optional': [{'minWidth': '1280'}, {'minHeight': '720'}], 'mandatory': {}}}
    WARNING  2017-11-30 08:55:10,589 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
    INFO     2017-11-30 08:55:10,636 module.py:788] default: "GET / HTTP/1.1" 200 8616
    INFO     2017-11-30 08:55:10,685 module.py:788] default: "GET /css/main.css HTTP/1.1" 200 6402
    INFO     2017-11-30 08:55:10,689 module.py:788] default: "GET /callstats/callstats.min.js HTTP/1.1" 200 245432
    INFO     2017-11-30 08:55:10,696 module.py:788] default: "GET /js/apprtc.debug.js HTTP/1.1" 200 101567
    INFO     2017-11-30 08:55:11,086 module.py:788] default: "GET /images/webrtc-icon-192x192.png HTTP/1.1" 200 31806
    INFO     2017-11-30 08:55:18,872 apprtc.py:417] Added client 26553344 in room 419183955, retries = 0
    INFO     2017-11-30 08:55:18,874 apprtc.py:93] Applying media constraints: {'audio': True, 'video': {'optional': [{'minWidth': '1280'}, {'minHeight': '720'}], 'mandatory': {}}}
    WARNING  2017-11-30 08:55:18,879 apprtc.py:137] Invalid or no value returned from memcache, using fallback: null
    INFO     2017-11-30 08:55:18,880 apprtc.py:560] User 26553344 joined room 419183955
    INFO     2017-11-30 08:55:18,881 apprtc.py:561] Room 419183955 has state ['26553344']
    INFO     2017-11-30 08:55:18,896 module.py:788] default: "POST /join/419183955 HTTP/1.1" 200 1203
    INFO     2017-11-30 08:55:24,331 module.py:788] default: "GET /images/webrtc-icon-192x192.png HTTP/1.1" 304 -
    INFO     2017-11-30 08:55:24,363 apprtc.py:485] Saved message for client 26553344:{True, 1} in room 419183955, retries=0
    INFO     2017-11-30 08:55:24,383 module.py:788] default: "POST /message/419183955/26553344 HTTP/1.1" 200 21
    INFO     2017-11-30 08:55:24,396 apprtc.py:485] Saved message for client 26553344:{True, 2} in room 419183955, retries=1
    INFO     2017-11-30 08:55:24,405 module.py:788] default: "POST /message/419183955/26553344 HTTP/1.1" 200 21
    INFO     2017-11-30 08:55:58,211 apprtc.py:455] Removed client 26553344 from room 419183955, retries=0
    INFO     2017-11-30 08:55:58,212 apprtc.py:494] Room 419183955 has state None
    INFO     2017-11-30 08:55:58,221 module.py:788] default: "POST /leave/419183955/26553344 HTTP/1.1" 200 -
    INFO     2017-11-30 08:55:59,071 module.py:788] default: "GET /r/ HTTP/1.1" 404 154
    INFO     2017-11-30 08:56:00,542 module.py:788] default: "GET /favicon.ico HTTP/1.1" 404 154

The browser shows some error message like this
Failed to get access to local media. Error name was NotSupportedError. Continuing without sending a stream.

Why this behaviour? i need to access from other pc. is this possible?

A: Please do enable SSL. The access will only work with SSL


text:
Q: When Stitching using HotChocolate, How Can A Remote Schema's Type Be Renamed? Here's my scenario. I have a GraphQL gateway that stitches a dozen or so remote schemas together, using the following code:
services.AddHttpClient(schema.TypeName, c => c.BaseAddress = new Uri(schema.Url));

public virtual void Add(IRequestExecutorBuilder builder, bool ignoreRootTypes = true)
{
    var type = this.GetType();
    builder.AddRemoteSchema(type.Name, ignoreRootTypes);
}

Assume that the remote schemas are immutable. One of the remote schemas has a type called Name. This appears to be a reserved keyword, because during stitching, I get the exception:

For more details look at the Errors property.

*

*An item with the same key has already been added. Key: Name

I can correct this error by modifying the Name type of the remote service to be something like PersonName, however, as I mentioned above, these external schemas should be immutable.
Is there a way to rename a restricted type before this exception is thrown at the Gateway level?

A: Add a call to RenameType:
public virtual void Add(IRequestExecutorBuilder builder, bool ignoreRootTypes = true)
{
    var type = this.GetType();
    builder.AddRemoteSchema(type.Name, ignoreRootTypes);
    builder.RenameType("Name", "PersonName", type.Name);
}

This will rename the incoming type from your remote schema to something else.


text:
Q: MySql - Get all occurring I have an MySql DB.
My main table is all the sentences of a series of 5 books, with indexes for the book, chapter in book, sentence in chapter.
Example - For Harry Potter book five, chapter 1 , sentence 3 I'll have a row like that.
BookID   ChapterID   SentenceID   Text
   4         1           3          Deprived of their usual car-washing and lawn-mowing pursuits, the inhabitants of Privet Drive had retreated into the shade of their cool houses, windows thrown wide in the hope of tempting in a nonexistent breeze.

I need to retrieve all the occurrence of a letter or a word.
So if I search for 'e' I'll get the same row 17 times. 'e' occur 17 time in this row.
I've simplified the scenario, I have more information to retrieve for each letter.
So far I've been unable to get something useful.
Thank you

A: I'm 90% certain an SQL query won't return more than one row for a given database row, unless you use a JOIN. But that would be very inefficient for your purposes.
The way this would typically be implemented is using a query like SELECT * FROM books WHERE Text LIKE '%e%', which would return all of the rows that have at least one "e" in the text; then your application would iterate over the rows and count the occurrences.


text:
Q: python to mysql insert error I'm trying to insert data into a database hosted on Network Solutions using python and the code below. I was able to successfully connect to the db but when I tried to insert the data into the table I get this error:
1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`focused`.`test_results`, CONSTRAINT `test_results_practice_tests_FK` FOREIGN KEY (`practice_test_id1`) REFERENCES `practice_tests` (`practice_test_id`))

import mysql.connector
from mysql.connector import errorcode

config = {
  'user': '{user}',
  'password': '{psswd}',
  'host': '{host}',
  'database': '{dbname}',
  'raise_on_warnings': True,
}

try:
  cnx = mysql.connector.connect(**config)
  cursor = cnx.cursor()

  query = """INSERT INTO test_results (result_id, student_id1, practice_test_id1, section_1_score, section_1_missed, section_2_score, section_2_missed, section_3_score, section_3_missed, section_4_score, section_4_missed, e_reading_score, e_analysis_score, e_writing_score, command_score, command_missed, words_score, words_missed, expression_score, expression_missed, heart_score, heart_missed, standard_score, standard_missed, problem_score, problem_missed, passport_score, passport_missed, history_score, history_missed, science_score, science_missed, math_score, reading_score) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
  data_test_result = (1, 1, 1, 1, '', 1, '', 1, '', 1, '', 1, 1, 1, 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, 1)
  cursor.execute(query, data_test_result)

except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cnx.close()

This is a picture of the table structure for reference.

I was wondering what I can do to solve this problem and successfully insert the data into the table. Thanks so much for your help in advance!

A: The meaning of the error message is that the database structure defines a relationship between the table into which you are inserting data and another table called practice_tests. Values in your practise_test_id1 column are therefore required to exist as primary key values in the practice_tests table to maintain the "relational integrity" of the structure.
You should find that if you insert an appropriate row into practice_tests your code will work - but don't forget to call the connection's commit method otherwise your changes won't be made permanent.


text:
Q: Select a different Element inside XML Windows Phone I have managed to get the following to work, this gets all the services in the XML below.
But there is one Service that is outside of the elements, but the rest are in.
I need all services to be in one list.
As you can see from the XML service '1' is outside whereas the '1a' service is inside and the rest are here.
How do I modify the following code or additional code to select all services in one list?
var routeNames = (from n in doc.Descendants(ns + "ArrayOfService
                     select new RootContainer
                          {
                            Stops = (from s in n.Elements(ns + "Service").Elements(ns + "client").Elements(ns + "services").Elements(ns + "Service")

                                       select new Stops

                                       {

                                           NaptanCode = s.Element(ns + "serviceDescription").Value,
                                           StopName = "/Images/Services/" + s.Element(ns + "serviceName").Value + ".png",
                                           StopId = s.Element(ns + "serviceId").Value
                                       }).ToList()
                          }).Single();

        listServices.ItemsSource = routeNames.Stops;

xml:
         <ArrayOfService xmlns="http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Service z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
     <client z:Id="i3">
       <services>
        <Service z:Id="i5">
          <serviceDescription>Whitehawk - County Hospital - City Centre - Hove - Portslade - Mile Oak</serviceDescription>
          <serviceName>1A</serviceName>
          <serviceText>Whitehawk - Mile Oak</serviceText>
        </Service>
       </services>
     </client>
     <serviceDescription>Whitehawk - County Hospital - City Centre - Hove - Portslade - Mile Oak</serviceDescription>
     <serviceName>1</serviceName>
   </Service>
  </ArrayOfService>

A: Try this
var routeNames = doc.Descendants(ns + "client").FirstOrDefault().Descendants(ns + "Service").Select(s => new {
                    NaptanCode = s.Element(ns + "serviceDescription").Value,
                    StopName = "/Images/Services/" + s.Element(ns + "serviceName").Value + ".png",
                    StopId = s.Element(ns + "serviceId").Value
                }).ToList();

to get both level of service use this
           var routeNames = doc.Descendants(ns + "ArrayOfService").FirstOrDefault().Elements(ns + "Service").Select(x => new {
                serviceDescription = (string)x.Element(ns + "serviceDescription"),
                serviceName = (string)x.Element(ns + "serviceName"),
                services = x.Descendants(ns + "Service").Select(s => new {
                    NaptanCode = s.Element(ns + "serviceDescription").Value,
                    StopName = "/Images/Services/" + s.Element(ns + "serviceName").Value + ".png",
                    StopId = s.Element(ns + "serviceId").Value
                }).ToList()
            }).ToList();

You can enumerate through query results with following
foreach (var parentService in routeNames)
{
    foreach (var childService in parentService.services)
    {
    }
}


text:
Q: Error in building cordova app. What to do? I am having an error "Cannot find module 'q'" as I build my BlankCordovaApp project. I am using Visual Studio 2015 Preview.
sorry I cant post a picture cause I am new here. Here's what i got after building the project:
1> Rebuild All started: Project: BlankCordovaApp3, Configuration: Debug Android
1> GeneratedJavascript=scripts\index.js;scripts\platformOverrides.js;scripts\index.js;scripts\platformOverrides.js
1> C:\..\..\documents\visual studio 2015\Projects\BlankCordovaApp3\BlankCordovaApp3
 > call "C:\Program Files (x86)\nodejs\"\nodevars.bat
1> Your environment has been set up for using Node.js 0.10.33 (ia32) and npm.
1> MDAVSCLI : error :Cannot find module 'q'
Rebuild All: 0 succeeded, 1 failed, 0 skipped

A: Solution 1
This problem is indicative of a problem with node.js.
Usually, these can be solved by simply going to BUILD/REBUILD SOLUTION in the top menu of Visual Studio.  If that doesn't work, continue with Solution 2 or Solution 3
Solution 2
Navigate to your bld\Debug\platforms\android\cordova\ folder and verify that the q folder exists and has content.  There should be several folders there that resemble the contents of a Git project.  At the very minimum, there should be a package.json file.

*

*You should backup your q folder by renaming it to q_old or something similar.   You can find the node_modules folder at bld\Debug\platforms\android\cordova\.

*Add a new folder called q.

*Copy the package.json file from q_old into your new q folder

*From the new q folder, execute npm install from the CLI (command line interface).

Be aware that this requires a package.json folder, which should be present in your bld\Debug\platforms\android\cordova\ folder.
Solution 3
Try the Node add-on npm-install-missing.  From your CLI, type
npm-install -g npm-install-missing
After that has finished installing, you can simply type npm-install-missing from your project directory, which should look something like this:
C:\Users\<MYUSERNAME>\Visual Studio 2015\Projects\BlankCordovaApp3\> npm-install-missing
Once you've got something in cmd that looks like that, press Enter and you should see something very similar to what occurred when you installed the Node Module node-install-missing.


text:
Q: Make a button perform an SQL statement I'm trying my luck here. I am currently developing a website wherein people should be able to send a message and add a user as a friend from that person's profile page. I have a button, namely [Add as friend] using the basic <button></button> clauses. What would be the best workaround to do this?
For example, I'd like the SQL statment: INSERT into friends (uid, fid, isapproved) VALUES ('1', '2', '1') when the [Add this friend] button is clicked.
I'm working with just php and MySQL for now. Any suggestion would be more than welcome. Thanks, guys.

A: *

*Button calls javascript function.

*Javascript function posts (AJAX,possibly using jquery) to a php file 'addfriend'

*PHP file executes mysql, returns JSON

*Javascript function calls callback and shows return value

A: If you are not using AJAX, something like this should be enough.
addfriend.tpl.php file
<form method="post" action="action_addfriend.php">
 <input type="hidden" value="<?=$userid;?>" name="userid" />
 <input type="submit" value="Add as Friend" />
</form>

action_addfriend.php file
<?php

if ($_POST)
{
  $fid = htmlspecialchars(stripslashes($_POST['userid']));
  $fid = mysql_real_escape_string($fid);
  include("your_connectdb_file.php");
  mysql_query("INSERT into friends (uid, fid, isapproved) VALUES ('1', '$fid', '1')");
  mysql_free_result();
}
?>

A: If you are only using PHP as a scripting language without any javascript, then you should make that button direct to a page which handles the add friend request for the given user_id.
For a friend addition to work on the same page you would need to use javascript and Ajax to make a background call to a php file which will handle the request silently and return a response if it were successful.

A: send AJAX request with POST and/or GET data to url responsible for adding friends, eg: mysupersocialnetwork.org/friend/add/
this page request will trigger php and php will execute script.


text:
Q: Rewrite algorithm as a template function to compare 2 values I am trying to rewrite the selection sort algorithm below as a template function that compares two elements.
here is my sorting algorithm
    #include <iostream>

#include "util.h"

/**
    Gets the position of the smallest element in a vector range.
    @param a the vector
    @param from the beginning of the range
    @param to the end of the range
    @return the position of the smallest element in
    the range a[from]...a[to]
*/
int min_position(vector<int>& a, int from, int to)
{
   int min_pos = from;
   int i;
   for (i = from + 1; i <= to; i++)
      if (a[i] < a[min_pos]) min_pos = i;
   return min_pos;
}

/**
   Sorts a vector using the selection sort algorithm
   @param a the vector to sort
*/

void selection_sort(vector<int>& a)
{
   int next; // The next position to be set to the minimum

   for (next = 0; next < a.size() - 1; next++)
   {
      // Find the position of the minimum
      int min_pos = min_position(a, next, a.size() - 1);
      if (min_pos != next)
         swap(a[min_pos], a[next]);
   }
}

int main()
{
   rand_seed();
   vector<int> v(20);
   for (int i = 0; i < v.size(); i++)
      v[i] = rand_int(1, 100);
   print(v);
   selection_sort(v);
   print(v);
   return 0;
}

I wrote a template to compare the values, but I am having trouble implementing it on my program above.
template <typename T>
void sort(T A[],int N)
{

 for(int n = 1;n < N;n++) {
     T mover = A[n];
     int k = n;
     while(k > 0) {
       if(A[k-1] > mover) {
         A[k] = A[k-1];
        k--;
       } else
         break;
     }
     A[k] = mover;
}

}

I am new to c++ and templates/sorting is giving me fits, so I am looking for some assistance or guidance.
thanks


text:
Q: Resize Grid Items WinRt Can you resize grid items dynamically?
I have a gridview that has a textbox in it. They textbox has a number of bound values that can cause it to grow in size but it does not do so after the app is running.
    <Slider x:Name="FontSizeSlider" Minimum="10" Maximum="120" />

    <GridView ItemsSource="{Binding MyList}" >
        <GridView.ItemTemplate>
            <DataTemplate>
                <TextBlock
                    Height="{Binding ElementName=FontSizeSlider, Path=Value}"
                    Width="{Binding ElementName=FontSizeSlider, Path=Value}"
                    Text="{Binding}"
                    FontSize="{Binding ElementName=FontSizeSlider, Path=Value}"/>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

I realise that the items would have to shuffle around too so that then can fit in the columns. I don't think this is supported in gridview is it?
Is this possible?

A: Fixed it by adding:
        <GridView.ItemsPanel>
            <ItemsPanelTemplate>
                <VariableSizedWrapGrid />
            </ItemsPanelTemplate>
        </GridView.ItemsPanel>


text:
Q: try except not running except part I have a short code that ftps a small file into a server.
session = ftplib.FTP("192.168.0.164", "admin", "admin")
file = open("path/test.txt", "rb")
try:
    session.storbinary("STOR application/test.txt", file)
except:
    print("failed")
else:
    print("success!")
file.close()

In the above piece I changed the IP address to so it would fail (there is no 192.168.0.164 device) and it doesn't print failed like it's supposed to.  In the terminal I get a
"connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" error.
if I mistype the path, I also don't get a failed print on the terminal.
If I type in the correct IP the success part does work.
Am I using the try/except wrong?
UPDATE:
Current code looks like this:
file = open("path/test.txt", "rb")
try:
    session = ftplib.FTP("192.168.0.161", "admin", "admin")
    session.storbinary("STOR application/test.txt", file)
except:
     print("Unable to reach host")
else:
    print("success!")
    session.quit()
finally:
    print ("DONE!!")
    file.close()

I figure the ftplib.all_errors will catch all errors (host unreachable, and file not found).  It seems to catch the unable to reach host errors, but no file not found errors.

A:
Am I using the try/except wrong?

Your syntax is correct, but Python is not actually reaching the try block at all.
When you call session = ftplib.FTP(host, ...) where host is unreachable, the code will stop in its tracks there. That's because FTP.__init__() greedily calls self.connect(). This will in turn call socket.create_connection(), which will not succeed for an unreachable host.
So, you'd need to modify to:
with open("path/test.txt", "rb") as file:
    try:
        session = ftplib.FTP("192.168.0.164", "admin", "admin")
        session.storbinary("STOR application/test.txt", file)
    except Exception as e:
        print("failed")
        print(e)
    else:
        print("success!")
    finally:
        session.quit()


text:
Q: Distribution of rational points in the real locus of a planar algebraic curve Let $C$ be a smooth projective geometrically connected curve over $\mathbb{Q}$. Assume that $g(C)=3$ and that $C$ is not hyperelliptic. Then the canonical sheaf defines a closed immersion $C\to\mathbb{P}^2_{\mathbb{Q}}$. Tensoring with $\mathbb{R}$ and analytifying we get an isotopy class of a nullhomologous one-dimensional submanifold of $\mathbb{R}P^2$ that is either

*

*empty

*one oval

*two ovals not encircling each other

*one oval surrounded by another

*three ovals not encircling each other

*four ovals not encircling each other.

By Faltings's theorem $C$ has finitely many rational points. In fact assuming the weak Lang conjecture there is an absolute bound on how many rational points a curve of fixed genus may have. Has the distribution of the rational points with respect to the real locus been studied?
A similar question has been asked for elliptic curves.


text:
Q: Binary operator '==' cannot be applied to two '[AnyHashable:Any]!' operands I'm going to compare 2 dictionaries in this way:
var previouldObj:[AnyHashable:Any]!
var obj:[AnyHashable:Any]!
for i in 0..<self.arrayData.count
{

     obj=self.arrayData[i] as! [AnyHashable:Any]
     if(obj == previouldObj)
     {

     }
}

But I'm getting this error

Binary operator '==' cannot be applied to two '[AnyHashable:Any]!' operands

How to solve this? Please help me
Thanks

A: One way to do this is to convert previouldObj into an NSDictionary and call isEqual.
    var previouldObj:[AnyHashable:Any]!
    var nsDict = NSDictionary(dictionary: previouldObj)
    var obj:[AnyHashable:Any]!
    for i in 0..<self.arrayData.count
    {

        obj=self.arrayData[i] as! [AnyHashable:Any]
        if(nsDict.isEqual(to: obj))
        {

        }


text:
Q: Combine grep -v with grep -r? I want to remove an entire line of text from all files in a given directory. I know I can use grep -v foo filename to do this one file at a time. And I know I can use grep -r foo to search recursively through a directory. How do I combine these commands to remove a given line of text from all files in a directory?

A: Try something like:
grep -vlre 'foo' . | xargs sed -i 's/pattern/replacement/g'

Broken down:
grep:
  -v 'Inverse match'
  -l 'Show filename'
  -r 'Search recursively'
  -e 'Extended pattern search'

xargs: For each entry perform

sed -i: replace inline

A: The UNIX command to find files is named find, not grep. Forget you ever heard of grep -r as it's just a bad idea, here's the right way to find files and perform some action on them:
find . -type f -print | xargs sed -i '/badline/d'

A: I think this would work:
grep -ilre 'Foo' . | xargs sed -i 'extension' 'Foo/d'
Where 'extension' refers to the addition to the file name. It will make a copy of the original file with the extension you designated and the modified file will have the original filename. I added -i in case you require it to be case insensitive.
modified file1 becomes "file1"
original file1 becomes "file1extension"
invalid command code ., despite escaping periods, using sed
One of the responses suggests that the newer version of sed's -i option in OSX is slightly different so you need to add an extension. The file is being interpreted as a command, which is why you are seeing that error.


text:
Q: windows forms is not working in asp.net unable to integrate Forms authentication in my application. always redirecting to login page . after login its redirecting to login page again . in url its showing - http://localhost:1186/Login.aspx?ReturnUrl=%2fIndex.aspx
web.config
<authentication mode="Forms">
    <forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH"></forms>
</authentication>
<authorization>
    <deny users="?"/>
</authorization>

code behind
login page button click event
objAmin.AdminLoginId = txtUserName.Text.Trim();
objAmin.Password = txtPasssword.Text.Trim();
DataSet dsAdminLoginDetail = objAmin.GetAdminLoginDetails();
DataRowCollection drc = dsAdminLoginDetail.Tables[0].Rows;
if (drc.Count > 0)
{
   lblError.Visible = false;
   DataRow dr = drc[0];
   Response.Redirect("Index.aspx");
}


text:
Q: Shared folder of pc on Mobile I have following setup
Galaxy on8 with Wi-Fi hotspot on : 192.168.43.1
Xolo a500 connected to Wi-Fi hotspot :192.168.43.23
And also same  xolo a500 connected to pc (mint linux) via usb cable with usb tethering ..
So for that connection
xolo a500: 192.168.42.1
Pc:              192.168.42.12
I can access shared folder of pc on xolo a500  via usb connection.
But I can't access the same on galaxy on8.
However if turn on some server app on galaxy on8 and put its ip address on pc I can view that servers interface ..
Or in different word
I can ping galaxy on8 from pc
I can ping xolo a500 with both address.
But I can't ping pc from galaxy on8.
Pc and galaxy on8 are on different subnet..and I can't merge these subnet..
This happens with all the android device
They have 192.168.43.* with Wi-Fi interface.
And 192.168.42.* with usb interface..
These details are same for win7 on same pc.
My question is this
If I can ping galaxy on 8 from pc then why can't I do vice versa ?
And
how I can view shared folder of pc on Galaxy on8 on this setup..?
(I don't want to root my Galaxy on8,but xolo a500 is rooted,and I can interchange position of both device on this setup if that helps!!!!)

A: The could be an issue with netmask. Can you check  Gateway, DNS and other details  using the codes from terminal
ip addr show

and,
ip route show

Check if they correspond with other two, otherwise the galaxy phone is likely to be in a different subnet.

A: run iptables -L in Xolo.
if You find something like this,
Chain FORWARD policy DROP
then it is clear that Xolo a500 is not forwarding packets coming from Wifi Network To USB Network.
you need to change FORWARD policy to ACCEPT in iptables of xolo
to do so instead of typing command ,
install AFWall+ app on rooted xolo,
open it and grant superuser permission to it,
tick WiFi and Lan checkbox of (tethering) - DHCP + DNS services from the list,
then option -> Apply
then option -> Enable Firewall
done..
one other thing ,
if ping from On8 to PC is not working then try to add route from  Galaxy on8 to PC via Xolo A500 in Galaxy on8 by this command
ip route add 192.168.42.0/24 via 192.168.43.23 dev wlan0

if you can't add route in On8 (your Galaxy on9 is NOT rooted)
then make small change on above setup you provided.
1 swicth on hotspot of xolo a500
2 connect galaxy on8 to xolo a500
and everything else remains untouched
now a default route to xolo a500 will be added in Galaxy on8.
done...


text:
Q: C++ Errors in constructors I've got a problem with my code.
I've got a class called Player which looks like this
class Player
{
public:
   ...
Player();
Player(string firstName, string lastName, int birthYear);
~Player();
   ...
};

My source.cpp looks like this
string firstName = ...;
string lastName = ...;
int birth = ...

Player team[x](firstName, lastName, birth); // <--- This is were I get my errors

My errors are saying
error C3074: an array can only be initialized with an initializer-list

error C2466: cannot allocate an array of constant size 0

error C2057: expected constant expression

The constructor I want to use is Player(string firstName, string lastName, int birthYear). I think that I might be using the default constructor in source.cpp
I want to create 5x Player team[x](firstName, lastName, birth)
But this is where I get my errors. Any suggestions?

A: This line simply isn't valid:
Player team[x](firstName, lastName, birth); // <--- This is were I get my errors

It doesn't make sense.  You're trying to declare an array and call a constructor at the same time.  You already created your team array.  If you want to create a Player and assign it then you would use:
team[x] = Player(firstName, lastName, birth);

Of course, you already created a bunch of them (default initialized) when you created the array in the first place. Since this is C++, use a std::vector<Player>.

Also, something that is wrong but is not generating an error:
int matches;
int* dates = new int[matches];

Here, matches is uninitialized and its value is indeterminate. Reading that variable invokes undefined behavior, and certainly you don't want any random size for your array (why aren't you using a vector again?) You need to initialize matches before using it.

A: One problem with your code is that the variable matches hasn't been initialized and has an indeterminate value.
int matches;
int* dates = new int[matches];

You should initialize matches before calling new int[matches].
A team of nrOfPlayers players is constructed when you allocated an array of Players:
Player* team = new Player[nrOfPlayers];

You can now fill in a player's information by creating a temporary Player object and assigning it to an element in team. This will call Player's implicitly defined copy assignment operator:
Replace line 75 with:
team[x] = Player(firstName, lastName, birth); // copy constructor is called


text:
Q: Manually trigger Root Certificate Update on Windows Is there a way to manually trigger a Root Certificate Update?
I'm troubleshooting a problem with a certificate that keeps disappearing from the Certificate Store. I think this is related to Trusted root certificate being automatically removed from store. But I want to be sure, so I need to be able to trigger the Root Certificate Update - otherwise I have to keep waiting for it to happen at some random time.


text:
Q: Where should my raw SQL go in Symfony 2? I'm currently rebuilding my current website using Symfony 2 instead of the previous Codeigniter framework it was running on. I'm completely new to Doctrine too, and I'm having a little trouble working out the best place to put a complicated-ish MySQL query.
I have a service container currently that uses this query via prepare($sql)->execute(), and various functions that use the data it provides. As it stands now, I pass doctrine to the service container, and run the query within. I then use the same service container to do what I want with this data.
To me, it just doesn't feel right fetching and using the database data in the same class? Should I put the execute() query in the entities folder at the bottom of the Doctrine created file, in the entities folder in it's own file, or is it fine where it is?

A: I think, it will the be better way to create a custom repository class in Repository folder for some actions by preparing entity data.
You can read more about custom repository here custom-repository-classes
Further repository can be used throw doctrine.
For example:
$container->get('doctrine')->getRepository('YourBundleName:Entity')->someRepositoryMethod();


text:
Q: WebComponents add elements to sidebar I am about to learn vanilla js web components. I could successfull render some elements generated by webcomponents, now I would like to give it some design and put it inside a sidebar. However I am not sure if this is webcomponents or just design problem, the elements won´t display anymoer after adding the sidebar.
Maybe you could take a look at my code and give me some hints, where I am causing the problem?
@Edit:
As suggested in comment I have put it in fiddle, so you can try it out. Now I understeand the behavior even less, then In fiddle it looks kind as it should and on my local machine not.
    <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>DiceArea</title>

    window.addEventListener('load', () => {
        getUsers();
    });

    function getUsers() {
        const users = ["player1", "player2", "player3", "player4", "player5"];
        const nav = document.createElement("player-nav");
        nav.setAttribute("class", "sidenav")
        document.body.appendChild(nav);

        users.forEach(user => {
            user = document.createElement('table-user');
            nav.appendChild(user);

            user.addEventListener("click", () => {
                alert("lol")
            })
        })
    }

    class User extends HTMLElement {
        constructor() {
            super();
            this.shadow = this.attachShadow({mode: 'open'});
        }

        connectedCallback() {
            this.user();
        }

        user() {
            this.shadow.innerHTML = `

           `
   }
}

customElements.define("table-user", User);

https://jsfiddle.net/9bt8Lk0v/8/
And that is how it look on my local machine:

A: At first sight I see 2 possible problems:

*

*You are doing .createElement('player-nav') but never defined that Custom Element

*You are doing nav.appendChild()
IF nav is an element with shadowDOM, you have to do nav.shadowRoot.appendChild() because the original element content is now 'lightDOM'
see: Difference between Light DOM and Shadow DOM
Your code is still very traditional/oldskool DOM manipulation.
I butchered your JSFiddle into a (quick) example showing some Web Components concepts you can play with:
<template id=TABLE-PLAYERS>

Players

</template>

<template id=PLAYER-NAV>

  <slot name=avatar></slot>

        <slot class=name name=username></slot>

</template>


text:
Q: How to enable MS Word document editing, when the document is protected to use form fields? I have a Word document in which I need to use form fields (populating list entries through VBA). Before handing over the Word document to the end user I have to restrict editing on form fields (Developer - Restrict Editing). But it is restricting the whole document for editing and the user cannot even edit remaining fields in the document.
I have tried stop protecting whole document but that exposes form fields to the user. Also drop-downs don't work on form fields if I don't protect the document.

A: Re:

it is restricting the whole document for editing and the user cannot even edit remaining fields in the document

If those 'other fields' are formfields and you use 'filling in forms' editing restrictions, the editing restrictions do not prevent access to the 'other fields'. And if some other content not using formfields requires user access, you can insert a Section break before & after that content, then leave that Section unprotected when applying the 'filling in forms' editing restrictions.
The same approach works with content controls also.
Note, however, you should not use formfields and content controls in the same document. They weren't designed for use that way and trying to do so is a known source of problems.


text:
Q: Cannot implicitly convert type 'void' to 'object' WPF C# Yo, been working with Console.Application up until now.
And I have the following error which I do not know how to solve this is my code,
    private void CpuLabel_OnLoaded(object sender, RoutedEventArgs e)
    {
        CpuLabel.Content = GetComponent("Win32_Processor", "Name");
    }

    private static void GetComponent(string hwclass, string syntax)
    {
        var mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
        foreach (var mj in mos.Get())
        {
            Convert.ToString(mj[syntax]);
        }
    }

On  a basic console application I would just have it
Console.Writeline(Convert.ToString(mj[syntax]));

and than call for the method like this:
GetComponent("Win32_Processor", "Name");

How ever I want to bind that to my CpuLabel, how would I go ahead and do that ?

A: It is because your method doesnt have return type. Change void to type what u need to return. e.g if u want to return string try this :
 private static string GetComponent(string hwclass, string syntax)
    {
        StringBuilder sb = new StringBuilder();
        var mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + hwclass);
        foreach (var mj in mos.Get())
        {
            sb.Append(Convert.ToString(mj[syntax]));
        }

       return sb.ToString();
    }


text:
Q: how to update the xml file using xmlstarlet I am using windows version of xmlstarlet to update an xml file, via windows batch file.
xml edit --update "/xml/table/rec[@id=3]/@id" --value 10 %xmlfile%

I expected this to update the id attribute of rec node to 10. When I run this I see the updated xml as expected in the command line, but the file is never updated.
How can I do it, I want to stay away rewriting the whole file as the file could be big one.
before update:
<?xml version="1.0"?>
<xml>

    <rec id="1" />
    <rec id="2" />
    <rec id="3" />

</xml>

after update:
<?xml version="1.0"?>
<xml>

    <rec id="1" />
    <rec id="2" />
    <rec id="10" />

</xml>

A: You did not show your input document, but I assume it is the following, taken from the xmlstarlet documentation:
<xml>

    <rec id="1">
      <numField>123</numField>
      <stringField>String Value</stringField>
    </rec>
    <rec id="2">
      <numField>346</numField>
      <stringField>Text Value</stringField>
    </rec>
    <rec id="3">
      <numField>-23</numField>
      <stringField>stringValue</stringField>
    </rec>

</xml>

xmlstarlet modifies the file, but the result is sent to standard output, not saved in the original file. Use another option --inplace to modify the file in place:
$ xml ed --inplace -u "/xml/table/rec[@id='3']/@id" -v 5 rec.xml

Then:
$ cat rec.xml
<?xml version="1.0"?>
<xml>

    <rec id="1">
      <numField>123</numField>
      <stringField>String Value</stringField>
    </rec>
    <rec id="2">
      <numField>346</numField>
      <stringField>Text Value</stringField>
    </rec>
    <rec id="5">
      <numField>-23</numField>
      <stringField>stringValue</stringField>
    </rec>

</xml>

By the way, this question seems to ask something very similar to this question.

EDIT: As suggested by @npostavs, this option is listed in the edit help:
$ xml edit --help
...
-L (or --inplace)   - edit file inplace
...


text:
Q: C# While loop logic Take a look at this code below, i completely understand what this program is doing but there is one doubt regarding the output of the program on the console.
using System;
using System.IO;

class program
{
public static void Main()
{
    StreamReader myReader = new StreamReader("TextFile1.txt");
    string line = "";

    while (line != null)
    {
        line = myReader.ReadLine();
        if(line != null)
            Console.WriteLine(line);
    }

    Console.ReadLine();
}
}

and the output as follows

My question is that when i comment off the 'if' statement within the while loop, output is still exactly the same but the cursor moves an extra line down further, and i didn't understand why?

A: Because last readed line is null and when you have if you don't do Console.WriteLine and you don't have additional new line.
When you commet it out you don't check if line is not null and if it is null you print new line without any other data because line=null

A: This is effectively what you have when you comment out the if statement
while (line != null)
{
    line = myReader.ReadLine();
    Console.WriteLine(line);
}

So the extra line you are seeing is line being printed when it is in fact null.
When the if statement is included, WriteLine is not called on the final pass of the loop.

A:  if(line != null)

prints only when string is not NULL
  //if(line != null)

prints even when string is NULL (The reason why the cursor moved to an extra line down further)


text:
Q: Jquery cross fade height jump issue I am completely new to jquery and trying to solve height jump during the cross fading two div. Also facing the issue to keep remember action on refreshing the page.
This is my code I am trying to use for cross fade
$(document).ready(function(){
    $("#playlist").css("display","none");
    $("#vplaycheck").click(function(){

        if ($("#vplaycheck").is(":checked"))
        {
            $("#playlist").fadeIn("fast");
            $("#v_single").fadeOut("fast");
        }
        else
        {
            $("#playlist").fadeOut("fast");
        $("#v_single").fadeIn("fast");
        }
    });
    if ($("#vplaycheck").is(":checked"))
    {
        $("#playlist").fadeIn("fast");
        $("#v_single").fadeOut("fast");
    }
    else
    {
        $("#playlist").fadeOut("fast");
        $("#v_single").fadeIn("fast");
    }
});

    <form>
        <input type="checkbox" id="vplaycheck" />Checkbox

Single V

            Name:
            <input type="text" id="name" />

            Comment:
            <input type="textarea" id="info" />

    </form>

A: You need to make the two divs occupy the same space without influencing each other. You can acheive this by positioning them absolutely.
form{ position: relative; }
#playlist,#v_single{
   position: absolute;
   float: left;
}

A: Instead of fadeout I used only fadein and it stops jumping.


text:
Q: c++ extract member of a key of a std::multiset into a std::vector without having a getter I encountered the problem during an interview. I had to create a multimap which had as keys objects with one private member(a string, the name of the object) and mapped value ints(not relevant). There was one restriction imposed by the person leading the interview: there should be not get or set functions associated to the member string of the object. After some processing of the multimap with STL functions(like removing some elements), the following was requested: to extract the name of the key objects into a vector while removing any duplicates. I do not know how to extract the name of the key objects without having a get function(I could remove the duplicates once the extraction is performed). The person leading the interview brought into discussion functors and possibility to use a functor which could be a friend of the Object class.
Please let me know if you have any idea how this could be solved!
I provide bellow a simplified version of the code creating the multimap.
class Object
{
    std::string m_name; /* no set or get function allowed */
public:
    Object(std::string name): m_name(name) {}
    friend bool operator< (const Object& o1, const Object& o2)
    {
        return o1.m_name.compare(o2.m_name) < 0;
    }
};
void testMap()
{
    std::multimap<Object, int> m1;
    m1.insert(std::make_pair(Object("abc"), 1));
    m1.insert(std::make_pair(Object("qwerty"), 2));
    m1.insert(std::make_pair(Object("def"), 3));
    m1.insert(std::make_pair(Object("qwerty"), 4))
    /* extract Objects names in a vector while removing duplicates without adding a get m_name function */
}

Please let me know if you have any idea how this could be solved! I do not know how to access m_name which is private without a get function...

A: Not a nice solution, but using the fact that m1.begin() will always point to the alphabeticly first element we can decide if a given string would be the first in it, by inserting it to the map, and erasing it after the check. So we can start a binary-search caracter by character for the first string. Using this we can extract all keys from the map (by removing the already ones we find). I know this solution is a bit unortodox, and making a getter (or a friend function/class what is effectively a getter) is way better, but this can be done without modifying the class.
bool is_first(std::string s,std::multimap<Object,int>& m){
    auto it=m.insert(std::make_pair(Object(s), -1));
    bool res=it==m.begin();
    m.erase(it);
    return res;
}
bool eq(const Object&a,const Object& b){
    return (!(a<b)) && (!(b<a));
}
std::string get_first(std::multimap<Object,int> m){
    int len=0;
    std::string res;
    while (1){
        char mn=-128,mx=127,mid;
        res+=mn;
        while(mn+1!=mx){
            mid=(mn+(int)mx)/2;
            res[len]=mid;
            if (is_first(res,m)){
                mn=mid;
            }else{
                mx=mid;
                if (eq(m.begin()->first,Object(res)))
                    return res;
            }
        }
        res[len]=mn;
        ++len;
    }
}

void testMap()
{
    std::multimap<Object, int> m1;
    m1.insert(std::make_pair(Object("abc"), 1));
    m1.insert(std::make_pair(Object("abc"), 1));
    m1.insert(std::make_pair(Object("qwerty"), 2));
    m1.insert(std::make_pair(Object("def"), 3));
    m1.insert(std::make_pair(Object("qwerty"), 4));
    while (!m1.empty()){
        std::string s=get_first(m1);
        std::cout<<s<<" ";
        m1.erase(s);
    }
}

The motto for this solution: "If it stupid but it works, then it isn't stupid"

A: If the interviewer mentioned "to use a functor which could be a friend of the Object class," this implies that you are allowed to modify class Object by adding a friend declaration. In that case, you can simply add a friend function (I don't see why a Functor would be better) like
class Object
{
    std::string m_name; /* no set or get function allowed */
public:
    Object(std::string name): m_name(name) {}
    friend bool operator< (const Object& o1, const Object& o2)
    {
        return o1.m_name.compare(o2.m_name) < 0;
    }
    friend std::string name(const Object& o)
    {
        return o.m_name;
    }
};

I cannot be sure, though, that the interviewer had this in mind; as @NathanOliver mentioned, there is a template trick to access a private member, but I cannot imagine that someone would ask that at an interview.