text:
Q: По разному форматируется текст в заголовках DataGrid на разных вкладках TabControl в XAML Вот код TabControl:
<TabControl>
        <TabItem Header="TabItem0">
            <Grid>
                <DataGrid AutoGenerateColumns="False"
                          CanUserAddRows="False"
                          CanUserResizeColumns="False"
                          CanUserSortColumns="False"
                          EnableRowVirtualization="False"
                          HeadersVisibility="Column"
                          IsReadOnly="True"
                          ItemsSource="{Binding}"
                          SelectedIndex="{Binding}"
                          SelectionMode="Single"
                          VirtualizingPanel.IsVirtualizing="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn x:Name="ti0dgtc1"
                                            Width="*"
                                            Binding="{Binding}">
                            <DataGridTextColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti0dgtc1}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Просто такой текст в первом хедере" />
                                </Grid>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTextColumn x:Name="ti0dgtc2"
                                            Width="0.8*"
                                            Binding="{Binding}">
                            <DataGridTextColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti0dgtc2}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Просто такой текст во втором хедере" />
                                </Grid>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTextColumn x:Name="ti0dgtc3" Width="0.5*">
                            <DataGridTextColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti0dgtc3}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Здесь длинный текст в несколько строк в хедере" />
                                </Grid>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTemplateColumn x:Name="ti0dgtc5" Width="*">
                            <DataGridTemplateColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti0dgtc5}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Комментарий" />
                                </Grid>
                            </DataGridTemplateColumn.Header>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBox Text="{Binding, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" />
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </TabItem>
        <TabItem Header="TabItem1">
            <Grid>
                <DataGrid AutoGenerateColumns="False"
                          CanUserAddRows="False"
                          CanUserResizeColumns="False"
                          CanUserSortColumns="False"
                          EnableRowVirtualization="False"
                          HeadersVisibility="Column"
                          IsReadOnly="True"
                          ItemsSource="{Binding}"
                          SelectedIndex="{Binding}"
                          SelectionMode="Single"
                          VirtualizingPanel.IsVirtualizing="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn x:Name="ti1dgtc1"
                                            Width="*"
                                            Binding="{Binding}">
                            <DataGridTextColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti1dgtc1}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Просто такой текст в первом хедере" />
                                </Grid>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTextColumn x:Name="ti1dgtc2"
                                            Width="0.8*"
                                            Binding="{Binding}">
                            <DataGridTextColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti1dgtc2}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Просто такой текст во втором хедере" />
                                </Grid>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTextColumn x:Name="ti1dgtc3" Width="0.5*">
                            <DataGridTextColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti1dgtc3}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Здесь длинный текст в несколько строк в хедере" />
                                </Grid>
                            </DataGridTextColumn.Header>
                        </DataGridTextColumn>
                        <DataGridTemplateColumn x:Name="ti1dgtc5" Width="*">
                            <DataGridTemplateColumn.Header>
                                <Grid Width="{Binding Path=ActualWidth, ElementName=ti1dgtc5}" HorizontalAlignment="Center">
                                    <TextBlock Margin="5" Text="Комментарий" />
                                </Grid>
                            </DataGridTemplateColumn.Header>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBox Text="{Binding, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" />
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </TabItem>
    </TabControl>

Не пугайтесь такого большого кода. Здесь две вкладки. Во второй вкладке копия первой, только с другими именами колонок.
Для TextBlock определил стиль:
<Style TargetType="TextBlock">
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="TextAlignment" Value="Center" />
    <Setter Property="TextWrapping" Value="Wrap" />
    <Setter Property="FontWeight" Value="Bold" />
</Style>

Вот результат:

Как видно, в первой вкладке все нормально отформатировано в заголовках, а во второй нет. Вопрос: почему так и как происходит мне его отформатировать?

A: Если после запуска приложения обратить внимание на окно Events в VS, то можно увидеть сообщения об ошибках привязки:

Как видно из текста сообщения, привязка не находит элемент с заданным именем. Это может показаться странным, т. к. элемент с тамим именем, вроде, существует. Но если попробовать в окне Live Visual Tree найти его, то вы его не обнаружите. Дело в том, что TabControl использует виртуализацию и создает контент только по мере необходимости (а необходимость только одна — когда вкладка открыта).
Тут можно, конечно, попробовать как-то отловить момент переключения вкладок и создавать привязку после того как контент отобразится, но это вам скорее всего не нужно, т. к. центрирование текста заголовка столбца DataGrid можно сделать гораздо проще:
<DataGridTextColumn Width="*" Header="Просто такой текст в первом хедере">
    <DataGridTextColumn.HeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="5"/>
        </Style>
    </DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>

Ну и потом стоит вынести этот стиль в ресурсы:
<Window.Resources>
    <DataTemplate x:Key="HeaderTemplate">
        <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center"/>
    </DataTemplate>
    <Style TargetType="DataGridColumnHeader">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="5"/>
        <Setter Property="ContentTemplate" Value="{StaticResource HeaderTemplate}"/>
    </Style>
</Window.Resources>

Тогда разметка DataGrid существенно облегчится:
<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Width="10*" Header="Просто такой текст в первом хедере"/>
        <DataGridTextColumn Width="8*" Header="Просто такой текст во втором хедере"/>
        <DataGridTextColumn Width="5*" Header="Здесь длинный текст в несколько строк в хедере"/>
        <DataGridTextColumn Width="10*" Header="Комментарий"/>
    </DataGrid.Columns>
</DataGrid>


text:
Q: BindingResult object has not errors I've the following code
Object
package com.example.demo;
import javax.validation.constraints.*;

public class Customer {

    @NotEmpty(message="first name should contain a value")
    private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

Controller
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.BindingResult;
import javax.validation.Valid;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    private static int counter = 0;

    @RequestMapping("/showForm")
    public String showForm(Model model) {
        model.addAttribute("customer", new Customer());
        return "customer-form";
    }

    @RequestMapping("/processForm")
    public String processForm(@Valid @ModelAttribute("customer") Customer customer, BindingResult bindingResult) {
        return "customer-form";
    }

}

Form in a jsp file
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <html>

    <head></head>

    <body>
        <form:form method="POST" action="processForm" modelAttribute="customer">
            <form:label path="firstName">Name</form:label>
            <form:input path="firstName" />
            <form:errors path="firstName"/>
            <button type="submit">Submit</button>
        </form:form>
    </body>

    </html>

I've done some debugging and when I click the submit button the method processForm is called correctly, but the bindingResult has no errors. The firstName variable is empty. Why validation is not working?

A: Make sure that you've declared Hibernate Validator dependency in the pom.xml (if you use maven)
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>7.0.4.Final</version>
</dependency>

Validation constraints can be in your classpath from other libs, but validation processor being in dependency above

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if a list from DocumentSnaphot is empty? I have a class IsProduct where I get data from another class, Product. In my class Product I have a List of String, but in my IsProduct class I just want to get the first item of the List as a String. I can get the first item with doc['images'][0], but sometimes my List is empty and it returns an error. How can I fix this?
class IsProduct {
 IsProduct.fromDocument(DocumentSnapshot doc) {
  name = doc['name'] as String;
  //I tried this but it doesn't work
  image = doc['images'][0] == [] ? '' : doc['images'][0] as String;
  pid = doc['pid'] as String;
  description = doc['description'] as String;
  storeId = doc['storeId'] as String;
  i = doc['i'] as int;
}

String name;
String image;
String pid;
String storeId;
String description;
int i;
}

A: Try this
  image = doc['images'].isEmpty ? '' : doc['images'][0] as String;


text:
Q: Writing an R data frame to a Microsoft SQL Server I am trying to export an R data frame (funds) to a Microsoft SQL Server table (R_Predictions). The code below is creating a new table (called R_Predictions) with all of my column names displayed in the SQL Server, but the data is not transferring over in the process. Thanks in advance for any help. The R script I am using is shown below:
library(RODBC)

connection <- odbcConnect('sfRCP_RStudio', rows_at_time=1)

sqlSave(connection, funds, tablename = "R_predictions", append = FALSE)

sqlUpdate(connection, funds, tablename = "R_predictions", index = "index")

P.S. I have both sqlSave() and sqlUpdate listed as I have tried both of these options and neither has worked.
Below is the error I am receiving when I try to use the sqlUpdate function:

Error in sqlUpdate(connection, funds, tablename = "R_predictions2", index = "index") :
[RODBC] Failed exec in Update22018 0 [Microsoft][ODBC SQL Server Driver]Invalid character value for cast specification

EDIT/UPDATE: The "Invalid character value for cast specification" seemed to be an issue with exporting two "Date" data type fields I have in my data frame. I converted both of these to "character" data types and tried creating a new table (called R_predictions4) in my Microsoft SQL Server. The new error I am getting is shown below:

[RODBC] Failed exec in Update
42000 229 [Microsoft][ODBC SQL Server Driver][SQL Server]The INSERT permission was denied on the object 'R_predictions4', database 'myDB', schema 'dbo'.

It seems like I have a security issue at this point. If I update my odbcConnect() function to include the admin username and password will this work? Any other thoughts/suggestions?


text:
Q: Add ReSharper_ToggleSuspended as toolbar button I'd like to map the ReSharper_ToggleSuspended command to a button on a toolbar in VS 2012, but the command is not listed in the ReSharper category of Commands availabe in  Customize > Commands dialog.
Is there a way to do this?

A: Borrowed from the suggestion on the R# issue tracker for this issue.
In the VS Package Manager Console, you can run these commands to add the ReSharper_ToggleSuspended command to an existing toolbar named "R#".
$cmdBarName = "R#"
$cmdName = "ReSharper_ToggleSuspended"
$cmdText = "R# Active"
$toolbarType = [EnvDTE.vsCommandBarType]::vsCommandBarTypeToolbar

#----If you have a command bar you want to use---
#$cmdBar =  $dte.CommandBars.Item($cmdBarName)
# - or you can create one -
$cmdBar = $dte.Commands.AddCommandBar($cmdBarName, $toolbarType)
#------

$cmdItem = $dte.Commands.Item($cmdName).AddControl($cmdBar, 1)
$cmdItem.Caption = $cmdText

You can use any existing toolbar, or create one from scratch. I had originally added a new toolbar using the UI but updated this to include how to create one, as well as to update the Button text to use $cmdText.
Rick Strahl has a decent writeup on the command bars, if you are interested.

