text:
Q: Is any Direct Summand of a Free Module over a PID also Free?
Let $R$ be a PID and $F$ be a free module over $R$. Suppose we have $F=A\oplus B$ for some $R$-modules $A$ and $B$. Then are $A$ and $B$ necessarily free?

If $F$ is finitely generated, then I know that $A$ too is finitely generated. Thus we can write $A$ as a direct sum of a torsion module and a free module. Since there is no torsion in $F$, the torsion part of $A$ must be zero. Thus $A$ must be free and same for $B$.
Is the statement true even when $F$ is not finitely generated?


text:
Q: MySQL error: Incorrect table definition; there can be only one auto column and it must be defined as a key Whenever I try to create the tables running my page called 'createtables.php', it can't create the table 'Ausleihe'.
<?php
    include 'connect.php';
    $query = "CREATE TABLE Schueler(
        SchuelerVorname VARCHAR(30) NOT NULL,
        SchuelerName VARCHAR(30) NOT NULL,
        StrasseUndHausnummer VARCHAR(50) NOT NULL,
        PLZ INT(5) NOT NULL,
        Ort VARCHAR(50) NOT NULL,
        SchuelerNummer INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY
    )";
    $result = mysqli_query($conn, $query);
    if(!$result) die ("Fehler beim erstellen der Tabelle 'Schueler': " .mysqli_error($conn));

    $query1 = "CREATE TABLE Buch(
        AutorVorname VARCHAR(30) NOT NULL,
        AutorName VARCHAR(30) NOT NULL,
        BuchName VARCHAR(50) NOT NULL,
        ISBN VARCHAR(35) NOT NULL,
        BuchNummer INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY
    )";
    $result = mysqli_query($conn, $query1);
    if(!$result) die ("Fehler beim erstellen der Tabelle 'Buch': " .mysqli_error($conn));

    $query2 = "CREATE TABLE Ausleihe(
        AusleihDatum DATE NOT NULL,
        AusleihNummer INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        BuchNummer INT(6) UNSIGNED AUTO_INCREMENT,
        SchuelerNummer INT(6) UNSIGNED AUTO_INCREMENT,
        FOREIGN KEY (BuchNummer) REFERENCES Buch(BuchNummer),
        FOREIGN KEY (SchuelerNummer) REFERENCES Schueler(SchuelerNummer)
    )";
    $result = mysqli_query($conn, $query2);
    if(!$result) die ("Fehler beim erstellen der Tabelle 'Ausleihe': " .mysqli_error($conn));
?>

What exactly am I doing wrong? Is it because of the foreign keys?
And sorry that my code is partly German, shouldn't really matter though.

A: The error message says exactly what the problem is - you can't have more than one AUTO_INCREMENT column. You will have to remove the AUTO_INCREMENT attribute from one of your columns. Probably something like this:
$query2 = "CREATE TABLE Ausleihe(
        AusleihDatum DATE NOT NULL,
        AusleihNummer INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        BuchNummer INT(6) UNSIGNED,
        SchuelerNummer INT(6) UNSIGNED,
        FOREIGN KEY (BuchNummer) REFERENCES Buch(BuchNummer),
        FOREIGN KEY (SchuelerNummer) REFERENCES Schueler(SchuelerNummer)
        )";

A: The auto incrementation should be done on your Buch and Schueler table. You should use the query from Matt Spinks answer.

A: Obviously the mysql error itself has the answer. 'Ausleihe' table have three auto incrementing columns which is causing the error. You have to remove AUTO_INCREMENT from 'BuchNummer' and 'SchuelerNummer' columns so only 'AusleihNummer' will be left with auto increment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restful services descriptor WADL or other way to identify method type? How can I identify a web service supports rest behavior or not? And if a service supports Rest then would that service expose any descriptor(e.g WADL) through which I can get method name, method parameters and method type (e.g. Get, put, post...)?
WSDL 2.0 supports Rest but currently no web service supporting it.
Thanks,
Asif

A: if you use the HTTP OPTIONS method against an url, it should tell you what methods it supports.


text:
Q: Reshape data long data in R or aggregate? I have a data set that is in a long format, and I can't seem to get it the right shape for analysis.  Perhaps this shape is appropriate — my experience has been almost entirely with wide format data, so this data file is not making sense to me. (Reproducible data file at end of the post.)
> head(df,10)
    ID attributes values
1   1         AU    AAA
2   1         AU    BBB
3   1         YR   2014
4   2         AU    CCC
5   2         AU    DDD
6   2         AU    EEE
7   2         AU    FFF
8   2         AU    GGG
9   2         YR   2013
10  3         AU    HHH

The attributes column contain variables of interest to me, and I want to perform a series of aggregation functions.  For example, I would like to:
1.Obtain a count of the number of authors (AU) for each ID.  For example:
   ID       N.AU
    1           2
    2           5
    3           1
    4           2
    5           5
    6           1

*Compute the median number of authors (AU) by year (YR)
YR           Median.N.AU
2013          5.0
2014          1.5

For both of these examples, I have tried dplry with group_by and summaries, but haven't cracked the code.  I have also tried dcast.  My hope is to come up with a solution that I can easily generalize to a larger data frame that has many more attributes that take on either a single value or multiple values.  Any help or pointers to a similar solution would be greatly appreciated.
attributes = c("AU", "AU", "YR", "AU", "AU", "AU", "AU", "AU", "YR", "AU", "YR",
   "AU", "AU", "YR", "AU", "AU", "AU", "AU", "AU", "YR", "AU", "YR")
ID = c(1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6)
values = c("AAA", "BBB", "2014", "CCC", "DDD", "EEE", "FFF", "GGG", "2013", "HHH", "2014",
   "III", "JJJ", "2014", "KKK", "LLL", "MMM", "NNN", "OOO", "2013", "PPP", "2014")
df <- data.frame(ID, attributes, values)

A: I think you're getting confused because you actually have two tables of
data linked by a common ID:
library(dplyr)
df <- tbl_df(df)

years <- df %>%
  filter(attributes == "YR") %>%
  select(id = ID, year = values)
years
#> Source: local data frame [6 x 2]
#>
#>    id year
#> 1   1 2014
#> 2   2 2013
#> 3   3 2014
#> 4   4 2014
#> 5   5 2013
#> .. ..  ...

authors <- df %>%
  filter(attributes == "AU") %>%
  select(id = ID, author = values)
authors
#> Source: local data frame [16 x 2]
#>
#>    id author
#> 1   1    AAA
#> 2   1    BBB
#> 3   2    CCC
#> 4   2    DDD
#> 5   2    EEE
#> .. ..    ...

Once you have the data in this form, it's easy to answer the questions
you're interested in:

*

*Authors per paper:
n_authors <- authors %>%
  group_by(id) %>%
  summarise(n = n())

Or
n_authors <- authors %>% count(id)

*Median authors per year:
n_authors %>%
  left_join(years) %>%
  group_by(year) %>%
  summarise(median(n))
#> Joining by: "id"
#> Source: local data frame [2 x 2]
#>
#>   year median(n)
#> 1 2013       5.0
#> 2 2014       1.5

A: Here's a possible data.table solution
I would also suggest to create some aggregated data set with separated columns. For example:
library(data.table)
(subdf <- as.data.table(df)[, .(N.AU = sum(attributes == "AU"),
                                Year = values[attributes == "YR"]) , ID])
#    ID N.AU Year
# 1:  1    2 2014
# 2:  2    5 2013
# 3:  3    1 2014
# 4:  4    2 2014
# 5:  5    5 2013
# 6:  6    1 2014

Calculating median per year
subdf[, .(Median.N.AU = median(N.AU)), keyby = Year]
#    Year Median.N.AU
# 1: 2013         5.0
# 2: 2014         1.5

A: I misunderstood the structure of your dataset initially.  Thanks to the comments below I realize your data needs to be restructured.
# split the data out
df1 <- df[df$attributes == "AU",]
df2 <- df[df$attributes == "YR",]

# just keeping the columns with data as opposed to the label
df3 <- merge(df1, df2, by="ID")[,c(1,3,5)]
# set column names for clarification
colnames(df3) <- c("ID","author","year")

# get author counts
num.authors <- count(df3, vars=c("ID","year"))
  ID year freq
1  1 2014    2
2  2 2013    5
3  3 2014    1
4  4 2014    2
5  5 2013    5
6  6 2014    1

summaryBy(freq ~ year, data = num.authors, FUN = list(median))
  year freq.median
1 2013         5.0
2 2014         1.5

The nice thing about summaryBy is that you can add in which ever function has been defined in the list and you will get another column containing the other metric (e.g. mean, sd, etc.)


text:
Q: Interesting exercises using printf & scanf only I'm running out of ideas for my "Beginning C" class, and the only topics I've discussed so far are Data types, Variables & the printf & scanf functions.
My last quizzes involved simple formulas (area of a circle, volume of a cube..) enclosed inside the printfs..

eg. printf("volume = %d",length * width * height);

I'm looking for something more interesting using only printfs and scanfs :(
Update~ Just to clarify: My students don't know how to use conditional statements and iterative statements yet. It's only week 2, and this is their very first programming class :'( And yes, they can only retrieve the input, then modify it in some way before they output it in the console. I can play with escape sequences (create a box asterisks) or format specifiers (a 3 precision division operation) but that's it..

A: *

*Write a program that asks the user
their name, age, and favorite letter
of the alphabet.

*Print a single sentence containing
all the information.

*Bonus: Print a sentence
containing the first letter of their
name.

Answer:
char name[50];
int age;
char letter;

printf( "\nWhat is your name? " );
scanf( "%s", name );

printf( "\nHow old are you? " );
scanf( "%d", &age );

printf( "\nWhat is your favorite letter of the alphabet? " );
scanf( " %c", &letter ); //skipping whitespace

printf( "\n\n-------------------\n\n");
printf( "Your name is %s, you are %d years old, and your favorite letter of the alphabet is %c.\n", name, age, letter );

printf( "The first letter of your name is %c", name[0] );

If you'd like some math in there, ask them questions like:

*

*Write a program that asks the user
how many weeks until christmas, then
print out how many seconds there are
until christmas (given the number of
weeks entered only).

A: I have used a unit converter previously.

*

*Convert temperatures to and from
Celsius, Fahrenheit, and Kelvin.

*Change the base as mentioned by
Alex.

*Cooking weights and measures has lots of interesting conversions.

A: How about a base-converter. In other words, prompt for a number in decimal and a number system (say, 2 for binary or 16 for hex) and then output the number in that system.

A: Using only printfs and scanfs, and nothing more?  You can only retrieve input and output the input if that's the case.
I don't think that's what you meant though...
Math/Algorithm Related

*

*Generate/Output the first N prime numbers

*Calculate factorial(n) recursively/iteratively

*Use C as a tool to Find a formula for sum of alternating sums up to positive N

Game Related

*

*Write a simple character based pong game (single player)

*Write "nibbles" a.k.a "snake" (char based)


text:
Q: trigger click automatically using jquery I am trying to trigger click automatically after the page load.
Here is the code
$("document").ready(function() {

    setTimeout(function() {

        $(".amcharts-export-menu-top-right").find('a').trigger('click');

    },1000);
});

But it is not working
Here is the entire code:
https://jsfiddle.net/32g26a4d/

A: You could try this
$("document").ready(function() {

 setTimeout(function() {

    $('.amcharts-main-div .amcharts-export-menu-top-right a')[0].dispatchEvent(new Event('click'))

   },1000);
 });

JSFiddle example

A: As you are using .export-main class for creating button using AmCharts you don't need to use any other class/find method for selecting that anchor button. Please follow below code::
$("document").ready(function() {
    setTimeout(function() {
        $(".export-main a")[0].click();
    },1000);
});

Working jsfiddle link:: link

A: You should do this during the chart's rendered or animationFinished event if you have an animation. $("document").ready() doesn't ensure that the chart will be finished loaded as the chart creation process is asynchronous.
Add this to your makeChart call:
//if you have startDuration set to a value > 0:
AmCharts.makeChart("chartdiv", {
  // ...
  "listeners": [{
    "event": "animationFinished",
    "method": function() {
      $('.amcharts-main-div .amcharts-export-menu-top-right a')[0].dispatchEvent(new Event('click'));
    }
  }]
});

//if you don't have startDuration set or it is set to 0:
AmCharts.makeChart("chartdiv", {
  // ...
  "listeners": [{
    "event": "rendered",
    "method": function() {
      setTimeout(function() {
        $('.amcharts-main-div .amcharts-export-menu-top-right a')[0].dispatchEvent(new Event('click'));
      }, 500)
    }
  }]
});

Updated fiddle


text:
Q: How to build an input form with Re-base (Firebase) in React Native? I'm playing around with Firebase and react native and found that re-base is a useful tool. I'm not so much into Redux but believe that rebase will allow me to make my app work something like this

I have some design issues on how to set it up. I'm not gonna drop some code because I'm afraid to do the XY-problem.
Imagine I have the following Firebase database setup
{"DRAFT 1": {
  "Information A": {
    "Value 1": foo,
    "Value 2": bar,
    "Value 3": baz
  },
  "Information B": {
    "Value 1": '',
    "Value 2": '',
    "Value 3": 'hello world'
  } },
 "DRAFT 2: {
  "Information A": {
    "Value 1": '',
    "Value 2": '',
    "Value 3": ''
  },
  "Information B": {
    "Value 1": '',
    "Value 2": '',
    "Value 3": ''
  } }
}

(I don't need to have spaces in the key names but would be nice..)
The screen should show the drafts but also allow me to create a new draft (colored borders indicate components).

If I press one of the blue button the Firebase ref is stored in the state of the outer blue component (and passed down as prop to the next yellow component).
If I press the green button it will push a new key to Firebase and store it in the state (of the blue component)
Once the picked draft ID is stored in the state (blue component) a new (yellow) component shows and the old one hides (orange). The ID is passed down as prop

The InputComponents each a JavaScript Objects in their state that can be synced with the Firebase node (got the ref from the props).
if the object doesn't exist in Firebase the component will push/post the object to Firebase and then sync it.
The button in the top right corner is looking at the Firebase node (ref is stored in the state) and some logic checks if if all fields are filled out, then it would be clickable...
Is this a good design or is there a smarter way (no redux thx)?


text:
Q: PATH variable in .zshenv or .zshrc My setup is zsh 5.0.5 in arch linux
I have set the PATH variable as below in .zshenv
typeset -U path
path=(~/bin $path)
DW=$HOME/Downloads

but it didn't work. print $PATH shows only
/usr/local/bin:/usr/bin:/usr/bin/vendor_perl:/usr/bin/core_perl

.zshenv was read, because I could see DW variable is set. Only PATH variable isn't set. And what I don't understand is, after rename the .zshenv to .zshrc, PATH variable just works as intended.
Need any special treatment setting environment variables in .zshenv?

A: I just encountered this problem myself, and the real answer is that Zsh on Arch sources /etc/profile – which overwrites and exports PATH – after having sourced ~/.zshenv.
See: https://wiki.archlinux.org/index.php/Zsh#Configuration_files

A: It seems that when you have macos or some linux distros there is a canonical solution to the problem which involves /etc/paths or /etc/paths.d. You should be letting /usr/libexec/path_helper construct your path for you using configuration files.
This immediately solved the problem in all places for me.

A: I've got the same problem. The cause was my .zshrc (fresh install of oh-my-zsh) override PATH (ignoring existing value):
export PATH="/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/core_perl"

To fix, I comment the line.


text:
Q: get updated date field row after inner joining table I have a situation where a row is inserted whenever a schedule is created with call_back_date value
la_id is the same for each row, i want get a most recent row that is max(call_back_date)
I have written this query which fetch all the entries for those schedule after inner joining three tables:
SELECT
la_details.application_no,
la_details.id la_det,
la_details.client_id client_id,
la_details.la_name la_name,
la_details.sex sex,
la_details.advisor_name advisor_name,
la_details.client_phone client_phone,
la_details.client_mobile client_mibile,
la_details.level level,
la_details.state state,
la_details.pin_code pin_code,
trans_schedules.id schedule_id,
trans_schedules.*,
comments.descriptions
FROM
la_details
INNER JOIN trans_schedules
ON
trans_schedules.la_id=la_details.id
INNER JOIN comments
ON
comments.comment_id=trans_schedules.comment_id
WHERE
(trans_schedules.comment_id<>'1'
OR
trans_schedules.list_followup = '1'
OR
trans_schedules.counter_flag='0')
AND
la_details.case_closed='0'
ORDER BY
trans_schedules.call_back_date
) a1 INNER JOIN
(
SELECT la_id,MAX(call_back_date) AS call_back_date from
trans_schedules group by la_id
) b1 on a1.la_det = b1.la_id and a1.call_back_date  = b1.call_back_date

My question is how could i use a subquery on previous query to get max call_back_date row
Thanks in advance for help!!!!

A: For MySQL:
Select LAST_INSERT_ID();
It will give you last inserted identity record


text:
Q: What are the advantages of a custom MembershipProvider in ASP.NET? If I need to implement my own MembershipProvider class, I have to implement all the services I require myself, so what advantage do I gain by implementing a MembershipProvider derived class versus just writing my own MySecurity class?

A: Getting an authentication system right is hard, because it's so easy to build something that only appears to work.  You don't want to find yourself in a situation where a year after deployment you finally discover your system was cracked six months previously.
Building your system using the MembershipProvider model helps you do it right by giving you a skeleton that lends itself to being implemented correctly.  You only need to accurately fill in a set of methods, and you can rely on the high-level architecture provided to make sure you are using the right methods in the right places.
Getting individual method implementations done right is comparatively easy.  You can put those into your unit test and have confidence that they do what they are supposed to.
Put another way, you don't have to worry about whether you check your authentication token in the right places.  The parts of ASP.Net that call into the membership provider know when to do that.  All you have to do is correctly implement the check, and that normally comes down to a simple comparison.
Additionally, you may not need to start from scratch.  You have to option to inherit from an existing provider and only add the functionality you want that it doesn't already provide.

A: If you just need something a "little" different from one of the default membership providers then you should probably just consider inheriting from one of the built-in providers or one of the better 3rd party providers and extend it with the additional functionality that you need or override the functionality that you want to change.

A: The main advantage of writing your own MembershipProvider class is that it's considered by the ASP.NET as a first-class component and you can use the standard interfaces for authentication and authorization and only have to change the config file afterwards if you want to use a different provider.

A: Technically, you should gain some level of portability - by using the existing model, you should be able to drop your provider into other web applications, to replace their membership system with very little effort.
Unfortunately, the number of 3rd parties out there who seem to have gone their own way when it comes to membership/profiles is quite impressive, and also rather depressing, especailly when you've put all the effort into writing something based on it.
That being said, by using the membership provider model, all the other controls that use membership "just work" (i.e. Login, LoginStatus, LoginName, etc) without having to write custom versions of those as well.

A: Well, it depends... I found it very useful because I had to add the concept of functions, so that every role had functions associated to them, and so forth.
In that case I implemented my own Membership and RoleProvider classes which contained the AddFunctionToRole method... IsFunctionAssignedToUser method... etc etc
A little more info on that here


text:
Q: Review of solution: Prove $\liminf({a_n}) \ge \liminf({b_n})$ ${a_n} \ge {b_n}\forall n \in $
Prove: $\liminf({a_n}) \ge \liminf({b_n})$
I proved it by contradiction. Let's assume $\liminf({a_n}) < \liminf({b_n})$.
$a := \liminf({a_n})$
$b := \liminf({b_n})$
So, by the definition of partial limit:
$\eqalign{
  & \forall \varepsilon  > 0\forall {N_0} \in \exists n > {N_0}st|{a_n} - a| < \varepsilon   \cr
  & \forall \varepsilon  > 0\forall {N_0} \in \exists n > {N_0}st|{b_n} - b| < \varepsilon  \cr} $
Then,
$\eqalign{
  & a - \varepsilon  < {a_n} < a + \varepsilon   \cr
  & b - \varepsilon  < {b_n} < b + \varepsilon  \cr} $
Lets substract the two inequalities:
$a_n-b_n < a-b < 0$
$a_n-b_n$ must be positive by definition, and so the last line is a contradiction.
Therefore, liminf of $a_n$ must be equal/greater than liminf of $b_n$.
Does the logical statements are good enough?
Do you think it can be polished?

A: Since $\liminf a_{n} = a$ it follows from definition of "$\liminf$" that for any $\epsilon > 0$ we have $a_{n} > a - \epsilon$ for all sufficiently large $n$ and $a_{n} < a + \epsilon$ for an infinity of values of $n$. Similarly we have a statement for $b_{n}$ and $b$. Assume on the contrary that $a < b$ and we set $2\epsilon = b - a$ so that $b - \epsilon = a + \epsilon$. Now we can see that $b_{n} > b - \epsilon = a + \epsilon$ for all sufficiently large values of $n$. This means that $a_{n} \geq b_{n} > a + \epsilon$ for all sufficiently large values of $n$ and this contradicts the statement "$a_{n} < a + \epsilon$ for an infinity of values of $n$". This contradiction shows that $a \geq b$.
Note that even if $a_{n} > b_{n}$ for all $n$ we can only infer $a \geq b$ and not $a > b$. In fact we can have $a = b$ in this case too.