A: I think that the Resharper_ToggleSuspended command relates to the 'Suspend' button under Tools->Options...->Resharper->General. It seems you can't have items from the Options dialogue as commands. Possibly your only choice is to assign a keyboard shortcut to it.


text:
Q: How to get XXhr completed date in Oracle Please help me to get following output using pl sql.
date    hours   sum (has to be derived when querying out.)
1/1/2014    3   3
1/2/2014    2   5
1/3/2014    4   9
1/4/2014    5   14
1/5/2014    6   20
1/6/2014    2   22
1/7/2014    4   26
**1/8/2014  5   31**
1/9/2014    6   7  (previous day remainder 1 + 6)
1/10/2014   4   11
1/11/2014   8   19
1/12/2014   4   23
1/13/2014   5   28
**1/14/2014 8   36**
1/15/2014   3   9 (previous day remainder 6 + 3)
1/16/2014   4   13
1/17/2014   7   20
1/18/2014   3   23
1/19/2014   6   29
**1/20/2014 2   31**

Desired output is as follows.
1/8/2014
1/14/2014
1/20/2014

Looking forward your quick help.

A: Here is complete demo code for your desired output.
create  table dumt (tdate date,hours number);

insert all
into dumt values('01-jan-2014',3)
into dumt values('2/jan/2014',2)
into dumt values('3/jan/2014',4)
into dumt values('4/jan/2014',5)
into dumt values('5/jan/2014',6)
into dumt values('6/jan/2014',2)
into dumt values('7/jan/2014',4)
into dumt values('8/jan/2014',5)
into dumt values('9/jan/2014',6)
into dumt values('10/jan/2014',4)
into dumt values('11/jan/2014',8)
into dumt values('12/jan/2014',4)
into dumt values('13/jan/2014',5)
into dumt values('14/jan/2014',8)
into dumt values('15/jan/2014',3)
into dumt values('16/jan/2014',4)
into dumt values('17/jan/2014',7)
into dumt values('18/jan/2014',3)
into dumt values('19/jan/2014',6)
into dumt values('20/jan/2014',2)
select * from dual;

commit;

select tdate
from
   (
    select tDATE,
    case when lag(the_sum) over (order by the_sum)>30 then
    mod(lag(the_sum) over (order by the_sum),30)+hours
    else the_sum end as tsp
    from (
            select tDATE,HOURS,
                  (sum(HOURS) over (order by tDATE)) the_sum
            from dumt
         )
    )
    where tsp>=30;

A: select
  min(dt) keep (dense_rank last order by dt desc)
from (
       select
         dt,
         trunc(sum(hours) over (order by dt) / 30) bucket
       from
         tq84_hours
)
where bucket != 0
group by bucket;

Working example @ sqlfiddle


text:
Q: Incremental crawl - ChangedIdEnumerator not executed I have a BCS model (SharePoint 2010) that implement incremental crawl with ChangedIdEnumerator.
My model service implements three methods (ReadItem [SpecificFinder], ReadList[Finder] and ReadChangedList[ChangedIdEnumerator]).
The ReadList[Finder] is marked with the property Rootfinder, in order to the crawl use it in full indexing.
The full crawl works, but the incremental crawl, that should execute the ReadChangedList is not called, instead the the ReadList is called again and a full indexing is performed.
I haven't found a working example for this scenario.
Thanks

A: You will only be able to use the ChangedIdEnumerator and DeletedIdEnumerator with a DotNetAssembly. From personal experience (and exasperation), they do not seem to allow the SpecificFinder and StreamAccessor to be invoked with a Custom assembly.
I have implemented a couple of <IdEnumerator, ChangedIdEnumerator, DeletedIdEnumerator, SpecificFinder, StreamAccessor> assemblies and the Changed/Deleted collections do not result in calls to the SpecificFinder in Custom assemblies.
Microsoft has been mute on this point.
I do hope this helps.


text:
Q: How to lock/unlock a button based on tweeting I have a button that will be disabled until you send out a tweet that I have crafted.
Only users with twitter accounts will have access to this, and I will require users to sign-in to be able to access this button.
What kind of tools are available for me to check whether

*

*The user has actually tweeted it

*The user has not deleted the tweet afterwards

Now, there is no way to actually stop the user from deleting the tweet, but I would like to disable the button if the user has actually chosen to delete it afterwards.

A: By the fact "Only users with twitter accounts will have access to this, and I will require users to sign-in to be able to access this button" it simply means that the user ALREADY has login, before you start creating the HTML page.
Ie, before login, the user will see a form of HTML page, but after login, and at your webserver you have authenticated him via OAUTH2, then you will create the HTML specifically past-login.
That will also help to answer "the user has actually tweeted it", as you can now link the userid, with the tweet counter for specifically that user - 0 or 1.   Ie, you need will need to maintain a database at the server side of all userid who have tweeted it, and then add/remove everytime a new user added to it, or old user remove from it.   (which answer question 2)
Now, finally is the display of button:    simple, just check the database, if the userid is there, display it, otherwise don't generate the button for the HTML.
As you can see, everything is done at the server side - just like the user-dependent information for stackexchange.com as well.   If u create embedded Javascript to do the generation of HTML? well, it is not secure, and also wrong, because the user can login / delete from from two different PC/browser, and you will get inconsistencies.


text:
Q: Best way to remove all the Viewcontroller from navigation controller stack I have some view controller's within the navigation controller stack, hence I want to remove all the view controllers except for parent controller. What is the best way to remove all the view controllers in navigation controller?
Thanks.

A: Use [[self navigationController] popToRootViewControllerAnimated:YES];
It should move to the rootviewcontroller immediately.