text:
Q: sonar jacoco report not executed I have added code for generating jacoco coverage report using sonar.But when i am running mvn clean install sonar:sonar.Only sonar-related functionality executed.Jacoco coverage report is not generated.
<!-- Below plugin ensures the execution of test cases during maven build -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>${runSuite}</include>
                    </includes>
                </configuration>
            </plugin>

            <!-- Sonar-JaCoCo integration plugin -->
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.6.201602180812</version>
                <configuration>
                    <destFile>${sonar.jacoco.reportPath}</destFile>
                    <append>true</append>
                </configuration>
                <executions>
                    <execution>
                        <id>agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>

            <properties>
        <sonar.sources>src/main</sonar.sources>
        <sonar.tests>src/test</sonar.tests>
        <!-- Below property indicates the pattern of the test suite -->
        <runSuite>**/*Suite.class</runSuite>
        <!-- Sonar-JaCoCo properties -->
        <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
        <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
        <sonar.jacoco.reportPath>${basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
        <sonar.language>java</sonar.language>
    </properties>

A: The Java plugin no longer runs your unit tests for you. As documented here, you need to launch them yourself before the analysis:
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Dmaven.test.failure.ignore=true


text:
Q: Laravel Eloquent check for relationship between two specific models I have two models with a many to many relationship
Post and Category
I am trying to find out if a specific category belongs to a specific post.
I can see if a specific post has any categories, I'm tempted to just get all of the categories for the post and load it into an array then do an in_array check for the category I am looking for. Before I go that route is there a proper way to do this in Eloquent though?

A: You can do this like so:
$post->categories()->where('id', $category->id)->exists();


text:
Q: F# lookup issues on recursive types I am trying to create two types where one is able to remove itself from the other such as in this example.
type employee (workplace : Job) =
    member this.Fire () = workplace.Employees.Remove(this) |> ignore
and Job () =
    let employees = new ResizeArray<employee>()
    member this.Employees = employees

But this gets me the compile error of "Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved."
I'm not sure what I am doing wrong here. Any help would be appreciated

A: You can solve the problem even without reordering the declarations - when the F# compiler type-checks the Employee declaration, it doesn't yet know what is the type of workplace.Employees (because the type hasn't been declared yet), so it doesn't know where does the Remove method come from. You can correct that by adding type annotation that specifies that Employees is ResizeArray<Employee>:
type Employee (workplace : Job) =
    member this.Fire () =
      let emps : ResizeArray<Employee> = workplace.Employees
      emps.Remove(this) |> ignore

and Job () =
    let employees = new ResizeArray<Employee>()
    member this.Employees = employees

However, this example isn't very functional - if you're going to use mutable state (such as ResizeArray), then the state should be hidden as private state of the type (so Jobs could have a Remove method).
In general, declaring recursive type declarations is a bit less comfortable in F# - however, you shouldn't need them that often. Quite frequently, you can use more generic types (i.e. Job may not need to know abou the Employee type).

A: Try this..
type Job () =
    let employees = new ResizeArray<employee>()
    member this.Employees = employees
and employee (workplace : Job) =
    member this.Fire () = workplace.Employees.Remove(this) |> ignore


text:
Q: Why do values change when casting a function pointer? (msvc ver20) To test storing a value in a text segment, I wrote the code below.
The value of 'foo' and the value of 'v', 'bar' are different when viewed using debugging. Normal functions without '__declspec(naked)' also have their values changed.
When debugging memory using the address of 'foo', '12345678' is displayed well.
I'd appreciate it if you could tell me why the values change.
edit:
When I checked again, the only thing that the 'foo' value displayed in debugging was different from the value or output of the program. But I still don't know why it's different.
code:
__declspec(naked) void foo() {
    __asm {
        _emit 0x78
        _emit 0x56
        _emit 0x34
        _emit 0x12
    }
}

int main() {
    cout << sizeof(&foo) << '\n';

    void (*bar)() = foo;
    cout << bar << '\n';

    void* v = (void*)(&foo);
    cout <<  v << '\n';

    unsigned* p = (unsigned*)(v);
    cout << p << '\n';

    unsigned a = *p;
    cout << hex <<  a;

    cout << (void(*)())foo;
    cout << foo;
}

output:
4
00EA1357
00EA1357
00EA1357
00EA1357
00EA1357
c74e9


text:
Q: Issue with authenticating against Azure AD I'm trying to authenticate an asp.net core 2 application using Azure AD.  It works fine locally.  Unfortunately when I publish it to Azure, I keep running into issues.
I keep getting this error:
AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application:
No matter what I change in Azure and the code, I'm not able to get it to work.
In Azure AD, I have the same values set as the reply urls.
In App registrations (Preview), the app has the same reply urls.
I'm not sure if this is causing the issue or not. The application and AD are on different Azure instances.  I've checked and the Application has the correct Azure AD ClientId.
Is there anything else I can do/try?
This is what my app.config looks like:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "companyname.com",
"TenantId": "b1234",
"ClientId": "a1234",
//"CallbackPath": "/signin-oidc"
"CallbackPath": "http://mysite.azurewebsites.net/signin-oidc"
//"CallbackPath": "https://localhost:44330/signin-oidc"
},

According to everything that I've read, this should be working.

A: The callback url is used in Azure APP service's built-in authentication (Easy Auth) .
So the first attempt is disable the Easy Auth :

*

*In the Azure portal, navigate to your App Service app. In the left navigation, select Authentication / Authorization.

*Make App Service Authentication OFF.

Then you application will take over the authentication process.


text:
Q: Simpson's rule in numerical methods In the following code I have implemented composite Simpson's rule. However I should be getting approximately $291$ but for some reason I am getting something different. I implemented a few other methods to test it and the proper answer was $291$ So how do I fix my code?
from math import pi,cos,sin
def SimpsonMethod(f,a,b,n):
    h = (b-a)/n
    s = f(a)+f(b)
    for i in range(1,n,2):
        s+=4*f(a+i*h)
    for i in range(2,n-1,2):
        s+=2*f(a+h*h)
    return s*h/3
 print(SimpsonMethod(lambda x: x**2,5,10,100))

giving the output
237.39917687499988

A: Typo in the part of the function that calculates the even nodes, should be s+=2*f(a+i*h), this is after fixing:
from math import pi,cos,sin
def SimpsonMethod(f,a,b,n):
    h = (b-a)/n
    s = f(a)+f(b)
    for i in range(1,n,2):
        s+=4*f(a+i*h)
    for i in range(2,n-1,2):
        s+=2*f(a+i*h)
    return s*h/3.
print(SimpsonMethod(lambda x: x**2,5,10,100))

and the result
291.66666666666674


text:
Q: How Can I Conditionally Select Data using a HTTP POST request while getting Data from Server? So I am using a RestAPI where it is specified in the document that I have to :

*

*log in using the username and password with the POST method. The response of which is a token. Raw JSON to be used.

*use that token and make a Bearer POST request with headers as "date_end" and "date_begin" to retrieve data in JSON format. The same Raw JSON to be used.

Now the final retrieved data has 25 keys which does not include the "date_end" and "date_begin" keys. Out of which one column is the STATEX. Of all, there's is a "XXXXX" value. Now I want to query only these "XXXXX" values from the server. How do I do it without downloading the entire dataset and filtering? I want the request to query like we have 'parameters' in GET request. This RestAPI does not allow GET requests.
I did get the token value successfully. Now for retrieving the data,
I have tried:
json_data = {"date_end" : ... , "date_begin" : ...}
requests.post(url=url, headers={Authentication: 'Bearer '+token}, json=json_data)
Which produces a JSON response contining 25 Keys. I only want data of key "STATEX" which has value "XXXXX"
I don't want to download all data and filter because the rest of it is not needed.


text:
Q: How do I match groups from Exchange Online to Azure AD? I want to uniquely identify a group that is used in Exchange Online so that I can find the same group in Azure AD. The group has, in my case, permissions on a mailbox as returned by Get-MailboxPermission in PowerShell.
When using the Get-Group cmdlet from the ExchangePowerShell-Module I get a few identifying properties, but none of those are helpful in identifying the same group in Azure AD:

*

*DisplayName (not unique and changeable)

*SamAccountName (not available via Graph API or AzureAD PowerShell module)

*Sid (specific to Exchange Online and not the same as in Azure AD)

*WindowsEmailAddress (changeable, not required)

*ExchangeObjectId (not available via Graph API or AzureAD PowerShell module)

In Azure AD I have a whole other set of identifying properties (e.g. Graph API):

*

*ID (the ObjectID displayed in Azure AD, not available in Exchange Online)

*DisplayName (not unique and changeable)

*Mail (changeable, not required)

*SecurityIdentifier (specific to Azure AD and not the same as in Exchange Online)

It seems my only option would be to use a combination of DisplayName and maybe WindowsEmailAddress/Mail which is horrible?
Is there any other way I could uniquely identify the groups to match them together?
UPDATE:
My scenario is as follows:
I need to process all permissions of all mailboxes:

*

*I basically call Get-MailboxPermission for every mailbox.

*By expanding the property User I can get the Exchange-SID of the permitted user or group.

*I can then match this Exchange-SID to a user or group as returned by the Get-User or Get-Mailbox cmdlets.

*I can find the corresponding Azure AD user by matching the ExternalDirectoryObjectId as returned by Get-User.

*The group does not have the property ExternalDirectoryObjectId and no other uniquely identifying and unchangable property that can be found in Azure AD.

A: Case 1 : Matching the Group ID From Graph API to Exchange Online Commandlets
Getting the list of the groups from the Graph and matching it with the group from the Exchange Online Commandlets.
The Id Obtained from the Graph API will match that of the Get-Group
The below is the snippet of the Graph response :
{
            "id": "c0749057-8163-4228-be88-1a0df3aab7b1",
            "deletedDateTime": null,
            "classification": null,
            "createdDateTime": "2020-09-08T11:21:53Z",
            "creationOptions": [],
            "description": "This is a new Group",
            "displayName": "NewGroup1",
            "expirationDateTime": null..............

If you get the Id : c0749057-8163-4228-be88-1a0df3aab7b1 & Run the below command, you will get the corresponding group :
Get-Group -Identity "c0749057-8163-4228-be88-1a0df3aab7b1"

Output :

Case 2 : Matching the Group ID from the Exchange Online Commandlets to Graph Group ID
(UPDATE)
Only the unified groups will be visible in the Graph APIs (or) will have the ExternalDirectoryObjectId
So you could run
(Get-UnifiedGroup -Identity <Your Exchange Group ID>).ExternalDirectoryObjectId

This will return the Azure AD Object Id of the Group.

HTH !


text:
Q: How to open another tab with a link? I've used jquery-ui tabs in a page. But I want, if someone clicks the link "Click me" in Tab1, it will automatically open the Tab2 for him. I want the link "Click me" to work as same as the Tab2 option works. How can I do that?
My codes are given below
<!doctype html>

<meta charset="utf-8">
<title>Homepage</title>

  <link rel="stylesheet" href="css/jquery_ui.css">
  <link rel="stylesheet" href="css/index.css">

Tab1

Tab2

Tab3

Something about Tab1

Click me

Something about Tab2

Something about Tab3

A: use target="_blank" attribute in your anchor tag, like

Tab1

A: Use this:

Click me

A: Maybe it will help you for custom click jquery-ui-tabs-with-nextprevious
$('#my-text-link').click(function() { // bind click event to link
    $tabs.tabs('select', 2); // switch to third tab
    return false;
});

A: You can set the id of tab two in href tag of anchor element.

Click here to open tab 2

A: try this..

Tab1

using this link you can open new window with new page.

A: on the click event of the "Click me" button
Add the below code to acheive it.
$("a[href='#tab_two']").trigger("click");

This should work for you.


text:
Q: Android HTTP POST to get response without JSON, and put in Toast I wanted to test if my Android app can sucessfully get the response from a php page, without JSON. The php just contains echo "hello";, but I failed to Toast it. Closest solution I can find is, where I tried to put some parts of it into my code: How can I view the string sent from httppost?
My code as below (updated):
public void onClick(View v) {
    Thread t = new Thread() {
        @Override
        public void run() {
            Log.i("Threaded", "Inside thread!!!");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.10/fyp/test.php");

            try {
                HttpResponse response = httpclient.execute(httppost);
                InputStream content = response.getEntity().getContent();
                Log.i("Connect", content.toString());

                BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while ((line = buffer.readLine()) != null) {
                    sb.append(line + "\n");
                }
                Log.i("Connect", sb.toString());

                handler.post(new Runnable() {
                    public void run() {
                        showToastMessage("hello");
                      }
                    });
            } catch (Exception e) {
                Log.e("Connect", "Fail");
                e.printStackTrace();
            }
        }

    };
}

The thread seems not running, where the line Log.i("Threaded", "Inside thread!!!"); is not showing in LogCat, which part am I doing wrongly? Note: handler has been declare in the class.

A: Make sure you perform the toast on the UI thread or else it will fail.
Either use a Handler or wrap your network operation in a AsyncTask where you pass the result to the onPostExecute method which is processed by the UI thread.
http://developer.android.com/reference/android/os/AsyncTask.html
If this is not your problem, add logging to see that you get a response from the server and check your LogCat for the "hello"


text:
Q: How do I create path-based routing rules for Azure Application Gateway in C#? With Azure Portal I have manually created an Application Gateway using path-based routing. Now I need to automate this in C#. I can't seem to find any way to create a path-based routing rule. I'm using the Microsoft.Azure.Management.Fluent package. What am I missing?
If this isn't supported through the Fluent API, is there a REST alternative?
Ex:
var appGw = Azure.ApplicationGateways.Define(AppGwName)
    .WithRegion(Region)
    .WithExistingResourceGroup(resourceGroup)
    .DefineRequestRoutingRule("default")
    // Now what?

A: I can find the path-based routing settings in the Microsoft.Azure.Management.Fluent package, but cannot find a way to configure it. And there is an issue related to this in github.
But it can definitely use the Microsoft.Azure.Management.Network package to create the Application Gateway with path-based routing settings.
Here is an example:
        ApplicationGateway gateway = new ApplicationGateway();

        //configure thepath-based routing.
        ApplicationGatewayRequestRoutingRule r = new ApplicationGatewayRequestRoutingRule();
        r.RuleType = ApplicationGatewayRequestRoutingRuleType.PathBasedRouting;
        gateway.RequestRoutingRules.Add(r);

        //configure other settings.
        //gateway.Location = "xxx";

        gateway.Validate();

        //create the gateway.
        NetworkManagementClient networkManagementClient = new NetworkManagementClient(your_credential);
        networkManagementClient.ApplicationGateways.CreateOrUpdate("resource group name", "application gateway name", gateway);

The reference code example: here and here.
For api, you can refer to Create Application Gateway. And in the request body, it defines the path-based routing settings.


text:
Q: Grails - Forked Grails VM exited with error when compiling It happens when grails tries to compile the project, when --stacktrace and --verbose are used it shows the same output. I tried to reinstall the plugins and grails.
I'm using grails 2.4.3
Here's the error:
Running without daemon...
Compiling 230 source files
Parent process shutdown. Exiting...
Error Forked Grails VM exited with error

A: The problem that you have is that you don't know what is wrong. In order to find the real problem I recommend you change in grails-app/conf/BuildConfig.groovy the parameter: grails.project.fork for this:
grails.project.fork = [
    compile: false,
    test: false,
    run: false,
    war: false,
    console: false
]

Try again and you will see the real problem.

A: grails-app/conf/BuildConfig.groovy
dependencies {
    // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
     runtime 'mysql:mysql-connector-java:5.1.27'
    // runtime 'org.postgresql:postgresql:9.3-1100-jdbc41'
    // runtime 'mysql:mysql-connector-java:5.1.40'

}

A: I had the same issue ,It may be some database problem check whether you have a correct dump or go to C:\Users\Your-pc.grails\2.4.4\ and delete the .slcache folder and retry running the application again.

A: First time when I faced this error I delete project and imported again. It resolved.
Next time I deleted target forder and files from. m2 folder. It worked.


text:
Q: How can I detect if my computer has been remotely accessed and monitored by an employer? I work remotely as a freelancer, on a new imac I purchased specifically for this gig. Until recently, I had a seat on the client's Adobe Enterprise, and I frequently exchange files with the client. I became aware of suspicious activities, such as the cursor moving by itself, and clients making references to my work or computer activity, that they could not have known without access to my desktop, or mysterious system crashes. I have since tightened up my security, but: How can I detect the presence of a monitoring system, or perhaps, an undisclosed user, and prevent access to my computer, and a potential invasion of privacy?

A: Assuming they're monitoring or remotely logging in to your machine, the computer itself would have to be configured to accept these connections. Open System Preferences>Sharing and go to the Screen Sharing tab, check whether it is on, if so whether it is set to allow access for all users or only specified ones. Do the same for the Remote Login tab, Remote Management tab, and Remote Apple Events tab.
If all of these are disabled, or access to these functions is restricted to users you know for a fact they do not have access to, try going to the Users & Groups preference pane, and check to see whether there are any Network-Sharing enabled users besides the administrator account, and if the Guest user is enabled, whether or not it has Remote Login access.
If none of the above are the case you may try checking the machine's SSH logs, assuming SSH has been enabled, to see if there have been any recent remote logins via the Terminal. Finally, of course, if there are any Remote Desktop applications installed, check their logs as well. I am not familiar with Adobe Enterprise, perhaps check the application settings to see if anything regarding remote monitoring or connections is mentioned.
If none of the above are relevant, or do not yield any results, you can always try going to the System Preferences>Security & Privacy pane, then the Firewall tab, turning on the Firewall, opening the Firewall Options... window, checking Automatically allow built in software to receive incoming connections, unchecking Automatically allow downloaded signed software to receive incoming connections, and checking Enable stealth mode. This will effectively block all incoming connections from whatever software is used for monitoring/remote login, and may even reveal what software is being used when it prompts for Firewall access during the next remote login attempt.


text:
Q: Report "Queries by type" analysis I'm using pgbadger to analize postgres logs.
I see "queries by type" section and don't understand what means "others" category in table.

I know only dml, ddl, tcl, dcl commands. DCL is absent in table, but Others is too huge to be only dcl.
Please tell me what queries are included in category "Others"?

A: In my case, it is referring to my executed functions, every time a function is executed pgbadger recognize it as "others" and I  have select, create a temp table, insert and delete in one single function. Wondering if triggers can be recognized as "others" as well.


text:
Q: Moving Camera to specific Point in Scene (while rotated/translated) - OpenGL ES 2 I was wondering how I can move my camera to a specific point in my scene, even if I already have rotated, translated and scaled in all three dimensions. For a point P (x,y,z) I clearly can't use translate(x,y,z) - if I do so I'm ending on a totally different point.
I've a building with floors and rooms. I would like to have two different camera perspectives. The first one is the Bird-Eye, where I can see a specific position from the top. It should look similar to:

The second one is a 3-dimensional, where I have my camera with a specific value (but constant, like 30°) and I'm looking to the point (and I would like to chose my "x"-rotation here). As you can see in the following picture, this is what the second camera view should look like:

Like I said I'm not aware of how to move the camera to a specific position because after rotation/translating the values are totally different. Besides this, I'm not sure if I'm thinking about the correct way.
My whole translation/rotation/scaling is only about the model. I don't change anything in the look-at method. I'm using the following methods for modifying the model (by on-touch-gestures):
             // translate to world position
             Matrix.setIdentityM(tmpMatrix, 0);
             Matrix.translateM(tmpMatrix, 0, translateX, translateY, translateZ);
             Matrix.multiplyMM(resMatrix, 0, tmpMatrix, 0, mModelMatrix, 0);
             System.arraycopy(resMatrix, 0, mModelMatrix, 0, 16);

            // rotate around center
            Matrix.setIdentityM(tmpMatrix, 0);
            if (rotationX != 0)
                    Matrix.rotateM(tmpMatrix, 0, rotationX, 1.0f, 0.0f, 0.0f);
            if (rotationY != 0)
                    Matrix.rotateM(tmpMatrix, 0, rotationY, 0.0f, 1.0f, 0.0f);
            if (rotationZ != 0)
                    Matrix.rotateM(tmpMatrix, 0, rotationZ, 0.0f, 0.0f, 1.0f);

            Matrix.multiplyMM(resMatrix, 0, tmpMatrix, 0, mModelMatrix, 0);
            System.arraycopy(resMatrix, 0, mModelMatrix, 0, 16);

            // scale down
            Matrix.setIdentityM(tmpMatrix, 0);
            Matrix.scaleM(tmpMatrix, 0, r * s, r * s, r * s);
            Matrix.multiplyMM(resMatrix, 0, tmpMatrix, 0, mModelMatrix, 0);
            System.arraycopy(resMatrix, 0, mModelMatrix, 0, 16);

*
             * Set the camera position (View matrix)
             */
            Matrix.setLookAtM(mViewMatrix, offset, eyeX, eyeY, eyeZ,
                              centerX, centerY, centerZ, upX, upY, upZ);

            /*
             * combine the model with the view matrix
             */
            Matrix.multiplyMM(mMVMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

            /*
             * this projection matrix is applied to object coordinates in the
             * onDrawFrame() method
             */
            Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, 1, -1,
                           nearPlaneDistance, farPlaneDistance);

            /*
             * Calculate the projection and view transformation
             */
            float[] mMVPMatrix = new float[16];
            Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVMatrix, 0);

            /*
             * all the drawing stuff inside the model-object (otherwise
             * translation/rotation wouldn't affect every object)
             */
            model3d.draw(mMVPMatrix);

I'm also taking care of translating in x,y,z while the model is rotated (e.g. the model is rotated by 90° - the object should still move to the left when I swipe left). This is managed by my onTouchEvent-Helper:
 position.add(touchManager.moveDelta(0).rotate(-angle));

My whole sourcecode is open-source, you could have a look into github.
Question
How can I translate and rotate the camera to a specific point (with specific distance/angle) no matter how my current rotation/position is? Are there any good literatures available? Any good open-source project I could have a look into? Sources on GitHub are really rare...
Should I work with the "lookAt"-Method or do I have to do some kind of translation/rotation of the model? Or should I change my eye and center?
Edit: Lets assume that I don't translate my model by my own (I'll disable the translating by user). I want to look at a specific point p (x,y,z) - no matter how I rotate and scale my model, I always want to look at this point p! - How do I do this? Do I have to translate my model - do I have to change my eye or center?

A: If you want the direction of the camera and the distance from the point to be constant, if you know the angles around y and pitch-roll axis, you can set the 3D-distance (the distance in x, y and z axis) from the scalar distance d:
Vector3 dist   = Vector3 (    d * sin(yawAngle) * fabs(cos(pitchRollAngle)),
                              d * sin(pitchRollAngle),
                              d * cos(yawAngle) * fabs(cos(pitchRollAngle))    );