text:
Q: UrlClassLoader to load a image resource I am creating an eclipse workspace starting by a java project (not written by me).
I am facing problems with the following method:
    public static URL getURL(String fileName) {
       URLClassLoader urlLoader = (URLClassLoader) getInstance().getClass()
            .getClassLoader();

       URL fileLocation = urlLoader.findResource(fileName);

       return fileLocation;

since the findResource doesn't find the JPG resource (filename = "icons/INIT.JPG").
Looking on urlLoader.getUrl, I noticed the class aims only to jar files. Adding the folder icon to the Project->Libraries under eclipse I managed to let findResources look into the icon folder: nevertheless, the image is not a jar file and so it isn't considered.
Honestly, I don't get the point of using this process to load an image, but I cannot change the code and I was hoping in a solution within Eclipse project setup.
Thanks in advance

A: Based on the answers to my questions in the original comment, there are some facts:

*

*You cannot change the code, and it looks like it's retrieving the AppClassLoader.

*Even if you cast it into URLClassLoader, it's still an instance of an AppClassLoader, so it will look for the contents of the classpath and all JAR/ZIP files in JAVA_HOME\lib\ext.

You said that the project is guaranteed to work without to move the file anywhere, so there's only one option: add the file that you want to retrieve with the ClassLoader to the classpath.

*

*Right click on the project, select Build Path and choose Configure Build Path.

*Click on Source > Add Folder... and add the folder where the resources that you want to take are.

PD: If you add the folder as Class Folder in the Libraries tab, the JPG image won't be recognised by the AppClassLoader.


text:
Q: Bad bibtex entries using InBook I got several of the following warning:

Warning--can't use both author and editor fields in ...

These were @InBook entries. It was possible to correct them by

*

*using @InCollection instead

*changing chapter to title

*and title to booktitle
Was this an ugly hack, or something has changed over the versions of BibTeX?
I use version 0.99d .
I copied the BibTeX entries from various sources, including the ACM Digital Library and the Springer website. Might they think something different as correct BibTeX than my implementation?
EDIT minimal working examples:
The first is foot.tex:
\documentclass[10pt,a4paper, twocolumn]{article}

\title{Paper}
\author{Gergely}

\begin{document}

\maketitle

\cite{Winskel:1995:MC:218623.218630}

\bibliographystyle{abbrv}
\bibliography{foot}

\end{document}

and foot.bib:
@inbook{Winskel:1995:MC:218623.218630,
 author = {Winskel, Glynn and Nielsen, Mogens},
 chapter  = {Models for Concurrency},
 title = {Handbook of Logic in Computer Science (Vol. 4)},
 editor = {Abramsky, S. and Gabbay, Dov M. and Maibaum, T. S. E.},
 year = {1995},
 isbn = {0-19-853780-8},
 pages = {1--148},
 numpages = {148},
 url = {http://dl.acm.org/citation.cfm?id=218623.218630},
 acmid = {218630},
 publisher = {Oxford University Press},
 address = {Oxford, UK},
}

On this, BibTeX gives the warning

Warning--can't use both author and editor fields in Winskel:1995:MC:218623.218630

I changed this as I have written above to have boot.tex:
\documentclass[10pt,a4paper, twocolumn]{article}

\title{Paper}
\author{Gergely}

\begin{document}

\maketitle

\cite{Winskel:1995:MC:218623.218630}

\bibliographystyle{abbrv}
\bibliography{boot}

\end{document}

and boot.bib:
@incollection{Winskel:1995:MC:218623.218630,
 author = {Winskel, Glynn and Nielsen, Mogens},
 title  = {Models for Concurrency},
 booktitle = {Handbook of Logic in Computer Science (Vol. 4)},
 editor = {Abramsky, S. and Gabbay, Dov M. and Maibaum, T. S. E.},
 year = {1995},
 isbn = {0-19-853780-8},
 pages = {1--148},
 numpages = {148},
 url = {http://dl.acm.org/citation.cfm?id=218623.218630},
 acmid = {218630},
 publisher = {Oxford University Press},
 address = {Oxford, UK},
}

This does not give any warning.
The calls were pdflatex foot and bibtex foot and similarly for the boot files.
What is the correct way of citing such an item?

A: The inbook entry type is designed for referring to a chapter of a book with a single author or set of authors.  This is why you receive the warning in your first example: you can't have both an author and an editor field in the inbook type since only one is assumed. In other words, each chapter of the book is by that editor or author.
If the chapters of the book have different authors then you should use the incollection entry type not the inbook type. This entry type allows for both an author and an editor, and also has separate fields for title and booktitle as you did in your second example.
Online bibtex entries are known to be very variable in their accuracy and adherence to proper bibtex requirements.


text:
Q: At what level are covariates held constant in multiple logistic regression? I'm running a multiple logistic regression with several continuous and categorical covariates. I was wondering how to interpret the results of each covariate if the others are held constant. At what level are continuous control variables held? Are they held at their mean?
I believe that for categorical control variables, the reference category is the level at which it is held. What if I want to hold it to another level, such as one coded, 1 or 2?

A: This is mostly addressed at What does "all else equal" mean in multiple regression?  Namely, that they can be held constant at any value or level of the covariates.  In some sense, it is easiest to explain them (or conceive of them) as being held at the means of the other continuous variables and the reference levels of the other categorical variables, but any value or level could be used.  Furthermore, this assumes that there are no interaction terms in the model amongst your covariates, otherwise it is not generally possible to hold all else equal (that is also explained in the linked thread).
The only added complication in a logistic regression context (or any generalized linear model in which the link is not the identity function), is that this only pertains to the linear predictor.  For example, in logistic regression, the result of $\bf X \boldsymbol{\hat\beta}$ is a set of log odds.  However, people often prefer to see $\hat p_i$, instead.  That is of course fine, but it involves a nonlinear transformation.  As a result, due to Jensen's inequality, the sigmoid curves you would get for the relationship between $X_1$ and $Y$ would differ based on whether $X_2$ is held constant at $\bar X_2$ or $\bar X_2 + s_{\bar X_2}$.  The implication of this is that there isn't really any such thing as "all else equal" in the transformed space, only in the space of the linear predictor.
If it helps to clarify these ideas, consider this simple simulation (coded in R):
set.seed(6666)                              # makes the example exactly reproducible
lo2p = function(lo){ exp(lo)/(1+exp(lo)) }  # we'll need this function

x1 = runif(500, min=0, max=10)     # generating X data
x2 = rbinom(500, size=1, prob=.5)
lo = -2.2 + 1.1*x2 + .44*x1        # the true data generating process
p  = lo2p(lo)
y  = rbinom(500, size=1, prob=p)   # generating Y data

m  = glm(y~x1+x2, family=binomial) # fitting the model & viewing the coefficients
summary(m)$coefficients
#               Estimate Std. Error   z value     Pr(>|z|)
# (Intercept) -2.0395304 0.25907518 -7.872350 3.480415e-15
# x1           0.4220811 0.04409752  9.571538 1.053267e-21
# x2           1.2582332 0.22653761  5.554191 2.789001e-08

x.seq   = seq(from=0, to=10, by=.1)  # this is a sequence of X values for the plot
x2.0.lo = predict(m, newdata=data.frame(x1=x.seq, x2=0), type="link") # predicted
x2.1.lo = predict(m, newdata=data.frame(x1=x.seq, x2=1), type="link") # log odds
x2.0.p  = lo2p(x2.0.lo)  # converted to probabilities
x2.1.p  = lo2p(x2.1.lo)

windows()
  layout(matrix(1:2, nrow=2))
  plot(x.seq,  x2.0.lo, type="l", ylim=c(-2,3.5), ylab="log odds", xlab="x1",
       cex.axis=.9, main="Linear predictor")
  lines(x.seq, x2.1.lo, col="red")
  legend("topleft", legend=c("when x2=1", "when x2=0"), lty=1, col=2:1)

  plot(x.seq,  x2.0.p, type="l", ylim=c(0,1), yaxp=c(0,1,4), cex.axis=.8, las=1,
       xlab="x1", ylab="probability", main="Transformed")
  lines(x.seq, x2.1.p, col="red")

On the scale of the linear predictor (i.e., the log odds), the slope on $X_1$ is $\approx 1.26$ whether you are holding $X_2$ at $0$ or $1$.  That's because the lines are parallel.  On the other hand, in the transformed space, the lines aren't parallel.  The rate of change in $\hat p(Y=1)$ associated with a $1$-unit change in $X_1$ differs depending on whether $X_2 = 0$ or $X_2 = 1$.  (It also differs depending on what value of $X-1$ you are starting from.)

A: Coding really doesn't matter, because when it comes down to it, regression coefficients are always based on slope, i.e., $\Delta y/\Delta x$.  Categorical factors are always broken down to either $k-1$ dummy indicators for each $k$-level factor (corner point coding, level-1's $\Delta y/\Delta x$ goes to constant term) or $k$ dummy indicator variables (sum-to-zero constraints, no constant term).
Fundamental to regression is also the concept that $x$-predictors are not random variables, hence, the levels of every $x$-variable are supposed to be experimentally controlled values, which can in reality be set by e.g. a variometer.  For example, if age is a predictor, then the model will assume that at each age $18, 19, \ldots, 85+$ you enrolled experimental subjects for which $y$ was measured.  After all, this is what is done for each level of a categorical factor.
Regarding inferential tests of hypotheses, once you have overcome coding issues, there is a series of partial $F$-tests, which can be employed to address your specific question.
There is one caveat to tell students when learning regression, for e.g. serum plasma protein expression or mineral (element) concentrations, which is that, instead of thinking about a change in $y$ for a one-unit change in $x$, or concentration, for a significant positive slope the clinical interpretation is that subjects with greater $y$-values had greater $x$-values.


text:
Q: TensorFlow : Enqueuing and dequeuing a queue from multiple threads The problem I am trying to solve is as follows :
I have a list trainimgs of filenames. I have defined a

*

*tf.RandomShuffleQueue with its capacity=len(trainimgs) and min_after_dequeue=0.

*This tf.RandomShuffleQueue is expected to be filled by trainimgs for a specified epochlimit number of times.

*A number of threads are expected to work in parallel. Each thread dequeues an element from the tf.RandomShuffleQueue and does some operations on it and enqueues it to another queue. I have got that part right.

*However once 1 epoch of trainimgs have been processed and the tf.RandomShuffleQueue is empty, provided that the current epoch e < epochlimit, the queue must again be filled up and the threads must work again.

The good news is : I have got it working in a certain case (See PS at the end !!)
The bad news is : I think that there is a better way of doing this.
The method I am using to do this now is as follows (I have simplified the functions and have removed e image processing based preprocessing and subsequent enqueuing  but the heart of the processing remains the same !!) :
with tf.Session() as sess:
    train_filename_queue = tf.RandomShuffleQueue(capacity=len(trainimgs), min_after_dequeue=0, dtypes=tf.string, seed=0)
    queue_size = train_filename_queue.size()
    trainimgtensor = tf.constant(trainimgs)
    close_queue = train_filename_queue.close()
    epoch = tf.Variable(initial_value=1, trainable=False, dtype=tf.int32)
    incrementepoch = tf.assign(epoch, epoch + 1, use_locking=True)
    supplyimages = train_filename_queue.enqueue_many(trainimgtensor)
    value = train_filename_queue.dequeue()

    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    sess.run(init_op)
    coord = tf.train.Coordinator()
    tf.train.start_queue_runners(sess, coord)
    sess.run(supplyimages)
    lock = threading.Lock()
    threads = [threading.Thread(target=work, args=(coord, value, sess, epoch, incrementepoch, supplyimages, queue_size, lock, close_queue)) for  i in range(200)]
    for t in threads:
        t.start()
    coord.join(threads)

The work function is as follows :
def work(coord, val, sess, epoch, incrementepoch, supplyimg, q, lock,\
         close_op):
while not coord.should_stop():
    if sess.run(q) > 0:
        filename, currepoch = sess.run([val, epoch])
        filename = filename.decode(encoding='UTF-8')
        print(filename + ' ' + str(currepoch))
    elif sess.run(epoch) < 2:
        lock.acquire()
        try:
            if sess.run(q) == 0:
                print("The previous epoch = %d"%(sess.run(epoch)))
                sess.run([incrementepoch, supplyimg])
                sz = sess.run(q)
                print("The new epoch = %d"%(sess.run(epoch)))
                print("The new queue size = %d"%(sz))
        finally:
            lock.release()
    else:
        try:
            sess.run(close_op)
        except tf.errors.CancelledError:
            print('Queue already closed.')
        coord.request_stop()
return None

So, although this works, I have a feeling that there is a better and cleaner way to achieve this. So, in a nutshell my questions are :

*

*Is there a simpler and cleaner way of achieving this task in TensorFlow ?

*Is there any problem with this code's logic ? I am not very experienced with multithreading scenarios, so any obvious faults which have skipped my attention would be very helpful to me.

P.S : It seems that this code is not Perfect after all. When I ran with 1.2 million images and 200 threads, it ran. However when I run it for 10 images and 20 threads, it gives the following error :
CancelledError (see above for traceback): RandomShuffleQueue '_0_random_shuffle_queue' is closed.
     [[Node: random_shuffle_queue_EnqueueMany = QueueEnqueueManyV2[Tcomponents=[DT_STRING], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](random_shuffle_queue, Const)]]

I thought I got that covered by except tf.errors.CancelledError. What the hell is going on here ?

A: I finally found out the answer. The problem was that multiple threads were clashing together on various points in the work() function.
The following work() function works perfectly.
def work(coord, val, sess, epoch, maxepochs, incrementepoch, supplyimg, q, lock, close_op):
    print('I am thread number %s'%(threading.current_thread().name))
    print('I can see a queue with size %d'%(sess.run(q)))
    while not coord.should_stop():
        lock.acquire()
        if sess.run(q) > 0:
            filename, currepoch = sess.run([val, epoch])
            filename = filename.decode(encoding='UTF-8')
            tid = threading.current_thread().name
            print(filename + ' ' + str(currepoch) + ' thread ' + str(tid))
        elif sess.run(epoch) < maxepochs:
            print('Thread %s has acquired the lock'%(threading.current_thread().name))
            print("The previous epoch = %d"%(sess.run(epoch)))
            sess.run([incrementepoch, supplyimg])
            sz = sess.run(q)
            print("The new epoch = %d"%(sess.run(epoch)))
            print("The new queue size = %d"%(sz))
    else:
            coord.request_stop()
        lock.release()

    return None

A: I recommend having a single thread calling enqueue_many epochs times enqueue the correct number of images. It can then close the queue. This would let you simplify your work function and other threads.

A: I think the GIL will prevent any actual parallelism from being done in those threads.
To get performance with tensorflow you need to keep your data in tensorflow.
Tensor Flow's reading data guide explains how to address a very similar sort of problem.
More specifically, you seem to have rewritten a significant chunk of string_input_producer.


text:
Q: Ultrasonic Sensor HC-SR04 + Arduino Calculation? I'm using this code :
int trigPin = 7;
int echoPin = 8;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
}

void loop() {
  int duration;
  int distance;
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin,LOW);
  duration = pulseIn (echoPin,HIGH);
  distance = (duration/2)/29.1;
  Serial.print("distance = ");
  Serial.println (distance);
  delay(500);
}

I understand the concept that we send a pulse of 1000 µsec in this case and we wait for the reflected signal. But I don't understand how in this code, only the pulse width of the reflected signal is being used for the calculation.
I searched around and they say the reflected pulse width is proportional to the distance traveled. Can someone please explain how this happens (the physics behind it) and also where does the 29.1 comes from?
I read this documentation but I still don't understand the pulse width concept.
Many thanks in advance!

A: Like Chris touched on in the comments, the input pin goes HIGH for the time between it being send and received. I'm not exactly sure if it goes HIGH for a certain amount of time after or during the transmission, but you might be able to find that on a datasheet.

where does the 29.1 come from?

That's the speed of sound through air... you can use that to convert the time to centimeters. You'll have to divide it by two because it goes two ways.
Recap:

*

*Arduino sends pulse to SR04 (1000 microseconds):
 digitalWrite(trigPin,HIGH);, delayMicroseconds(1000);, &digitalWrite(trigPin,LOW);.

*SR04 emits a ping and changes the signal pin to HIGH

*The ping hits an object, bounces back, and goes back to the SR04

*The SR04 sets the pin back to LOW

The Arduino measures the length the signal pin is HIGH with this:
duration = pulseIn (echoPin,HIGH);


text:
Q: Docker-composer ERROR: Cannot start service db: OCI runtime create failed: container with id exists The first time I run docker-compose up, docker creates the components, yet, after rebooting when I just want to start the container and I run docker-compose start I get the following error:
ERROR: for mysqldb  Cannot start service db: OCI runtime create failed: container with id exists: xxxxxxx

If I delete the container and I run docker-compose up again it works, but every time I restart the computer I have to re-create the container, why is that? In the past I was able to mount the containers by running docker-compose start, whereas now it seems I have to recreate them every time.
I created the following docker-composer.yml:
version: '3.3'

services:
  # Database
  db:
    image: mysql:5.7
    container_name: mysqldb
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      DB_HOST: localhost
      MYSQL_ROOT_PASSWORD: testing
      MYSQL_DATABASE: testing
      MYSQL_USER: root
      MYSQL_PASSWORD: testing
    networks:
      - testingnetwork
    ports:
      - "3307:3306"
  # phpmyadmin
  phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin
    restart: always
    ports:
      - '8181:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: testing
    networks:
      - testingnetwork
  # Wordpress
  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - '8080:80'
    restart: always
    container_name: testing_wordpress
    volumes:
      - ./public/:/var/www/html
    environment:
      WORDPRESS_DB_NAME: testing
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: testing
      WORDPRESS_CONFIG_EXTRA: define('WP_ALLOW_MULTISITE', true );
    hostname: testing.org.local
    labels:
       com.theimpossiblecode.expose.domain: "testing.org.local"
       com.theimpossiblecode.expose.domainIsHost: "true"
    networks:
      testingnetwork:
          aliases:
            - testing.org.local
networks:
  testingnetwork:
volumes:
  db_data:

A: I got an error if I set "root" for MYSQL_USER in environment.
Then I changed MYSQL_USER: testing, it worked well.


text:
Q: AngularJS: How do I hide clicked element in angular? I'm totally new to angular and I'm finding that doing simple things aren't as obvious to me? I have a list of items that I display using ng-repeat. I simply want to hide the element once I click on an element within that scope. I'd like to do it the "angular" way with good practices.. just not sure what that is.
This is html

{{fruit.name}}

                <button ng-click="hideMe()">hide li</button>

This is my js
var myApp = angular.module('myApp', []);

myApp.factory('Fruits', function () {
    var Fruits = [{
        name: "banana"
    }, {
        name: "watermelon"
    }, {
        name: "strawberry"
    }];

    return Fruits;
});

function FruitsCtrl($scope, Fruits) {
    $scope.fruits = Fruits;

    $scope.hideMe = function () {
        alert('hide this li');
    };
}

I have this on jsfiddle: http://jsfiddle.net/hS5q8/2/
Help or direction would be great! Thanks!!

A: You can use ngHide directive. In Example added a property hide, ngHide will hide li if this property is true.
HTML

{{fruit.name}}

    <button ng-click="hideMe(fruit)">hide li</button>

Angularjs Method
$scope.hideMe = function (fruit) {
    fruit.hide=true;
    alert('hide this li');
};

DEMO


text:
Q: Looking at evaluating polynomials at a point via schemes Let $R$ be some commutative ring with identity and fix some $a \in R$. Then, consider the evaluation map:
$$\epsilon_a: R[x] \to R: f(x) \mapsto f(a)$$
We know that this is a surjective homomorphism (in fact, it gives the isomorphism $R[x]/(x-a) \cong R$), so it gives us a closed subscheme $\text{Spec} R \to \mathbb{A}^1_R$. My question is then: is there a geometric way to imagine this closed embedding of scheme, particularly in regards to the process of evaluating of polynomial $f(x)$ at $a$ ?

A: Let $S:=\operatorname {Spec}R$ and let $\pi:\mathbb A^1_R\to S$ be the canonical projection, dual to the embedding of rings $R\to R[x]$.
The fiber of  $\mathfrak p\in S$ under $\pi$ is the affine line $\pi^{-1}(\mathfrak p)=\mathbb A^1_{\kappa (\mathfrak p)}$ over the residue field $\kappa (\mathfrak p)=\operatorname {Frac}(R/\mathfrak p)$.
So the geometric picture is clear: the scheme  $\mathbb A^1_R$ is obtained by gluing together the affine lines over $\kappa (\mathfrak p)$ where $\mathfrak p$ runs through $S$.
And what is the morphism $j_a:S\to \mathbb A^1_R$ dual to your evaluation $\epsilon_a:R[x]\to R$ ?
It is the map $j_a:S\to \mathbb A^1_R$ associating to the prime ideal $\mathfrak p\in S$ the prime ideal $j_a(\mathfrak p) \subset R[x]$ consisting of the set of polynomials  $f\in R[x]$ such that $f(a)\in \frak p$.
The point $j_a(\mathfrak p)$ can also be seen as the rational point $\langle x-\bar a\rangle \in \mathbb A^1_{\kappa (\mathfrak p)}=\pi^{-1}(\mathfrak p)$,where $\bar a \in \kappa (\mathfrak p)$ is the image of $a$ under the natural map $R\to \kappa (\mathfrak p)=\operatorname {Frac}(R/\mathfrak p)$.


text:
Q: Setting BIOS/UEFI Administrator Password from Linux CLI is there a way to set the BIOS/UEFI Administrator password from a Linux CLI for a BIOS/UEFI that doesn't has any password set?
I'm trying to automate the process of provisioning some servers and wanted to avoid having to go to the BIOS/UEFI manually to set the admin password.
Thanks in advance!

A: No, because Linux can't access BIOS, because BIOS is a separate chip.


text:
Q: C Pipe between a parent and 2 children I can not figure out why only 1 child sends data to parent (only the 1st child)..
When I do sleep(5) after the child1 sends data through pipe to parent then the 2nd child sends the same prime number to the parent.
Can someone help me?

//--------------------------Consts---------------------------------
#define NUM_OF_CHILDS 2
#define N 20
#define WIN 5

struct msg{
 pid_t _pid;
 int _prime;
};

//--------------------------Prototypes-----------------------------
bool is_prime(int num);
void terminate(pid_t child_pid[],int fd[2]);
void do_child(int fd[2]);
void print_pair(const int f_arr[],const int s_arr[]);

//--------------------------Main-------------------------------------
int main()
{
 int f_arr[N] = {0},
  s_arr[N] = {0},
  ind, //running on children fork
  count1 = 0,
  count2 = 0,
  victory1 = 0,
  victory2 = 0,
  min = 0;

 int fd[2];

 bool read1 = false,
  read2 = false;

 srand((unsigned)time(NULL));
 pid_t child_pid [NUM_OF_CHILDS];//children pid status array

 struct msg msg1;

 if (pipe(fd) == -1)//pipe fd
 {
  perror("cannot open pipe");
  exit(EXIT_FAILURE);
 }

 for(ind = 0; ind < NUM_OF_CHILDS; ind++)
 {
  child_pid[ind] = fork();// duplicate the current process

  if (child_pid[ind] < 0)//fork failed
  {
   perror("Cannot fork()");
   exit(EXIT_FAILURE);
  }

  if(child_pid[ind] == 0)/* child : sends message to parent*/
   do_child(fd);
 }

 /* parent : receives message from child */
 close(fd[1]); // close the write-end of the pipe

 //read data from pipe
 while(read(fd[0],&msg1,sizeof(struct msg)) > 0)
 {
  if(child_pid[0] == msg1._pid)
  {
   f_arr[count1++] = msg1._prime;
   read1 = true;
  }

  else
  {
   s_arr[count2++] = msg1._prime;
   read2 = true;
  }

  if(read1 && read2)
  {
   if(f_arr[min] > s_arr[min])
    victory1++;
   else if(f_arr[min] < s_arr[min])
    victory2++;

   read1 = false;
   read2 = false;
   min++;
  }

  if(victory1 == WIN || victory2 == WIN)
   terminate(child_pid,fd);
 }

 close(fd[0]);// close the read-end of the pipe
 print_pair(f_arr,s_arr);

 return EXIT_SUCCESS ;
}
//---------------------------------------------------------------------
//checking if number is a prime number or not
//and return true or false
bool is_prime(int num)
{
 int i;
 if(num==0 || num==1 || num==2)
  return false;
 for(i=2;i<=num/2;i++)
 {
  //the number is not prime
  if(num%i == 0)
   return false;
 }
 //the number is prime
 return true;
}
//----------------------------------------------------------------
void do_child(int fd[2])
{
 struct msg message;
 int num;

 close(fd[0]);

 while (1)
 {
  num = rand() % 1000;
  if(is_prime(num))
  {
   message._prime = num;
   message._pid = getpid();
   write(fd[1], &message, sizeof(struct msg));
  }
 }
}
//----------------------------------------------------------------
void terminate(pid_t child_pid[],int fd[2])
{
 int ind,
 loop;

 for(ind = 0; ind < NUM_OF_CHILDS; ind++)
 {
  close(fd[1]);
  //first to give the process an opportunity to die gratefully before
  //using SIGKILL
  kill(child_pid[ind], SIGTERM);
  bool died = false;
  //It will give the process 5 seconds to die gracefully
  for (loop = 0; loop < 5 && !died; ++loop)
  {
   int pid;
   //the time the child process takes to close down gracefully.
   sleep(1);
   //to get the return status of that process and prevent zombie processes.
   if (waitpid(child_pid[ind], &pid, WNOHANG) == child_pid[ind])
    died = true;
  }
  //if SIGTERM did not killed the child do SIGKILL
  if (!died)
  {
   int pid;
   kill(child_pid[ind], SIGKILL);
   waitpid(child_pid[ind], &pid, 0);// harvest the zombie
  }

 }
}
//------------------------------------------------------------------
void print_pair(const int f_arr[],const int s_arr[])
{
 int ind;
 for(ind = 0; ind < N; ind++)
 {
  if(f_arr[ind] == 0 && s_arr[ind] == 0)
   break;
  printf("(%d,%d)\n",f_arr[ind],s_arr[ind]);
 }
}