Where the value of yawAngle can go from -π to π while the value of pitchRollAngle can go from -π / 2.0f to π / 2.0f. So, you can define the eyePt vector as:
Vector3 eyePt  = Vector3 (    pnt.x - dist.x,
                              pnt.y - dist.y,
                              pnt.z - dist.z    );

Where the pnt vector is the position of the point. Then, you set the lookAt vector in this way:
Vector3 lookAt = pnt;

Finally, the up vector is:
Vector3 up     = Vector3 (    0.0f,    1.0f,    0.0f    );

I hope this would help you. And sorry for my poor English.


text:
Q: Strange results while checking the memory layout of a c program using size command in linux When i check the memory layout of following c program, using command size program_name in linux, i get data = 552, bss = 8.
#include <stdio.h>

int main()
{
    return 0;
}

Now, after adding a uninitialized variable, i still get the same result, data = 552, bss = 8. I was expecting bss = 12 here.
#include <stdio.h>
int a;
int main()
{
    return 0;
}

If i add a variable initialized to a value, i get what i expected, data = 556, bss = 12
#include <stdio.h>
int a;
int b = 10;
int main()
{
    return 0;
}

However, if a declare a pointer and make it point to the initialized variable, i get data = 568, bss = 8, which i don't understand why.
(To me, it seems like both pointer and uninitialized variable have been added to initialized list!)
#include <stdio.h>
int a;
int b = 10;
int * c = &b;
int main()
{
    return 0;
}

Can someone please clarify what is happening here?

A: The DATA segment holds all initialized data. It is contained in the executable image. As b is initialized to a specific value it is contained in the DATA (in the image).
The BSS segment holds all unitialized vaiables. It is just a number contained in the image and the loader will allocate the memory for it and initialize it to zero. Thus a is contained in this number (contained as the number of bytes to allocate for it at load time).
c is not initialized to a value that can be placed in the DATA segment. Hence it is contained in the BSS segment, however, at load time, the loader must resolve this address and then initialize c to where b is actually placed in memory.
Note: as a result of this strategy, a and b are not contiguous in memory. This can make debuging memory problems harder. Probably debugging versions of the program will have them contiguous to be able to debug the program.


text:
Q: how to pass a new component for a link text in react? I would like to have a text in react component and one word in this text as a link that will lead to another webiste?
My component looks like this:
import { oneOf, string } from "prop-types"
import * as Styled from "./Banner.styled"

const Banner = ({ variant, size, text }) => (

)

Banner.propTypes = {
  text: string.isRequired,
  variant: oneOf(["complementary", "complementary", "complementary"]),
  size: oneOf(["complementary", "complementary", "complementary"]),
}

Banner.defaultProps = {
  variant: "complementary",
  size: "medium",
}

export default Banner

I am using storybook to show with the component and styled.js to style them,  but my question is, could you please hep me how should I pass to this componett a link?
My text should go like that:
I am learning react, please click this (link) That should be a link to another website.
could you please help me with creating component for  a link?

A: You can use the normal  tag for a link in react too. And then just pass a ReactElement (PropTypes.element) as text (instead of type string), e.g.:
<Banner
   text={<>I am learning react, please click this link</>}
   variant={..}
   size={...}
/>

Note: The <> and </> tags are used to wrap the two Nodes (text and ) into one "container", it won't generate a new HTML element in the DOM.
You will also need to change your proptype:
text: oneOf([PropTypes.string, PropTypes.element]).isRequired,


text:
Q: Why can I access a component variable only from outside the component? I have made a variation of an example app from an Angular book.
A working example (in development mode) can be found here: http://ng-ex.watchduck.net/#/21
The source code can also be found on GitHub.
The component log has the variable autoRefresh. (see here)
export class LogComponent implements OnInit {

  autoRefresh: boolean = false;

  constructor(private changeDetector: ChangeDetectorRef) { }

  ngOnInit() {
    this.changeDetector.detach();  // Here is the problem.
  }

  render() {
    this.changeDetector.reattach();
    this.changeDetector.detectChanges();
    this.changeDetector.detach();
  }
  start() { this.autoRefresh = true; }
  stop() { this.autoRefresh = false; }

}

I would like to use it in the component (in the green box) to show the current status, and to disable two buttons based on it. (see here) But that does not work. No initial value is shown, and then it just sticks with the first value.
<button (click)="start()" [disabled]="autoRefresh">start</button>
<button (click)="stop()" [disabled]="!autoRefresh">stop</button>

But when I place the buttons outside of the component it works. (see here)
<button (click)="viewer.start()" [disabled]="viewer.autoRefresh">start</button>
<button (click)="viewer.stop()" [disabled]="!viewer.autoRefresh">stop</button>

<app-log #viewer [logs]="logs"></app-log>

This is quite counter-intuitive, right? What is going wrong here?

Edit: The problem goes away, when I remove this.changeDetector.detach(); from ngOnInit.
But of course having it there is the point of this exercise.
To clarify: If the disabled attributes were removed, the start and stop button in the component would work fine. What fails is binding the variable autoRefresh to the disabled attributes (as well as using it with ngSwitch or just showing it with {{autoRefresh}}).

A: Obviously you have omitted - before edit - the most important part of the code which is ngoninit in your case....
When you do 'detach'you are simply excludiong current instance of component from angulars change detection cycle.
Because od that, you dont see the effects of setting value of 'autorefresh' as angular doesnt bother to reflect that change.
You effectively almost use onPush detrction strategy by detaching yourself from thr change detector.
When you are placing your buttons outside of the component, the host componemt IS in the change detection cycle therefore you ca see that ui reflects that change.
To verify this, detach the parent component from the change detection ref and you will see exactly the same results


text:
Q: I am building a mongoose aggregate for search mongodb documents I built an aggregate for searching according to a filter. The things that the user can search for are optional, So is there any way to make the match optional - for example the user can select a date, If he didn't select, I want the aggregate function not to use match date
    db.articles.aggregate(
        [ {
            $match : { date : userSelectedDate }, { else : elseSelection}
        } ]
    );

If no date is selected => cancel the date matching and match anothers