A: First, the two child processes are generating the same pseudorandom sequence because they're starting with the same seed. To have any chance of different numbers, you need to seed them after the fork, and probably use something that changes more than once per second (the chance of the two of them having different values of time() is very small even if you moved the srand(time(NULL)) after the fork).
Second, you are receiving all the numbers from the first process because it has a head start. There's plenty of time to write to the pipe while the second process is being created. The parent doesn't start reading until after both children are created, so the first child fills the pipe buffer and then blocks. Pipe buffers are at least a few kilobytes.
Even when I slowed down the child process by making it print the numbers to stderr, the first one still generated hundreds of numbers before the second one got going.
So what happens in your main loop when there are hundreds of messages arriving from child 1 and none from child 2? Your f_arr array overflows because it only has room for 20. After that, anything can happen.
The simplest way to prevent that would be to check whether count1 == N before attempting to store a number into f_arr[count1++], and if so, just continue; to the next message. You should do the same for messages from the second child, even though it's not likely to happen.
This way you'll be accepting at most N messages from each child, and ignoring the rest. You'll need to add another end condition to the main loop: if both children have sent N messages, you need to stop.
Another way to go would be to use a separate pipe for each child and alternate reading from both pipes to keep them synchronized, but I have a feeling you were deliberately avoiding that.


text:
Q: Interfaces and async practices I have an interface
public interface IUserFactory
{
       User GetUser(string id);
       void DeleteUser(string id);
}

Current class which implements uses functions which are synchronous.
I am now going to have an implementation which uses HttpClient, whose calls are async.
What I'm doing now is to have the new UserFactoryWeb class implement two sets of functions:
Task<User> GetUserAsync(string id)
Task DeleteUserAsync(string id)

and
User GetUser(string id)
void DeleteUser(string id)

the interface methods. In the interface methods I use the trick:
var t = Task.Run(async code...)
t.Wait();

in order to prevent deadlocks.
Are there other options?
Also, how can you support async calls in interfaces? It seems crazy that async isnt part of an interface signature.

A: Let's rationalise why interfaces don't need the async keyword

*

*A Method returning a Task / ValueTask does not need to be an Async Method (a method with the async keyword).

*An Async Method is basically compiler plumbing to help with

*

*The return Task / ValueTask (when not void),

*Placing exceptions on a returned Task / ValueTask (when not void)

*Allowing the use of the await keyword

*An Async Method runs synchronously until it hits the first await expression, at which point the method is suspended until the awaited task is complete.

*An Async Method does not need an await, in which case it's just compiler plumbing for the return value and exception when not void (see point 1.1 and 1.2 respectively)

*You can use await on anything the supports the INotifyCompletion and the return type exposes 3 members

*

*IsCompleted

*OnCompleted

*GetResult

*Task and ValueTask can be awaited regardless of whether they were returned by an Async Method (see point 5)

*Interfaces are just contracts between the implementer and the caller and give no indication of how the contract is implemented, they just contain definitions for a group of related functionalities

*The definition of such members need no guaranteed on whether the method has been plumbed up with an async keyword (or whatever funky things you do in that method) just that that it returns a Task / ValueTask
In short the async keyword is an implementation detail, the contract is just a definition, the definition doesn't care what you do in your method. However, if you do, or you would like your callers to know this, you document well.
To prove this, the async keyword has no actual bearing on the compilation of a method signature or how the callee invokes it. Let's look at the compiled code here. You will notice the method actually loses the async keyword and just returns a task. However, the compiler does to a lot of other plumbing to implement the language feature.
A method such as
public static async Task Test1()

Is actually compiled to
[AsyncStateMachine(typeof(<Test1>d__0))]
public static Task Test1()

Additional Resources

*

*async (C# Reference)

*await operator (C# reference)

*Asynchronous programming with async and await

*Interfaces (C# Programming Guide)

*Stephen Toub - await anything;

A: You can wrap your return type to Task like:
public interface IUserFactory
{
       Task<User> GetUser(string id);
       Task DeleteUser(string id);
}

A: Adding async to a method signature does not change the contract of a method at all. There is no async equivalent in IL at all. The implementation of the async language feature is entirely in the C# compiler.
This is fairly simple to demonstrate with a simple example and an IL de-compiler.
public class C {
    public async Task Example1(Task t) => await t;
    public Task Example2(Task t) => t;
}

// snip
public Task Example1(Task t)
// snip
public Task Example2(Task t)
// snip


text:
Q: Git: Remove directory from branch without affecting other branch I would like to:

*

*Checkout a new branch B2

*Delete directories

*Switch back to master and see the directories I deleted.

Instead, what I'm experiencing is that the directories I delete with B2 checked out are also appear removed when I checkout master.
git checkout master
ls
. .. dir1/ dir2/
git checkout -b B2
rm -rf dir2/
ls
. .. dir1/
git checkout master
ls
. .. dir1/

What am I missing?

A: In the branch you want the directories deleted in, you need to add and commit those changes before moving back to master.


text:
Q: Swift: Why the non-static methods can't call static variables and constant (static let) without dynamicType? It has destroyed my view about static variables and constant after using swift.
Why swift doesn't allow us to call static variables and constant in other methods?
for example:
class Aa {
    static let name = "Aario"
    func echo() {
        print(name)      // Error!
    }
}

Mr. ogres told me to use dynamicType .
class Aa {
    static var name = "Aario"
    func echo() {
        print(self.dynamicType.name)
    }
}

let a = Aa()
a.dynamicType.name = "Aario Ai"
a.echo()                         // it works!!!

It works! So why should I use dynamicType to call static variables?
Finally, the answer is:
class Aa {
    static var name = "Static Variable"
    var name = "Member Variable"
    func echo() {
        print(self.dynamicType.name)    // Static Variable
        print(Aa.name)                  // Static Variable
        print(name)                     // Member Variable
    }
}

let a = Aa()
a.dynamicType.name = "Aario Ai"
Aa.name = "Static: Aario"
a.name = "Member: Aario"
a.echo()                         // it works!!!

It's really different with other languages.

A: Static variables have to be addressed with their type, even when you're writing code within this type. See The Swift Programming Language (Swift 2.2) - Properties (in "Querying and Setting Type Properties"):

Type properties are queried and set with dot syntax, just like instance properties. However, type properties are queried and set on the type, not on an instance of that type.

In your code, simply write  Aa.name instead of name and you'll be fine.


text:
Q: VSS Unexpected error querying for the IVssWriterCallback—Access Denied I'm having trouble with VSS based backups of my Exchange server. I'm getting the following error on the start of the backup:
Volume Shadow Copy Service error: Unexpected error querying for the IVssWriterCallback interface.  hr = 0x80070005, Access is denied.
. This is often caused by incorrect security settings in either the writer or requestor process.

Operation:
   Gathering Writer Data

Context:
   Writer Class Id: {e8132975-6f93-4464-a53e-1050253ae220}
   Writer Name: System Writer
   Writer Instance ID: {6524807c-855e-4b4f-9295-dab2ac1e1948}

The service performing the backup is running as Local System, so I don't understand why it wouldn't have access. I've checked group policy and DCOM; there's no antivirus on the system and the firewall is disabled.
Edit:
The backup software is CloudBerry Enterprise Backup. I believe it uses the built-in Exchange Information Store writer, as I didn't see anything that looked like a third party writer when I ran vssadmin list writers. It's quite possible that I could have missed it, however.


text:
Q: Update last element in .SD group based on other elements I have a dataset dt in data.table format that looks like
  type id val

1 m     1   5
2 m     1   3
3 m     1  NA
3 e     2   7
4 e     3   7
5 m     4   4
6 m     4   2
7 m     4  NA

I want to replace val of the last entry (in my example NA) of each group by id of type m with the sum of val of the other entries of the group. I.e., I want to end up with a dataset like this:
  type id val

1 m     1   5
2 m     1   3
3 m     1   8
3 e     2   7
4 e     3   7
5 m     4   4
6 m     4   2
7 m     4   6

Currently, I am trying to wrap my head around data.table functions, particularly .SD and want to solve the issue with these tools.
So far, I have figured out that dt[type=="m",.SD[.N],.SDcols="val",by=id] gives me access to the relevant elements and dt[type=="m", lapply(.SD[1:.N-1]),.SDcols="val",by=id] provides me with the correct sum. However, I can't bring the two together.
Any help is appreciated.

A: We can use na.aggregate
library(zoo)
library(data.table)
setDT(dt)[type == 'm', val := na.aggregate(val,  FUN = sum), id]
dt
#   type id val
#1:    m  1   5
#2:    m  1   3
#3:    m  1   8
#4:    e  2   7
#5:    e  3   7
#6:    m  4   4
#7:    m  4   2
#8:    m  4   6

A: We can use replace :
library(data.table)

dt[type == "m", val := replace(val, .N, sum(val, na.rm = TRUE)), id]
dt

#   type id val
#1:    m  1   5
#2:    m  1   3
#3:    m  1   8
#4:    e  2   7
#5:    e  3   7
#6:    m  4   4
#7:    m  4   2
#8:    m  4   6

A: Another option:
library(data.table)

setDT(dt)[type == 'm', val := c(val[-.N], sum(val, na.rm = TRUE)), by = id]

Output:
   type id val
1:    m  1   5
2:    m  1   3
3:    m  1   8
4:    e  2   7
5:    e  3   7
6:    m  4   4
7:    m  4   2
8:    m  4   6


text:
Q: localtime() returning ambigious I wrote the below code and tested it out on different platforms. I got different results on HP-UX IA64,as compared to other platforms.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    time_t t;
    struct tm *gmt, *lat, ldummy;

    tzset();

    printf("Local timezone: TZ=%s\n\n", getenv("TZ"));

    t = 1394881705;

    lat = localtime(&t);
    printf("Local time is : %s", asctime(lat));

    gmt = gmtime(&t);
    printf("GMT is        : %s", asctime(gmt));

    return 0;
}

OUTPUT:-
Linux
$ ./a.out
Local timezone: TZ=CET

Local time is : Sat Mar 15 12:08:25 2014
GMT is        : Sat Mar 15 11:08:25 2014

SunOs
$ ./a.out
Local timezone: TZ=CET

Local time is : Sat Mar 15 12:08:25 2014
GMT is        : Sat Mar 15 11:08:25 2014

AIX
$ ./a.out
Local timezone: TZ=CET

Local time is : Sat Mar 15 12:08:25 2014
GMT is        : Sat Mar 15 11:08:25 2014

(This is where the problem is)
HP-UX IA64
$ ./a.out
Local timezone: TZ=CET

Local time is : Sat Mar 15 11:08:25 2014
GMT is        : Sat Mar 15 11:08:25 2014

I am trying to understand why the output is differing in case of HP-UZ IA64(Version is 11.31). I could not find any relevant documentation for this eccentric behaviour. Would someone help me with understanding this?

A: On HP-UX ia64, when I provide set timezone as, TZ=CET, it simply considers it as being the same as UTC. As per HP-UX documentation at link emphasis mine,
"TZ can be set using the format:
[:]STDoffset[DST[offset][,rule]]"
The offset here is mandatory and represents "the value that must be added to local time to arrive at Coordinated Universal Time (UTC)."
So, without offset, HP-UX considers the STD the same as UTC.


text:
Q: Alias "Post Link" in data.stackexchange.com generate invalid links for "Meta sites" of pt.stackoverflow and es.stackoverflow I create a query using [Post Link] and [Comment Link] and I noticed that the generated links are inverted for some sites, for example:
This https://data.stackexchange.com/ptme/query/775699/bug-in-links (query to pt.stackoverflow meta) generate links like this:
https://meta.pt.stackoverflow.com/q/1

But the correct one is:
https://pt.meta.stackoverflow.com/q/1

Ths https://data.stackexchange.com/esme/query/775699/bug-in-links (query to es.stackoverflow meta) generate links like this:
https://meta.es.stackoverflow.com/q/146

But the correct one is:
https://es.meta.stackoverflow.com/q/146

others like Web Apps Meta and Game Dev Meta and Russian Stack Overflow are generating correctly:

*

*https://data.stackexchange.com/meta.webapps/query/775699/bug-in-links

*https://data.stackexchange.com/meta.gamedev/query/775699/bug-in-links

*https://data.stackexchange.com/meta.russian/query/775699/bug-in-links
including the bug that occurred in Arqade Meta (mentioned in Per-site metas are not linked properly from the Data Explorer) has already been fixed, then it is a problem that only occurs in some cases, test arqade meta:

*

*https://data.stackexchange.com/meta.gaming/query/775699/bug-in-links

A: This has been fixed. I went through and updated the sites that had URLs from before the meta. move.
The generated post links should now work for all sites.


text:
Q: Quarkus Resteasy JSON-B deserialize lists into HashMap instead of List I'm trying to use Quarkus with Kotlin to create an API but I'm facing a problem related to the way that json-b is deserializing my json into my request classes.
Instead of deserialize into a List of MyRequestValue I'm getting a HashMap.
Not sure why json'b is able to deserialize objects properly but not be able to do the same with list of objects
Request Classes
data class MyRequest @JsonbCreator constructor(
    @JsonbProperty("name") val name: String,
    @JsonbProperty("values") val values: List<MyRequestValue>
)

data class MyRequestValue @JsonbCreator constructor(
    @JsonbProperty("id") val id: Int,
    @JsonbProperty("value") val value: String
)

Request Json
{
  "name": "Request",
  "values": [
    {
      "id": 1,
      "value": "value1"
    }
  ]
}

pom.xml
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy</artifactId>
    </dependency>
    <dependency>
      <groupId>io.quarkus</groupId>
      <artifactId>quarkus-resteasy-jsonb</artifactId>
    </dependency>

Instead of convert the json request into my data class objects, I'm getting MyRequest object with a hashmap as values instead of getting MyRequest object with a List.
Actual toString result:
MyRequest(name=Request, values=[{id=1, value=value1}])
Expected toString Result:
MyRequest(name=Request, values=[MyRequestValue(id=1, name=value1)])


text:
Q: Calling multiple XML files In my application(iPad application) I have 5 folders and inside of each folder i have one XML file. My question is, How can I call all .xml files, in my appDelegate
I have file1.xml, file2.xml, file3.xml, file4.xml,file5.xml (it's a requirement)
for call or adding Path for file1 xml I have this code:
NSString *xml = [[NSBundle mainBundle] pathForResource:@"file1" ofType:@"xml"];
NSData *Data = [NSData dataWithContentsOfFile:xml];
NSXMLParser *Parser = [[NSXMLParser alloc] initWithData:Data];
file1 *parser = [[file1 alloc] initXMLParser];

but how can I have all 5 in my appDelegate class?
and do I need to create specific parser class for each or since all information and tags are the same I just need to add all in my appDelegate
EDIT:
I have to call them from their folder I cann"t change the structure for example
Folder1/file1.xml
Folder2/file2.xml
Folder3/file3.xml and so on

A: Yes, you need to instantiate an NSXMLParser object for each XML file you're parsing. The simple way to load the XML files is as kimsnarf says: use a for loop and load them in order. If they're in the bundle (which they appear to be), I'd stick them in a specific path under "Resources," like "Resources/SpecialXMLJunk" and just load them by iterating over the results of something like URLsForResourcesWithExtension:subdirectory: (used to get the XML files out of "Resources/SpecialXMLJunk"). So, pseudocode-ish, probably something like this:
NSArray *xmlResourceURLs = [mainBundle
                            URLsForResourcesWithExtension: @"xml"
                            subdirectory: xmlResourcesPath];
foreach (NSURL *xmlURL in xmlResourceURLs)
    [self loadJunkXMLAtURL: xmlURL];

A: Create a for-loop and load/parse the files one by one. You should store the parsed data somewhere anyway (in a cache or database) so you don't need to hold on to the files and parsers after parsing. Retrieve data from the cache/database instead.


text:
Q: How to calculate CPU load using linux top command I am running top -b -n2 -d 1 | grep Cpu in a loop and notice it returns two entries in each iteration...
1) For each loop there are two lines of results...should I be using the first or second line...what is the difference between the two?
2) To calculate the CPU utilization do I add %us, %sy, %ni, %hi and %si?
Cpu(s):  1.6%us,  1.7%sy,  0.0%ni, 96.6%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%st
Cpu(s):  8.7%us,  9.4%sy,  0.0%ni, 81.9%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

Cpu(s):  1.6%us,  1.7%sy,  0.0%ni, 96.6%id,  0.0%wa,  0.0%hi,  0.1%si,  0.0%st
Cpu(s):  9.7%us,  8.9%sy,  0.0%ni, 81.5%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st

A: I needed the 2nd entry...
command = "top -bn 2 -d 0.01 | grep '^Cpu' | tail -n 1 | gawk '{print $2+$4+$6}'"

The 1st iteration of top -b returns the percentages since boot,
We need at least two iterations (-n 2) to get the current percentage.
To speed things up, you can set the delay between iterations to 0.01.
top splits CPU usage between user, system processes and nice processes, we want the sum of the three.
Finally, you grep the line containing the CPU percentages and then use gawk to sum user, system and nice processes:

top -bn 2 -d 0.01 | grep '^Cpu' | tail -n 1 | gawk '{print $2+$4+$6}'
        -----  ------   -----------    ---------   ----------------------
        |      |           |             |             |------> add the values
        |      |           |             |--> keep only the 2nd iteration
        |      |           |----------------> keep only the CPU use lines
        |      |----------------------------> set the delay between runs
        |-----------------------------------> run twice in batch mode


text:
Q: Email Validation function doesn't work | VB.net Protected Sub btn_Submit_Click(sender As Object, e As EventArgs) Handles btn_Submit.Click
    Dim _lblresponse As Label = Nothing
    _lblresponse = New Label

    Dim MyEmail As String = txb_Email.Text
    If EmailCheck(MyEmail) = True Then
        Dim _lblresponse_Valid As Label = Nothing
        _lblresponse = New Label
    Else
        Dim _lblresponse_Invalid As Label = Nothing
        _lblresponse = New Label
        _lblresponse.Text = "This is not a Valid Email"
        Me.plh_Response_Invalid.Controls.Add(_lblresponse)
    End If

    _lblresponse.Text = "*Your Request Has Been Sent"
    Me.plh_Response.Controls.Add(_lblresponse)

Function EmailCheck(ByVal emailAddress As String) As Boolean

    Dim pattern As String = "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
    Dim emailAddressMatch As Match = Regex.Match(emailAddress, pattern)

    If emailAddressMatch.Success Then
        Return True
    Else
        Return False
    End If

End Function

The function says the email format is false but when the submit button is pressed. It will send the email as valid even though it is not. What have I done wrong?

A: try this. No need to use emailAddressMatch
If Regex.IsMatch(emailAddress, pattern) then
  return true
Else
  return false
End If

Instead of
Dim emailAddressMatch As Match = Regex.Match(emailAddress, pattern)


text:
Q: Eliminating blob inside another blob I'm currently working on a program for character recognition using C# and AForge.NET and now I'm struggling with the processing of blobs.
This is how I created the blobs:
BlobCounter bcb = new BlobCounter();
            bcb.FilterBlobs = true;
            bcb.MinHeight = 30;
            bcb.MinWidth = 5;
            bcb.ObjectsOrder = ObjectsOrder.XY;
            bcb.ProcessImage(image);

I also marked them with rectangles:
Rectangle[] rects;
rects = bcb.GetObjectsRectangles();
Pen pen = new Pen(Color.Red, 1);
Graphics g = Graphics.FromImage(image);

foreach (Rectangle rect in rects)
{
     g.DrawRectangle(pen, rect);
}

After execution my reference image looks like this:

BlobImage
As you can see, almost all characters are recognized. Unfortunately, some character include blobs inside a blob, e.g. "g", "o" or "d".
I would like to eliminate the blobs which are inside another blob.
I tried to adjust the drawing of the rectangles to achieve my objective:
foreach (Rectangle rect in rects)
{

    for (int i = 0; i < (rects.Length - 1); i++)
    {
         if (rects[i].Contains(rects[i + 1]))
             rects[i] = Rectangle.Union(rects[i], rects[i + 1]);

    }
    g.DrawRectangle(pen, rect);
}

...but it wasn't successful at all.
Maybe some of you can help me?

A: you can try to detect rectangles within rectangles by check their corner indices,
I have one MATLAB code for this which i have written for similar kind of problem:
Here is snippet of the code is:
function varargout = isBoxMerg(ReferenceBox,TestBox,isNewBox)
X = ReferenceBox; Y = TestBox;
X1 = X(1);Y1 = X(2);W1 = X(3);H1 = X(4);
X2 = Y(1);Y2 = Y(2);W2 = Y(3);H2 = Y(4);
if ((X1+W1)>=X2 && (Y2+H2)>=Y1 && (Y1+H1)>=Y2 && (X1+W1)>=X2 && (X2+W2)>=X1)
Intersection = true;
else
`Intersection = false;`

end

*

*Where X and Y are upper left corner indices of the bounding rectangle; W and H are width and height respectively.

in above if Intersection variable becomes true that means the boxes having intersection. you can use this code for further customization.
Thank You


text:
Q: Aggregate by name and average value per day in SQL I have data of the following format in a table (I have only shown values for two hours, but in reality I have values for all 24 hours):
Name    Availability           Date             ItemID
--------------------------------------------------------
S1          75        2014-11-11 19:00:00.000   1124023
S1          80        2014-11-11 20:00:00.000   1124023
S2          60        2014-11-11 19:00:00.000   1124010
S2          50        2014-11-11 20:00:00.000   1124010

I would like to get the average availability for the entire day in the following format in a view:
Name    Availability       Date     ItemID
--------------------------------------------------------
S1         77.5         2014-11-11  1124023
S2          55          2014-11-11  1124010

It's okay if Date in the output shows up as 2014-11-11 0:00:00.000 as well.
I tried the following, but it doesn't work. Any help would be greatly appreciated.
SELECT Name, AVG(Availability), CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME) AS Expr1, ItemID
    FROM dbo.ServiceAvailability
    GROUP BY CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME)