A: I would try to build the query document dynamically.
var query = []
if (userSelectedDate){
  query.push({ $match : { date : userSelectedDate }})

db.articles.aggregate(query)

A: The solution was in mongoose documentation using: Aggregate#append(ops)
Appends new operators to this aggregate pipeline
after having the aggregate
    aggregate.append({ $project: { field: 1 }}, { $limit: 2 });

so now I can use if(condition) before appending
mongoose documentation for append


text:
Q: Access controller method from component and/or directive? I have a component that performs a task, but then needs to refresh the data (a method callable from the controller).
Is it possible to access the controller methods and properties from a component?
Is it available through Scope? Parent/root scope?
(Also noticed I'm using a directive as well which would love to access the parent scope)

A: I used $broadcast ... Not sure if that's the proper way to do it or not. I imagine trying to access the controller from component/directive is circular? So maybe $broadcast is what I want?
...For methods it makes sense I guess...But I do feel like I should be able to get a property from the controller. I must be doing something wrong if I can't see the parent scope...

A: You have to set the visibility on the parent then you can inject the parent to the child.  (I'm only on my phone and limited possibilities)  AFAIK SO has a question+answer already.

A: It sounds like you have one controller and one component which is a child element of the controller. In this case you can inject the controller in the component's constructor:
@NgController(...)
class MyController {
  refresh() {
    ...
  }
}

@NgComponent(...)
class MyComponent {
  MyController _myController;

  MyComponent(MyController this._myController);

  doSomething() {
    _myController.refresh();
  }
}

A: Components should basically be reusable and therefore shouldn't have any reference to the calling controller. Here is one solution where two separate controllers use one component to modify controller's property. I'm not sure have I used watch-function properly or is there better way to do this.
Idea comes from this question and answers:
AngularDart components and model binding
edit: ops, sorry: One controller and two different properties.
ang_testi.dart:
import 'package:angular/angular.dart';
import 'package:di/di.dart';

@NgComponent(
 selector: 'my-component'
)
class MyComponent {
  NgModel _ngModel;
  Scope _scope;

  MyComponent(this._ngModel, this._scope){
    _scope.$watch(() => _ngModel.modelValue, (value) => onC(value));
  }

  onC(value){
    if(value!=null) _ngModel.modelValue=value.toUpperCase();

    return _ngModel.modelValue;
  }
}

@NgController(
    selector: '[main-test]',
    publishAs: 'ctrl')
class MainTestController {
  String msg;
  String msg2;
  Scope _scope;
  MainTestController(this._scope){
    _scope.$watch(() => msg, (value) => onMsgC(value));
  }

  onMsgC(value){
    print("msg change:$value");
  }

}

class MyAppModule extends Module {
  MyAppModule() {
    type(MainTestController);
    type(MyComponent);
  }
}

void main() {
  ngBootstrap(module: new MyAppModule());
}

ang_testi.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>ng-model test</title>
    <link rel="stylesheet" href="ang_testi.css">

    <my-component ng-model="ctrl.msg"></my-component>
    <my-component ng-model="ctrl.msg2"></my-component>

<input type="text" ng-model="ctrl.msg">

Hello world from {{ctrl.msg}}!

<input type="text" ng-model="ctrl.msg2">

Hello world from {{ctrl.msg2}}!

A: I'm sorry if I'm polluting this thread.
I found a much simpler way to create a component, which can manipulate data in the calling controller. In the following example the @NgComponent transforms the string from the calling controller to uppercase and preserves a twoway binding.
The key to preserve binding is to use the variable of type: List, Map or Class (I believe also Set and Queue will work). With these types Dart uses "pointers", not values (sorry if the terms are not correct).
The correct type of variable makes also following code work (if you use for example type: String, bindings are not working): https://github.com/angular/angular.dart/issues/264
ang_testi.dart
import 'package:angular/angular.dart';
import 'package:di/di.dart';

@NgComponent(
 selector: 'my-component'
)
class MyComponent {

  List _test;

  @NgTwoWay('test')
  set test(List list){
    _test=list;
  }
  List get test{
    _test[0]=_test[0].toUpperCase();
    return _test;
  }
}

@NgController(
    selector: '[main-test]',
    publishAs: 'ctrl')
class MainTestController {
  List msg=[""];
  List msg2=[""];

}

class MyAppModule extends Module {
  MyAppModule() {
    type(MainTestController);
    type(MyComponent);
  }
}

void main() {
  ngBootstrap(module: new MyAppModule());
}

ang_testi.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>ng-model test</title>
    <link rel="stylesheet" href="ang_testi.css">

    <my-component test="ctrl.msg"></my-component>
    <my-component test="ctrl.msg2"></my-component>

<input type="text" ng-model="ctrl.msg[0]">

Hello world from {{ctrl.msg[0]}}!

<input type="text" ng-model="ctrl.msg2[0]">

Hello world from {{ctrl.msg2[0]}}!


text:
Q: Dockerfile facing issues while implementing in azure devops I have asp.net core project developed in my machine with docker support. The docker file resides in my project.
i.e, its placed outside the modules and under the rootfolder.
This image is working perfectly fine when I run using Visual studio.

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["WebApplication4.csproj", ""]
RUN dotnet restore "./WebApplication4.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "WebApplication4.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApplication4.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication4.dll"]

I have created a pipeline in Azure Devops. and pushed the same code the way it is in my system, to azure git repository. but it fails to at workdir itself.
What is that I am missing here?


text:
Q: Update OverlayEntry on scroll in SingleChildScrollView I am building the custom  dropdown using the OverlayEntry with Positioned inside
 OverlayEntry _createFloatingDropdown() {
    return OverlayEntry(builder: (context) {
      // yPosition = yPosition! + 56 - widget.scrollController.offset;
      return Positioned(
        left: xPosition,
        top: yPosition! + 56,
        width: width,
        height: height,
        child: Container(
          color: Colors.red,
          height: 200,
        ),
      );
    });
  }

This overlay dropdown is inserted onTap of my widget.
return InkWell(
      key: actionkey,
      onTap: () {
        setState(() {
          if (isDropdownOpen) {
            floatingDropdown.remove();
          } else {
            findDropDownData();
            floatingDropdown = _createFloatingDropdown();
            Overlay.of(context)?.insert(floatingDropdown);
          }

          isDropdownOpen = !isDropdownOpen;
        });
      },

The problem is that this InkWell widget is inside of SingleChildScrollView and after rendering the dropdown overlay its position is not updated on scroll, making my positioned widget fixed on the same position on the screen. How can I notify the overlay dropdown and make it update or rebuild on scroll?

A: I found a solution to add a scroll controller listener and remove and insert again overlay with the correct updated offset, but not sure if it is a good solution.
@override
  void initState() {
    actionkey = LabeledGlobalKey(widget.text);
    widget.scrollController.addListener(_onScroll);
    super.initState();
  }

  void _onScroll() {
    if (isDropdownOpen) {
      setState(() {
        floatingDropdown.remove();
        findDropDownData();
        floatingDropdown = _createFloatingDropdown();

        Overlay.of(context)?.insert(floatingDropdown);
      });
    }
  }


text:
Q: Windows Authentication using Apache CFX wsdl2java I am trying to use Apache CFX wsdl2java command on Mac OSX.
I have run this command ./wsdl2java .
The error I get is the following:  WSDLToJava Error: org.apache.cxf.wsdl11.WSDLRuntimeException: Fail to create wsdl definition from :
Caused by : WSDLException: faultCode=PARSER_ERROR: Problem parsing ''.: java.io.IOException: Server returned HTTP response code: 401 for URL:
I believe the reason I get this error is because it requires Windows Authentication.  I have tried to search on how to do this, but I have had no luck so far.
I would be extremely thankful for any help or ideas on this topic.
Thanks ahead of time.

A: If Axis 1.3, you can try
wsdl2java -uri http://user:pass@myapp.example.com/service/myService.wsdl
If Axis 1.4+ you can try
wsdl2java -http-proxy-user user -http-proxy-password pass -uri http://myapp.example.com/service/myService.wsdl

A: Use singleWsdl rather than wsdl, save it and reference the local copy in command parameters.
use abc/service/myService.singleWsdl rather than abc/service/myService.wsdl


text:
Q: ReadExisting() in Serial Port throws I/O exception We are reading Data from the SerialPort in .Net 2.0. But before reading we make sure that there is nothing in the Serial Port. So we are waiting until the serial Port In-Buffer is Empty.
Here is the Code:
SerialCommunicationPort.SerialPort.BaudRate = 300;
SerialCommunicationPort.SerialPort.Parity = Parity.None;
SerialCommunicationPort.SerialPort.StopBits = 1;
SerialCommunicationPort.SerialPort.DataBits = 7;
SerialCommunicationPort.SerialPort.ReadTimeout = 1;
SerialCommunicationPort.SerialPort.RtsEnable = true;
SerialCommunicationPort.SerialPort.DtrEnable = true;
SerialCommunicationPort.SerialPort.WriteTimeout = 1500;

do
{
    strTempRecv = SerialCommunicationPort.SerialPort.ReadExisting();
    if (string.IsNullOrEmpty(strTempRecv))
    {
        Thread.Sleep(100);
        intTimeOut++;
    }
    else
    {
        intTimeOut = 0;
    }
} while (intTimeOut < 50);

If the external device is sending data to the serial port at some Baud rate say 4800, our application is receiving that at 300. After some time the Do-While loop above throws this IO Exception:
System.IO.IOException: The I/O operation has been aborted because of either a thread exit or an application request.

   at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   at System.IO.Ports.SerialStream.BeginReadCore(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stateObject)
   at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count, Int32 timeout)
   at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count)
   at System.IO.Ports.SerialPort.ReadExisting()


text:
Q: How to get the list of values of scipy.ndimage gaussian_filter? I'm trying to get a list of values when I use a gaussian_filter.
I read a file with a column and float values. Example:
0.8457
0.0
0.505
etc...

My script is this:
#!/usr/bin/env python
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d

with open("file.txt") as f:
     m1 = map(float,f)

wt=np.array(m1).astype(np.float64)
wtsmoothed = gaussian_filter1d(wt, sigma=500)
result=np.count_nonzero(wtsmoothed)
print (result)

I want to get the list of values of the line dark red.

A: the problem is solved with:
for i in range(0,len(result)):
    print(result[i])


text:
Q: Is there a better way to make this function return true as expected I have a JS logic that I am trying to implement, and now pondering why it is not working: I have two arrays with at least one similar element in them, but implementing the logic returned false - but I was expecting the opposite result. Please take a look:
 const array_one = [
  "Apparel",
  "Footwear",
];

const array_two = [
  "Soap",
  "Footwear",
];

const checkArray = (arr1, arr2) => {
    if (arr1.length !== arr2.length) {
      return false;
    } else {
      for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
          return false;
        }
      }
    }
    return true;
  };

  console.log(checkArray(array_one, array_two)); //logs false to the console, was expecting 'true'.

A: *

*Using some method to check if any value from one array exists in another array:

const array_one = [ "Apparel", "Footwear", ]; const array_two = [ "Soap", "Footwear", ];
const checkArray = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false;
  } else {
    return arr1.some(value => arr2.includes(value));
  }
};

console.log(checkArray(array_one, array_two)); //true

*Using filter method:

const array_one = [ "Apparel", "Footwear", ]; const array_two = [ "Soap", "Footwear", ];
const checkArray = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false;
  } else {
    return arr1.filter(value => arr2.includes(value)).length > 0;
  }
};

console.log(checkArray(array_one, array_two)); //true

*Using the some method with the Set which is more performant since it has an average time complexity of O(n) for the has method, and does not require iterating through the entire array.

const array_one = [ "Apparel", "Footwear", ]; const array_two = [ "Soap", "Footwear", ];

const checkArray = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false;
  } else {
    const set = new Set(arr2);
    return arr1.some(value => set.has(value));
  }
};

console.log(checkArray(array_one, array_two)); //true

*Using the reduce method:

const array_one = [ "Apparel", "Footwear", ]; const array_two = [ "Soap", "Footwear", ];

const checkArray = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false;
  } else {
    return arr1.reduce((accumulator, value) => accumulator || arr2.includes(value), false);
  }
};

console.log(checkArray(array_one, array_two)); //true

Note: methods 1. filter and 2. reduce are less performant , since they create new arrays, accumulate values, which can be memory-intensive and slow for larger arrays.

A: Just flip your logic around.

*

*Make false the default assumption

*Create a Set for each input Array for O(1) lookup

*Check if the current item in the set exists in the other and immediately return true

const
  array_one   = [ "Apparel" , "Footwear" ],
  array_two   = [ "Soap"    , "Footwear" ],
  array_three = [ "Apple"   , "Orange"   ];

const checkArray = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false; // lengths must match
  }
  const
    set1 = new Set(arr1),
    set2 = new Set(arr2);
  for (const [value] of set1.entries()) {
    if (set2.has(value)) {
      return true; // short-circuit with true
    }
  }
  return false; // default assumption
};

console.log(checkArray(array_one, array_two));   // true
console.log(checkArray(array_one, array_three)); // false

If you think Set is overkill, you can always use Array.prototype.includes:

const
  array_one   = [ "Apparel" , "Footwear" ],
  array_two   = [ "Soap"    , "Footwear" ],
  array_three = [ "Apple"   , "Orange"   ];

const checkArray = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false; // lengths must match
  }
  for (let i = 0; i < arr1.length; i++) {
    if (arr2.includes(arr1[i])) {
      return true; // short-circuit with true
    }
  };
  return false; // default assumption
};

console.log(checkArray(array_one, array_two));   // true
console.log(checkArray(array_one, array_three)); // false


text:
Q: Accessing Jhipster Principal in ngOnInit First let me say thank you to all the JHispter developers and also that this project is amazing.
I have a Jhipster 4.14.0 microservices app that uses JWT.
I am trying to replace the menu with one from PrimeNG.
This works fine, but I need to access
principal.isAuthenticated()

and
principal.hasAnyAuthority(['ROLE_ADMIN'])

from ngOnInit or another way to load the menu data.  This always returns false.  I tried some other lifecycle methods and principal.isAuthenticated() eventually returns true after quite a few calls.
ngAfterContentChecked() {
    console.log('ngAfterContentChecked');
    console.log(this.principal.isAuthenticated());
}

This works fine when I use isAuthenticated from html
<div>{{isAuthenticated()}}</div>

,but I want to control the menu by creating a menu model in the component, but I cannot figure out how to load it correctly.
if(!this.isAuthenticated()) {
  this.model.push({ label: 'Sign in', icon: 'fa fa-fw fa-sign-in', command: (onclick)=> {this.login()} });
} else {
  this.model.push({ label: 'Sign out', icon: 'fa fa-fw fa-sign-in', command: (onclick)=> {this.logout()} });
}

I also tried adding the following to ngOnInit in NavbarComponent.ts
    this.principal.identity().then((account) => {
        this.currentAccount = account;
    });

,but I get this error in the chrome console.
core.js?593e:1440 ERROR TypeError: _this.connectedPromise is not a function
    at eval (tracker.service.ts?aa77:50)
    at eval (webstomp.js?afe9:292)
    at Array.forEach (<anonymous>)
    at SockJS.ws.onmessage (webstomp.js?afe9:284)
    at SockJS.EventTarget.dispatchEvent (eventtarget.js?d62b:51)
    at eval (main.js?8e93:274)
    at Array.forEach (<anonymous>)
    at SockJS._transportMessage (main.js?8e93:272)
    at WebSocketTransport.EventEmitter.emit (emitter.js?a8c1:50)
    at WebSocketTransport.ws.onmessage [as __zone_symbol__ON_PROPERTYmessage] (websocket.js?a354:35)
defaultErrorLogger @ core.js?593e:1440
ErrorHandler.handleError @ core.js?593e:1501
next @ core.js?593e:5481
schedulerFn @ core.js?593e:4319
SafeSubscriber.__tryOrUnsub @ Subscriber.js?3959:240
SafeSubscriber.next @ Subscriber.js?3959:187
Subscriber._next @ Subscriber.js?3959:128
Subscriber.next @ Subscriber.js?3959:92
Subject.next @ Subject.js?8398:56
EventEmitter.emit @ core.js?593e:4299
(anonymous) @ core.js?593e:4755
ZoneDelegate.invoke @ zone.js?6524:388
Zone.run @ zone.js?6524:138
NgZone.runOutsideAngular @ core.js?593e:4681
onHandleError @ core.js?593e:4755
ZoneDelegate.handleError @ zone.js?6524:392
Zone.runTask @ zone.js?6524:191
ZoneTask.invokeTask @ zone.js?6524:495
invokeTask @ zone.js?6524:1536
globalZoneAwareCallback @ zone.js?6524:1562

Any advice would be greatly appreciated on how to get the menu to load correctly based on authentication or roles when the app first loads.  The menu works fine, otherwise.

A: I was also wondering if this would work in a production build.  The setTimeout method did not wait in the production build.
ngOnInit() {
  setTimeout(() => {
    this.loadMenu();
  }, 0);
}

The only thing I have been able to get to work so far is using setInterval in ngOninit.  I keep polling to see if a user is authenticated and then load the menu and clear the interval.
    ngOnInit() {

      /**
       * This will load the menu, but only show items that do not require login
       * because the principal is not valued yet.
       */
      this.loadMenu();

      /**
       * This interval will run until the user is authenticated and then will reload the menu and clear the interval.
       */
      this.intervalId = setInterval(() => {
          if(this.isAuthenticated()) {
              this.loadMenu();
              clearInterval(this.intervalId);
          }
      }, 100);
    }

This seems like a hack to me and I feel there must be a better way.  Maybe create a menu service that observes the principal?  If anyone has any I ideas please let me know.

A: I did this in navbar.component.ts:
ngOnInit() {
    this.registerAuthenticationSuccess();
  }

  registerAuthenticationSuccess() {
    this.eventManager.subscribe('authenticationSuccess', (message) => {
      this.getAccount();
    });
  }

  getAccount() {
    this.principal.identity().then((account) => {
      this.account = account;
    });
  }


text:
Q: How can I change the app url for unit testing? I have a function which requires the url to be able to work. I am trying to unit test it as its behaviour changes depending on the url query parameters.
MyServiceTest.php
function testMyTestFunction() {
    $service = new MyService();

    // Some how change the url for the app. This doesn't work
    config(['app.url' => 'http://test.test?myNewParam=5']);

    $service->test();
}

MyService.php
function test() {
    // Does not contain `myNewParam`
    $url = url()->full();

    // do some logic
}

I've also tried mocking the request as that's what the url() helper function references but I've had no luck in doing this successfully.

A: When you use url()->full(); this returns the current request full URL, not the one set in the config. So when using this:
config(['app.url' => 'http://test.test?myNewParam=5']);

then you can get the value like this: config('app.url').
If you want to get the param through the url helper then you will need to make a request to the controller route that uses your service, for example:
$this->get('/test?myNewParam=5')->assert...

but then that would not be a unit test. You should better move out the usage of your url helper function from within your service method and provide that as a dependency to the service. That way you can use one url for your production code and another for your test code.