A: Your current query is very close, you are missing a few columns in your GROUP BY clause. I'd also suggest a shorter way to get the date without time.
SELECT
  Name,
  AVG(cast(Availability as decimal(10, 2))),
  CAST([Date] as date) AS Expr1,
  ItemID
FROM dbo.ServiceAvailability
GROUP BY Name, CAST([Date] as date), ItemID

See Demo. Since you are using SQL Server 2014, you can just cast your datetime column as a date - which drops the time portion.  I'd also suggest casting your Availability column to something other than an int so you get a decimal.
Since you are using an aggregate function any columns in the SELECT list that aren't being aggregated need to be included in the GROUP BY clause, so you need to include Name and ItemID.


text:
Q: Using Include? in Celerity Screen Scraping Script I am using to Celerity to screen scrape a web page and I'm attempting to scrape all of the text elements within a particular div class.  The following line of code I'm using is throwing the following error: wrong argument type String (expected Module) (TypeError)
Code: puts browser.text if browser.frame(:id, 'bottomframe').div.class.include? 'ClassName'
Can anyone tell me what this error means or more importantly how to fix my line of code.

A: Further review of the Celerity documentation has provided a solution to my question.
Celerity provides the ability to use Regular Expressions to specify what you would like to find/match on the particular web page.  For example: browser.link(:text, /ish/) means the first  element that matches the regular expression /ish/.
Thanks


text:
Q: should that interest
It would also be doing a big service to the honest business community and country, should that interest the president as well.

Source: http://www.fsfinalword.com/?page=archive&show=1&day=2015-05-26
What is the grammatical structure in the second part of the sentence ("should that interest the president as well"). Some kind of inversion? Could you rewrite that into a more comprehensible form?

A: "Should" is being used in a conditional sentence. It means about the same thing as "happen."
Here's a possible rewording of the sentence:
It would also be doing a big service to the honest business community and country, if that happens to interest the president as well.

A: Yes, the unusual word order in "should that interest the president" is an example of conditional inversion.
But if one tries to make it more comprehensible by simply reverting the word order to the more familiar "that should interest the president," the meaning of the phrase is changed.  In this new arrangement, the speaker is now declaring that service ought to interest the president.  In the original phrase, the speaker is uncertain about the president's interest.
To change the word order yet keep the same meaning, one needs a way of expressing this irrealis. That's the subjunctive, which is used for hypothetical situations, things that possibly may or may not exist (like the president's interest).
Another way to phrase it (in a familiar word order but preserving semantics) could be to say, "It would also be doing a big service to the honest business community and country, if that interest the president as well."
However, in everyday spoken English the subjunctive form for many verbs is increasingly uncommon (except for be and were ).  So it may be aceptable in some circles or even preferable to use "It would also be doing a big service to the honest business community and country, if that interests the president as well."

A: Yes, the final subordinate clause exhibits subject-auxiliary inversion. The reason that's possible is that the modal auxiliary "should" is in the subjunctive mood. The subjunctive is appropriate since the president's preference is not yet known, but the main clause is conditional on it.
For example, "If you had called, I would have answered." becomes "Had you called, I would have answered." This is not unlike the inversion that happens in questions, such as "Did you call?" or "Have you called yet?" where the meaning of the inversion also suggests uncertainty.
The simplest rewriting merely changes the clause to "if that should interest the president as well."
(For discussions of this, see here and here.)
The non-subjunctive version (called the indicative mood) of "should" is "shall," which is in the future tense. "That shall interest the president" would be a statement of certainty about his future preference.


text:
Q: Grey text appear white with outline in android device anyone has had this issue?
I am making an android app and my text within textview is a light grey. It is not very visible, but that is the effect I want.
When I look at my emulator it is fine, but when i upload the app to my android device, the text is corrected and now appears as white with a black outline.
I don't want this. I want the light grey color...
here is the actual code for the full layout for those asking:

 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_splash_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:layout_gravity="center"
android:background="#ffffff"
>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="some text here"
    android:textColor="#888888" /> </RelativeLayout>

A: In the comments, @Ma3x asked in the comments:

Since also your battery level and your clock display text are white with a black outline, I assume this is something at your system's level. Do you have some high contrast accessibility turned ON or any custom system-wide UI modifications? Or is it just a default theme like that? –

That gave me the hint I needed. In Settings > accessibility > High Contrast.


text:
Q: Filtering Pandas MultiIndex DataFrame Based on Level Counts I have a MultiIndex Pandas dataframe which looks like this:
col1    col2    col3
a       e       m
b       f       n
        g       o
c       h       p
        i       q
d       j       r
        k       s
        l       t

The MultiIndex consists of col1 and col2.
How can I select the "rows" of col1 which hold exactly two index labels in col2?
I.e., I want:
col1    col2    col3
b       f       n
        g       o
c       h       p
        i       q

A: Use the group by filter
df.groupby('col1').filter(lambda x: len(x) == 2)

          col3
col1 col2
b    f       n
     g       o
c    h       p
     i       q

A: IIUC
s=df.groupby(level=0).size()

df.loc[s[s==2].index.tolist()]
Out[583]:
          col3
col1 col2
b    f       n
     g       o
c    h       p
     i       q


text:
Q: Is there a way to search a corresponding column based on specific criteria? Excel I want to ask excel to search in a list (column) to see if the value in a specific cell appears. I then want to search the values next to these matches (in the next column) to see if a different specific cell content appears in these adjacent cells. I expect the result to be TRUE or FALSE.
As an example:
Do the contents of E1 appear in H:H next to contents of A23 in G:G.
Sample image

Thanks in advance.
I am open to trying it in R but suspect it will be easer in excel as the drag function will make adjusting the values easier.

A: So... I created a list then used countif function on that list.
the list constructed:
q4 = the variable I wanted to look for.
column A has the matching variable to q4 in in it
column c has the variable I wanted listed next to q4 .
=TEXTJOIN(", ",TRUE,IF(Q4=$A$3:$A$67,$C$3:$C$67,""))


text:
Q: Git ignore only files with the same name as folder I have this directory structure:
app/.bundle/
app/file1.bundle
app/tmp/file2.bundle
app/.gitignore

I would like to add an entry in .gitignore that only ignores files that ends with .bundle.
Doing *.bundle will also ignore the folder .bundle, but I want it checked in along with the contents.

A: You can do this:
*.bundle
!.bundle/

This will ignore everything that ends with .bundle, except a folder that is called .bundle.

A: If you have a directory with a file of the same name
samename/samename then I believe you can add to your .gitignore file:
samename/samename

Then only the file but not the directory will be ignored. If you only have
samename

in your .gitignore file then both the directory and the file will be ignored.
In your first version the file with the same name in a different directory will
not be ignored.  Say differentname/samename will not be ignored.  Let me know if I am wrong.


text:
Q: Devex Popupcontrol content not displayed in Firefox I am trying to use Devexpress popup control in a asp.net's repeater control to show full size image of the product.
It works perfectly in IE but image is not being displayed in Firefox and Chrome. I have tried to use same code as in http://demos.devexpress.com/aspxperiencedemos/popupcontrol/Features.aspx but still no success.
One difference I have noticed is that in my page popup control has an empty iframe while on devex's page there is no iframe. I could not find a property to control this thing.
I am using trial version of Devex 10.2.8.0.


text:
Q: Accessing a OGC WMS server and publishing it to ArcGIS FlexViewer I am trying to publish an OGC WMS service to my Flex Viewer. Within the configuration files amongst a few other layers I have the following:
        <layer label="EARSS National Outage Map" type="wms" visible="false" visiblelayers="earss:national_outage_map" skipgetcapabilities="false" alpha="0.6"
                autorefresh="60"
                url="https://earss.extranet.ornl.gov/geoserver/ows?service=wms&version=1.1.1&request=GetCapabilities/obs?srs=EPSG:4326">

The service does not appear within the TOC of the viewer. I tried the trick of creating "a service with a service" and that did not work.

A: hi you are using wms as a service but you are using wfs methods in your url
so u have juste to change ur url and it will work
Ex:
url="http://localhost:8080/geoserver/workspacename/wms?service=WMS&version=1.1.0&request=GetMap&layers=entrepot:layername1"

A:
url=https://earss.extranet.ornl.gov/geoserver/ows?service=wms&version=1.1.1&request=GetCapabilities/obs?srs=EPSG:4326

The WMS URL is incorrect, it should point to the service endpoint and not contain any parameters.
Take a look at the ArcGIS Viewer for Flex documentation.  Your layer information should look like:
<layer
  label="EARSS National Outage Map"
  type="wms"
  visible="false"
  alpha="0.6"
  url="https://earss.extranet.ornl.gov/geoserver/ows"
  visiblelayers="earss:national_outage_map"
  imageFormat="png"
  skipgetcapabilities="false"
  version="1.1.1"/>


text:
Q: What is the point of 'was this post useful'?
Possible Duplicate:
Anonymous user feedback now in testing

What is the point of the 'was this post useful' question under every answer?
I thought that was voting's job.

A: It only shows up if you're not logged in: it's to allow anonymous users a means to provide some amount of feedback that they can't otherwise do without reputation.
More info:
Anonymous user feedback now in testing


text:
Q: Ag grid customize group row cells with aggFunc I am trying to set a group with ag grid enterprise:
Here is an exmaple of my data row :
{'service': 'service A', 'agent': 'agent AAA', '5-5-2018': true, '6-5-2018': false}
I would like to group on the field 'service', I also have a custom component for cell rendering on fields with date.
Here is my colDefs :
[
 {field: 'agent', 'headerName': "Agents", hide: true},
 {field: 'service', 'headerName': "Services", cellRenderer:
    'agGroupCellRenderer', rowGroup: true, hide: true},
 {field: '5-5-2018', 'headerName': "05 - 05 - 2018", cellRenderer:
  "customCell",  aggFunc: "presence"},
 {field: '6-5-2018', 'headerName': "06 - 05 - 2018", cellRenderer:
  "customCell",  aggFunc: "presence"}
];

"presence" aggFunc only show a string '5/5' for now.
So the custom Cell works fine, I do have my groups and the agg data for each column, but custom Cell is applied to the group cells too, which in my case is not good.
How can I manage to redefine the cell renderer for group cells ( cells for the group row ) ?
Here is a screen shot :


text:
Q: Graphql Codegen Wizard Terminated Unexpected I am trying to use the GraphQL Codegen Wizard for my application.  I followed the installation instruction from this site: https://www.graphql-code-generator.com/docs/getting-started/installation
All the dependencies are successfully installed via npm with --legacy-peer-deps due to conflict.  When the time to run this command below, the script ended unexpectedly.  I did not get a chance to answer the question.
npx graphql-codegen init

enter image description here
what am I doing wrong?
System Details:

*

*OS Windows 10

*Node 16.15.1

*npm 8.11.0

*yarn 1.22.19

*Angular CLI 14.0.1

*GraphQL ^16

A: The only fix that I've come up with is downgrading to version 2.10.0 of graphql code generator.
In your package.json make this change -> "@graphql-codegen/cli": "2.10.0"
then npm install


text:
Q: Formatting a string to include tab characters in Infragistics Ultragrid I've been working with an Infragistics Ultragrid and I'm looking for a helpful hint. I'm using a table from SQL Server 2008 to populate my grid. The table that I'm calling has a column that has been updated to be something like this. "Items" + char(9) + char(9) + "Cost" + char(13) + char(10).
The "Items" section of the column is padded to be 50 charcters in length followed with the two tab characters, the cost then the new line characters. Ultimately this is what the results of a single row would look like. Notice how the items and the cost are lumped into a single cell.
Customer A             Chips and Soda           $5.00
                       Chips                    $2.50
                       Burger and Fries         $8.00
                       Fish and Chips           $7.50
                       Hot Dogs                 $4.50

When I print my sql server results in Management studio it works as intended. The problems is that when I print the results in the Ultragrid Cell it looks more like this:
Customer A              Chips and Soda           $5.00
                        Chips          $2.50
                        Burger and Fries         $8.00
                        Fish and Chips           $7.50
                        Hot Dogs       $4.50

One thing to note is that when I copy the contents in the cell and paste them to notepad it looks like the top table. I'm wondering if the width of the empty spaces is shorter than an actual character. If that makes sense? In any case how can I handle the output to be like the top table? Thanks - P Dog

A: Thanks to Davide, my solution was to have the font in the cell be displayed as "Lucinda Sans Typewriter." Now I understand the difference between fixed width fonts (monotype) and variable width fonts like Microsoft Sans Serif.


text:
Q: How Ruby on Rails run script file without interact? I am trying to run script file, backyard of application. When server started, the script must be run; until server stop.
I know rails runner command; but my script contain database process(insert), and return error named:
: uninitialized constant DataRecord (NameError)

script.rb :
#
# Some codes here
#

DataRecord.create(sensor_id: data[0].to_s, temperature: data[1].to_f, humudity: data[2].to_f)

#
# And some codes here..
#

-----------------------------------------------------------------

DataRecord is my model. It can run on 'application_controller', of course with interaction. Someone must enter the website. I don't want it.
data_record.rb :
class DataRecord < ApplicationRecord
end

application_record.rb:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end

activerecord gem is installed.
~$ ruby -v
ruby 2.3.1p112

~$ rails -v
Rails 5.0.1

A: Add require './config/environment' at the beginning of your script to load your rails app (and the models you need) in your script.
You might want to make it into rake or thor task instead.


text:
Q: what are the basic points to improve security on a php page? Some security points about get and post functions in php. and about sql connection in php so that i can save my website from crakers.

A: Here are some of the basic security tips covered by Steve in this blog 5 Basic PHP Security Tips which I hope you will find useful in your quest

UPDATE
The above link has been made redundant for a while now but here are some of the details covered in the article:
1. Input Filtering
Assume everything is dirty until proven clean. Filtering all data from external sources is probably the most important security measure you can take. This can be as easy as running some simple built-in functions on your variables.
When it comes to accepting user input, never directly use anything in $_GET or $_POST. Check each value to make sure it is something expected and assign it to a local variable for use.
// input filtering examples

// Make sure it is an integer
$integer = intval($_POST['variable_name']);

// Make it safe to use in a URL
$url_string = urlencode($_POST['variable_name']);
You can also check a value against a list of acceptable values. Here are two methods of doing this:

$page = 'home'; // initialize the variable

// Check input against a white-list of known options
$valid_options = array();
$valid_options[] = 'home';
$valid_options[] = 'downloads';
$valid_options[] = 'about';

if(in_array($_GET['page'], $valid_options))
{
   $page = $_GET['page'];
}

// OR this also works
switch($_GET['page'])
{
   case 'home':
   case 'downloads':
   case 'about':
      $page = $_GET['page'];
      break;
}

PHP as of version 5.2 provides a set of filtering functions designed just for the purpose of filtering user data. The filter_input() function is used to access a filtered version of input variables. This way you never have to touch the raw input via the $_GET or $_POST arrays.
// filter_input examples

// Make sure it is an integer
$integer = filter_input(INPUT_POST, 'variable_name', FILTER_SANITIZE_NUMBER_INT);

// Make it safe to use in a URL
$url_string = filter_input(INPUT_POST, 'variable_name', FILTER_SANITIZE_ENCODED);

// Make sure it is a valid URL
$url = filter_input(INPUT_POST, 'variable_name', FILTER_VALIDATE_URL);

2. Output Filtering
It is also important to filter what comes out of your applications. You want to avoid outputting the wrong characters and breaking the page rendering. This is also important in order to block certain attacks involving JavaScript injected by malicious users. There are a few functions to know for cleaning up text to display to the user:
$text = 'Test';
echo htmlspecialchars($text); // <a href="test">Test</a>
echo strip_tags($text); // Test

3. Database Queries
If your application uses a database to store data, this is another source of potential vulnerabilities. SQL Injection is a very common attack that involves maliciously crafted user input designed to change the logic of a query. This potentially allows the user to run any kind of query or bypass security measures. Stopping it is usually as easy as properly escaping data, or using prepared statements.
// $db refers to database connection resource/object
$name = "O'reilly"; // Contains a quote that will break the query

// MySQL via mysql_*
$safe = mysql_real_escape_string($name, $db);

// MySQL via MySQLi
$safe = $db->escape_string($name); // OOP Style
$safe = mysqli_real_escape_string($db, $name); // Procedural Style

// PostgreSQL
$safe = pg_escape_string($db, $name);

// Generic (last resourt)
$safe = addslashes($name);

4. Hide Your Errors
It's never a good idea to show the world your errors. Not only does it make you look bad, it also might give malicious users another clue to help them break your site. You should always have display_errors disabled in a production environment, but continue logging errors with log_errors for your own information.
These PHP configuration directives are suitable for a production server:
display_errors 0
log_errors 1

5. Use POST for Dangerous Actions
There are two common methods used to send data to a PHP application, GET and POST. GET works by adding variables to the end of URL's (eg. http://www.example.com/process.php?action=delete&id=123). POST works by sending variables in the body of the request (normal users will not see them). It is important to carefully consider which method to use for a certain task.
You should generally stick to POST when you are performing a potentially dangerous action (like deleting something). The reason is that is is much easier to trick a user into accessing a URL with GET parameters than it is to trick them into sending a POST request. Take this example:

If a user with an active session on your site visits another web page with the above image tag, the user's browser will quietly send a request to your site telling it to delete record 123.
Keep in mind that other precautions should also be taken to ensure requests are legitimate under a secure session. It is also easily possible to create a form that does the same as above using a POST request, so don't assume that method is "safe" either.

A: If you want to secure your application against SQL injection you must use these functions in your code :

*

*intval() : To get int values from Get or Post

*floatval() : To get floats

*doubleval() : to get doubles

For the string values you can use one of these functions :

*

*addslashes() : If you haven't any DB Connection yet

*mysql_real_escape_string() : the php tests the String input for you before sending it to the database if you are using MySQL

I wish these tips could help you because they helped me a lot
Regards
NiL

A: It all depends on how much effort you want to put into it. If you want the first principles, the other answers already provide some clues. If you want to provide security guarantees however...
Covering the web security topic fully takes a book's worth of information, so this cannot be done by a blog post or a stackoverflow reply.
A good start is looking at the detailed verification requirements of OWASP ASVS Level 1. ASVS is a standard for verifying the security of a web app before you ship it. Level 1 is the minimum level of security process you need to have to be able to make statements about the security of the app. Anything less and you simply cannot know whether the app is wide-open or not.
Other OWASP projects that are also helpful:

*

*OWASP development guide (incomplete)

*OWASP ESAPI (security API's to assist in correctly implementing the best practices)

A: Regarding SQL, make sure it only listens on localhost, 127.0.0.1. This has been the default for MySQL for several years now, but older installations used to listen to the outside world, exposing your server. I realize this only answers part of your question, but I personally don't believe PHP can be secure.

A: This is the most comprehensive PHP application security checklist I've seen
http://www.sk89q.com/2010/04/printable-php-security-checklist/