text:
Q: Display an image even after the user has closed the app How do I load the same picture the user has selected even after the user closes the app?
I currently have the following code which I call in onCreate, but the Bitmap is null every time the user closes the app.
 private void loadImageFromStorage() {

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        File myPath = new File(directory,"profile.jpg");

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(myPath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            File f = new File(directory.getAbsolutePath(), "profile.jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView coverView = findViewById(R.id.cover_view);
            coverView.setImageBitmap(b);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

A: Assuming the image was actually saved as profile.jpg and it exists in the imageDir folder, all you need to do to load the image (based on your current usage) is:
private void loadImageFromStorage() {

    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    File myFile = new File(directory.getAbsolutePath(),"profile.jpg");

    if(myFile.exists()){
        try {
            Bitmap b = BitmapFactory.decodeFile(myFile.getAbsolutePath());
            ImageView coverView = findViewById(R.id.cover_view);
            coverView.setImageBitmap(b);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        Log.d("MyApp", "The image file does not exist.");
    }

}

But if the image is not yet saved or non-existence, then you may need to ask another question that details how you are currently doing it. But this setup will allow you know if that image actually existts.


text:
Q: Show byte stream image asp.net mvc public static string GetAvatar()
{
    logger.Info("Start--GetAvatar");//aatif
   // string headerText = "Bearer " + token;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mxit.com/user/public/avatar/id");
    //request.Method = method;
    //request.Headers.Add(HttpRequestHeader.Authorization, headerText);
    //if (contentType != null)
    //{
    //    request.ContentType = contentType;
    //}

    string method = "GET";
    if (method == "GET")
    {
        try
        {
            WebResponse response = request.GetResponse(); // Byte Stream
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            string JsonGET = responseFromServer.ToString();

           // Avatar res = JsonConvert.DeserializeObject<Avatar>(JsonGET);
            reader.Close();
            dataStream.Close();
            response.Close();
            logger.Info("End--GetAvatar");//aatif
            return JsonGET;
        }

        catch (Exception ex)
        {

            logger.Error("CacheData.GetAvatar():" + ex.StackTrace);   /// Aatif

        }
    }
    logger.Info("End--GetAvatar"); ///aatif
    return null;
}

 string avatar = MURLEngine.GetAvatar();

Showing Image in front end:

How do i show the byte stream image on the front end? I am unable to do so right now.

A: You're close. Convert to base64.
(The other answers don't directly relate to your need for a WebRequest.)
public static string GetAvatar()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mxit.com/user/public/avatar/vini.katyal");

    WebResponse response = request.GetResponse();
    Stream responseStream = response.GetResponseStream();
    MemoryStream ms = new MemoryStream();

    responseStream.CopyTo(ms);

    byte[] buffer = ms.ToArray();

    string result = Convert.ToBase64String(buffer);

    response.Close();
    responseStream.Close();

    return result;
}

A: I suggest you create a GET method in your controller which accepts an id of your row or something. Based on that just fetch the byte array and send it back to the as an contentresult. Here is an example for that:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Image(int id)
{
    byte[] byteArray = _imageRepository.GetImage(id);
    return new FileContentResult(byteArray, "image/jpeg");
}

In the view you can call this controller method in following way:

A: Try to use Convert class methods. You can make use of Convert.ToBase64String method to convert a byte array to base64 string representation of the image.
Example from MSDN:
try {
      inFile = new System.IO.FileStream(inputFileName,
                                System.IO.FileMode.Open,
                                System.IO.FileAccess.Read);
      binaryData = new Byte[inFile.Length];
      long bytesRead = inFile.Read(binaryData, 0,
                           (int)inFile.Length);
      inFile.Close();
   }
   catch (System.Exception exp) {
      // Error creating stream or reading from it.
      System.Console.WriteLine("{0}", exp.Message);
      return;
   }

   // Convert the binary input into Base64 UUEncoded output.
   string base64String;
   try {
       base64String =
         System.Convert.ToBase64String(binaryData,
                                0,
                                binaryData.Length);
   }
   catch (System.ArgumentNullException) {
      System.Console.WriteLine("Binary data array is null.");
      return;
   }

Here is another example that I found.

A: I solved the issue:
            WebResponse response = request.GetResponse();

            byte[] b = null;
            using (Stream stream = response.GetResponseStream())
            using (MemoryStream ms = new MemoryStream())
            {
                int count = 0;
                do
                {
                    byte[] buf = new byte[1024];
                    count = stream.Read(buf, 0, 1024);
                    ms.Write(buf, 0, count);
                } while (stream.CanRead && count > 0);
                b = ms.ToArray();
            }

            return Convert.ToBase64String(b);

I firstly convert the response to Stream and then to Byte array then to the base64 string


text:
Q: backbone layout manager: how to remove child views How to clean up the children view when the parent view is removed. There are some cleanup activities involved in the child view. when I call the remove parent view there is no hook to remove the child view.

A: add the close function to your parent view (it: it was good if all children extends parent view or all your views extends a gad view, and the close function is inside the gad view )
close: function() {
  var err, i, view, _ref1;

  try {
    _ref1 = this.childViews;
    for (i in _ref1) {
      view = _ref1[i];
      if (typeof view.close === "function") {
        view.close();
      }
    }
    this.unbind();
    this.stopListening();
    this.undelegateEvents();
    return this.$el.empty();
  } catch (_error) {
    err = _error;
    throw new Error(err);
  }
}


text:
Q: SQLAlchemy: AmbiguousForeignKeysError double reference to parent I have the following simplified code for Groups that can have subgroups with roles:
from sqlalchemy import (
    CheckConstraint,
    Column,
    ForeignKey,
    PrimaryKeyConstraint,
    String,
    create_engine,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()

class Group(Base):
    __tablename__ = 'groups'
    name = Column(String, primary_key=True)
    group_roles = relationship('GroupRole', back_populates='group')

class GroupRole(Base):
    __tablename__ = 'group_roles'
    name = Column(String, ForeignKey(Group.name))
    group_name = Column(String, ForeignKey(Group.name))
    role = Column(String, nullable=False)
    __table_args__ = (
        CheckConstraint('name != group_name'),
        PrimaryKeyConstraint('name', 'group_name'),
    )
    group = relationship(Group,
                         foreign_keys=[name],
                         back_populates='group_roles')

engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
session.add(Group(name='test'))

When I run this, I get sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Group.group_roles - there are multiple foreign key path
s linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
I have also tried adding the following below the GroupRole table in lieu of the corresponding line already defined in Group:
Group.group_roles = relationship('GroupRole', foreign_keys=[Column(String, ForeignKey(GroupRole.name))], back_populates='group')

But I get the same error, and it doesn't look like others have had to do this. What am I doing wrong? How can I get my GroupRole table to reference my Group table? I'm using SQLAlchemy 1.3 and python 3.7.

A: You can make the code work with only backref on the GroupRole.group relationship, such as:
class Group(Base):
    __tablename__ = 'groups'
    name = Column(String, primary_key=True)

class GroupRole(Base):
    __tablename__ = 'group_roles'
    name = Column(String, ForeignKey(Group.name))
    group_name = Column(String, ForeignKey(Group.name))
    role = Column(String, nullable=False)
    __table_args__ = (
        CheckConstraint('name != group_name'),
        PrimaryKeyConstraint('name', 'group_name'),
    )
    group = relationship(Group,
                         foreign_keys=[name],
                         backref='group_roles')

Not sure this is what is intended though, but working:
g = Group(name='test', group_roles=[
    GroupRole(group_name='testrole', name='test', role='testrole'),
    GroupRole(group_name='testrole2', name='test', role='testrole2')
])
session.add(g)


text:
Q: creating a git diff to include all source files in repo Let me give the context first before explaining the requirement. We want to post a review on the reviewboard server with all source files in the repo. the reason is that we want to do some security related review on all the files and want to record the comments before fixing the issues. Reviewboard can upload the diffs. So if I can create a review with all source files being shown in diff format, this might work with reviewboard.
Can anybody tell me a good way to generate this kind of diff? Alternatively, can anyone suggest a good method to achieve the end goal?

A: You could create a commit (on a branch) that deletes every file in the repository. That would create a diff with negative lines for every existing line. It wouldn't be that hard:
$ cd my_repo
$ git checkout -b delete_everything
$ git rm -r .
$ git commit -m "Remove every file"

You could similarly then revert that commit, creating another commit with positive lines for every existing line.
$ git revert -n HEAD
$ git commit -m "Re-add every file"

Either of these could work for loading into Review Board.


text:
Q: In php: dropdownlist values depend on another drop down list in the same form How can I realize this solution?
dropdownlist values depend on another dropdownlist in the same form
e.g. :a form contains dropdownlist(car_name),dropdownlist (models of this car),button(search)
notice that :
1)car_model values depend on car_name value
2)car_name dropdownlist and car_model dropdownlist in the same form
thanks
Best Regards.

A: <form>
<select id="car_name">
    <option value="car1">Car 1</option>
    <option value="car2">Car 2</option>
    <option value="car3">Car 3</option>
</select>
<select id="car_model">
</select>
</form>
<script type="text/javascript">
// Maps all available car models
var modelMap = {
    'car1': [
        // Each entry contains the model's ID and text/label.
        ['car1-1', 'Car 1.1'],
        ['car1-2', 'Car 1.2'],
        ['car1-3', 'Car 1.3']
    ],
    'car2': [
        ['car2-1', 'Car 2.1'],
        ['car2-3', 'Car 2.2']
    ],
    'car3': [
        ['car3-1', 'Car 3.1'],
        ['car3-2', 'Car 3.2'],
        ['car3-3', 'Car 3.3'],
        ['car3-4', 'Car 3.4'],
        ['car3-5', 'Car 3.5']
    ]
};

// Get the dropdown list elements.
var nameList = document.getElementById('car_name');
var modelList = document.getElementById('car_model');

// Function to be called when the car name is changed
nameList.onchange = function() {
    // Get the selected car.
    var selectedName = nameList.options[nameList.options.selectedIndex].value;
    // Lookup available models in the map.
    var availModels = modelMap[selectedName] || [];

    var i, opt;

    // Set available models in the model dropdown.
    for (i = 0; i < availModels.length; ++i) {
        opt = availModels[i];
        modelList.options[i] = new Option(opt[0], opt[1]);
    }

    // Remove all old options if the new car has fewer models than a previous selection.
    for (; i < modelList.options.length; ++i) {
        modelList.options[i] = null;
    }
};
</script>

A: <form> <select id="car_name">
    <option value="car1">Car 1</option>
    <option value="car2">Car 2</option>
    <option value="car3">Car 3</option> </select> <select id="car_model"> </select> </form> <script type="text/javascript"> // Maps all available car models var modelMap = {
    'car1': [
        // Each entry contains the model's ID and text/label.
        ['car1-1', 'Car 1.1'],
        ['car1-2', 'Car 1.2'],
        ['car1-3', 'Car 1.3']
    ],
    'car2': [
        ['car2-1', 'Car 2.1'],
        ['car2-3', 'Car 2.2']
    ],
    'car3': [
        ['car3-1', 'Car 3.1'],
        ['car3-2', 'Car 3.2'],
        ['car3-3', 'Car 3.3'],
        ['car3-4', 'Car 3.4'],
        ['car3-5', 'Car 3.5']
    ] };

// Get the dropdown list elements.
var nameList = document.getElementById('car_name');
var modelList = document.getElementById('car_model');

// Function to be called when the car name is changed
nameList.onchange = function() {
    // Get the selected car.
    var selectedName = nameList.options[nameList.options.selectedIndex].value;
    // Lookup available models in the map.
    var availModels = modelMap[selectedName] || [];

    var i, opt;

    // Set available models in the model dropdown.
    for (i = 0; i < availModels.length; ++i) {
        opt = availModels[i];
        modelList.options[i] = new Option(opt[0], opt[1]);
    }

    // Remove all old options if the new car has fewer models than a previous selection.
    for (; i < modelList.options.length; ++i) {
        modelList.options[i] = null;
    } }; </script>

This is correct, but the "modelList" length property needs to be reset to zero. So like this.
 for (; i < modelList.options.length; ++i) {
     modelList.options[i] = null;
     modelList.length = 0;
 } }; </script>

A: Here correct code which remove missing model for car list:
<form>
<select id="car_name">
<option value="car1">Car 1</option>
<option value="car2">Car 2</option>
<option value="car3">Car 3</option>
</select>
<select id="car_model">
</select>
</form>
<script type="text/javascript">
// Maps all available car models
var modelMap = {
'car1': [
    // Each entry contains the model's ID and text/label.
    ['car1-1', 'Car 1.1'],
    ['car1-2', 'Car 1.2'],
    ['car1-3', 'Car 1.3']
],
'car2': [
    ['car2-1', 'Car 2.1'],
    ['car2-3', 'Car 2.2']
],
'car3': [
    ['car3-1', 'Car 3.1'],
    ['car3-2', 'Car 3.2'],
    ['car3-3', 'Car 3.3'],
    ['car3-4', 'Car 3.4'],
    ['car3-5', 'Car 3.5']
]
};

// Get the dropdown list elements.
var nameList = document.getElementById('car_name');
var modelList = document.getElementById('car_model');

// Function to be called when the car name is changed
nameList.onchange = function() {

// Remove all old options if the new car has fewer models than a previous selection.
for(i=modelList.options.length-1;i>=0;i--)
{
    modelList.remove(i);
}

// Get the selected car.
var selectedName = nameList.options[nameList.options.selectedIndex].value;
// Lookup available models in the map.
var availModels = modelMap[selectedName] || [];

var i, opt;

// Set available models in the model dropdown.
for (i = 0; i < availModels.length; ++i) {
    opt = availModels[i];
    modelList.options[i] = new Option(opt[0], opt[1]);
}

};
</script>


text:
Q: Dronekit python vehicle connect timeout I am trying to run a helloworld.py using dronekit on my solo drone.
My environment is
dronekit==2.7.0
pymavlink>=2.0.0

When I try to run the simple helloworld example the vehicle.connect() timesout.
ERROR LOADING MAVNATIVE - falling back to python implementation
Connecting to udpin:0.0.0.0:14550...
>>> Link timeout, no heartbeat in last 5 seconds
>>> No heartbeat in 30 seconds, aborting.
Traceback (most recent call last):
  File "/log/solo-script/helloworld.py", line 9, in <module>
    vehicle = connect("0.0.0.0:14550", wait_ready=True, baud=57600, heartbeat_timeout=30)
  File "/log/solo-script/env/lib/python2.7/site-packages/dronekit/__init__.py", line 2787, in connect
    vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout)
  File "/log/solo-script/env/lib/python2.7/site-packages/dronekit/__init__.py", line 2060, in initialize
    raise APIException('Timeout in initializing connection.')
dronekit.APIException: Timeout in initializing connection.

I have tried downgrading pymavlink to 1.1.73 as well, but did not work. Any help is much appreciated.

A: I had the same problem.After downgrading pymavlink also build older version of dronekit. I used 2.0.0 and its worked.Here is a link for dronekit versions: https://github.com/dronekit/dronekit-python/releases

A: Make sure you are using python2. Dronekit uses pymavlink and dronekit code have been changed to python3 but pymavlink has given me a lot of issues in python3 and it works fine in python2.
It looks like an issue in vehicle.initialize method however try to set wait_ready=False, If it works then your solo it's not sending the parameters that dronekit is expecting:
 # Default parameters when calling wait_ready() or wait_ready(True).
 self._default_ready_attrs = ['parameters', 'gps_0', 'armed', 'mode', 'attitude']

Try updating your solo firmware and getting the latest dronekit and pymavlink versions from their git repo.


text:
Q: How can I create a gradient shadowMap in threejs? I want to show a shadowMap of a model that the center shadow is darker and the edge  is light(or thin),how can I set the properties?

A: soft shadow map is the thing you are looking for.. just add
renderer.shadowMapType = THREE.PCFSoftShadowMap;

before that remember to cast and receive shadows for the meshes/objects and  enable shadow map by adding
renderer.shadowMap.enabled=true
good luck...