text:
Q: Wrote a program to view binary data. Did I do this correctly or am I getting junk data? My assignment this week is to go create a program that reads a data file that my professor sent to me. The assignment says there are 10 integers in this data that I need to write to an array, which I've done but I'm not sure if it's correct or just junk data. I will attach the a DL link for this file (it's only 40bytes). I've created a program below that will read off the 10 numbers that I need, but how do I know if it is junk data or the real deal. I am getting the same numbers everytime, is that an indication that I'm doing this correctly? Any long term tips for me to use in the future would be appreciated as well.
Here is the DL link
mysteryData
#include <stdio.h>
#include <string.h>

int main(void)
{
  int i;

  FILE* myFile = NULL;

  myFile = fopen("mysteryData.dat", "rb");

  int Mystery[10] =
  { '\0' };

  if (myFile == NULL )
  {
    printf("Failed to open file\n");
  }
  else
  {
    fread(Mystery, sizeof(int), sizeof(Mystery), myFile);

    printf("%d\n", Mystery);
  }

  for (i = 0; i < 9; i++)
  {
    printf("%d\n", Mystery[i]);
  }
  fclose(myFile);
}

A: First, if you mean to print the address of Mystery after the fread call, you should use %p. Second, perhaps printing in hex will help you see the problem:
% echo $'\x12\x34\x56\x78\x9a\xbc\xde\xff' > mysteryData.dat
% ./test
0x7fff598cfae0 # %p
78563412       # %x
ffdebc9a
a # newline = 0x0a
0
0
0
0
0
0
%

The values are being strung together in the integers, and are bytewise-reversed.  They are being strung together because you are reading them as integers:
12 34 56 78 9a bc de ff a0 00 00 00
^---------^ ^---------^ ^---------^

From this we see that ints in my compiler are 32 bits (4 bytes). Furthermore, the reason the bytes are swapped is because my system is little-endian; that means that the 12 is the least significant 8 bits, 34 is the next most significant, etc.
You probably want to access these as individual bytes, for which you should change Mystery to a char[10]. And maybe make it bigger to ensure you have enough space. Finally, you want to check the return value of fread, which will tell you how many bytes you have actually read.

Fread is declared thusly:
fread(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
                                 ^^^^         ^^^^^^

You are passing the right size, but instead of passing the number of items for nitems, you are passing the size of Mystery, which is nitems*sizeof(int). Use
fread(Mystery, sizeof(int), sizeof(Mystery)/sizeof(int), myFile);

Or better,
fread(Mystery, sizeof(Mystery[0]), sizeof(Mystery)/sizeof(Mystery[0]), myFile);

A: First of all it should specified how these integers are stored into the file.
As the file is 40 bytes and there is a specification that the count of items is 10 you can assume that they are stored as binary data and each integer takes four bytes.
*I say that because the file may be a text file with integers stored as newline separated values:
10
13
4563
-32
etc......
But. In 40 bytes there is no space for 10 integers stored as text, so let's say they are in binary data.
At this point we assume also that the endianess of the data is the same of the architecture your program will be compiled and run. I won't go further on this, for more info you may google for big endian little endian
Finally it should be specified what is the size of an integer. The size of an integer may vary depending on the OS / architecture:
see What does the C++ standard state the size of int, long type to be?
But we have 40 bytes, we know we have 10 ints. Into the file the int is 4 bytes for each number.
You may check if that match with your architecture with:
printf("Here ints are %d bytes.\n", (int) sizeof(int));

and looking at the output.
Going back to your code thare are some things to be adjusted. See the comments...
#include <stdio.h>
#include <string.h>

int main (void)
{
    int i;

    int itemsRead; // we'll use that later...

    FILE* myFile=NULL;

    myFile=fopen("mysteryData.dat", "rb");

    int *Mystery = malloc (sizeof(int) * 10); // It's a better practice...
    //... to allocate the buffers/arrays you need instead of declaring them
    // statically. If your file grows up with millions of numbers your code
    // will still be scalable.

    if(!Mystery) // Just check the alloc succeeded
    {
        printf("Failed to allocate buffer\n");
    }

    if(myFile==NULL)
    {
        printf("Failed to open file\n");
        free( Mystery ); // Free the buffer
        return 0;        // Quit
    }

    itemsRead = fread(Mystery, sizeof(int), 10, myFile);
    // 2nd parameter is size of element
    // 3rd parameter is how many items
    // the function returns the items actually read

    // What is the file was shorter than expected?
    // Check we were able to actually read 10 items of 4 bytes each

    if( itemsRead < 10 )
    {
        printf("The file ended unexpectedly\n");
        free( Mystery ); // Free the buffer
        return 0;        // Quit
    }

    for (i=0; i<10; i++) // 10 Items: count from 0 to 9 so until i<10
    {
        printf("%d\n", Mystery[i]);
    }

    free( Mystery  );
    fclose( myFile );
}


text:
Q: Routing to user detail inside a map I'm trying to route a normal user to his detail page
I've tried to route inside a map but I guess I'm doing it wrong

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Router } from '@angular/router';
import { AuthFacade } from 'libs/client/ngrx/src/lib/auth/+state/auth.facade';
import { Subscription, Observable, observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '@trilog/types';

@Component({
  selector: 'a-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
  form: FormGroup;

  user$: Observable<User> = this.authFacade.user$;
  isAdmin$: Observable<boolean> = this.user$.pipe(map(user => user && user.roles.some(role => (role.key == 'admin') || (role.key == 'system'))));
  id$: Observable<String> = this.user$.pipe(map(user => user && user._id))

  error$: Observable<any> = this.authFacade.authError$.pipe(map((err: any) => {
    if (err) {
      return err.error ? err.error.message : err.message
    }
  }));

  private authSub: Subscription;

  constructor(
    private http: HttpClient,
    private fb: FormBuilder,
    private router: Router,
    private authFacade: AuthFacade,
  ) {
    this.form = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.authSub = this.authFacade.isAdmin$.subscribe(isAdmin => {

      if (isAdmin) {
        // console.log("Is admin?", isAdmin);
        this.router.navigate(['/']).then(() => console.log('nav done')).catch(err => console.log(err));
      }
      else {
        // this.router.navigate(['/users/', this.id$])
        console.log("Hello")
        return this.user$.pipe(map(user => this.router.navigate(['/users/',user._id])))
        // return this.authFacade.user$.pipe(map(user => user && this.router.navigate(['/users/',user._id])))
      //  return this.user$.pipe(map(user => user && this.router.navigate(['/users/',user._id])))
      }
    });
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    if (this.authSub) { this.authSub.unsubscribe(); }
  }

  login() {
    if (this.form.valid) {
      this.authFacade.login(this.form.value);
    }

  }

}

Right now when log in as an admin everything works fine, but when i log in as a normal user it should route me to the user's detail page instead all im getting is the "Hello" from console log

A: Used  Vitalii's advice
this.user$.pipe(map(user => this.router.navigate(['/users/',user._id]))).subscribe(..)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sort column names alphabetically before underscore, then sort differently after underscore I have a dataframe and want to sort the columns alphabetically, but only up to a certain point within the name, then the order for each variable has to be changed depending on the suffix, how would this be done?
For example:
a_start <- sample(5)
a_end <- sample(5)
b_start <- sample(5)
b_end <- sample(5)

df <- data.frame(a_end, a_start, b_end, b_start)
df

  a_end a_start b_end b_start
1     1       4     1       5
2     2       2     5       1
3     5       1     3       2
4     4       3     2       4
5     3       5     4       3

If the columns have been sorted alphabetically, we would get the above. So how would I sort the names alphabetically before the underscore, then choose to have start before end like so:
  a_start a_end b_start b_end
1       4     1       5     1
2       2     2       1     5
3       1     5       2     3
4       3     4       4     2
5       5     3       3     4

For such a trivial example, it's easy enough to just sort the columns manually, but if there are hundreds of columns how could it be done?
Edit: Thanks for the replies so far but I've realised this example is not as comprehensive as it could have been. It should contain more than one underscore and sort alphabetically up to the last one, at which point the suffix gets sorted differently.
eg.
col_a_start <- sample(5)
col_a_end <- sample(5)
col_b_start <- sample(5)
col_b_end <- sample(5)

df <- data.frame(col_a_end, col_a_start, col_b_end, col_b_start)

sorted to give:
  col_a_start col_a_end col_b_start col_b_end
1           2         4           4         3
2           3         1           2         1
3           5         5           1         5
4           4         2           5         4
5           1         3           3         2

A: With the column name patterns showed, here is a base R option
df[order(trimws(names(df), whitespace = "_.*"),
    factor(trimws(names(df), whitespace = ".*_"),
      levels = c("start", "end")))]

-output
   a_start a_end b_start b_end
1       1     5       4     5
2       5     3       2     3
3       3     2       3     4
4       4     4       1     2
5       2     1       5     1

A: I've taken a stab at the answer. Basically create a new table with the column names, extract in separate columns the column name components you want to control then arrange the column names in order and lastly add this as argument into the relocate() formula
#assign col names into new tibble
col_names <- tibble(x=df %>% names())

#extract out into new columns name components
col_names_order <- col_names %>%
  mutate(before=str_extract(x,".*(?=_)"),
         after=str_extract(x,"(?<=_).*")
) %>%
  arrange(before,desc(after)) %>%
 pull(x)

#rearrange colnames by this logic
df %>% relocate(col_names_order)


text:
Q: Measure of subsets of profinite groups Let $G$ be an infinite profinite group, so $$G=\lim_{\longleftarrow}G/N$$ where $N$ runs through the open normal subgroups. I have two questions:

*

*Is $G$ of Haar measure zero in the compact group $\prod_NG/N$?

*What is the relation between the Haar measure of a subset $E$ of $G$ and the numbers $\frac{|EN/N|}{|G/N}$, the size of the image of $E$ in $G/N$?

A: 1) The measure of a closed subgroup $H$ of a profinite group $G$ is $\frac{1}{\vert G:H \vert}$. So $G$ has measure zero in $\prod G/N$ if and only if it has infinite index. This way you should be able to show that $G$ always has measure zero in $\prod G/N$.
2) As Yves mentioned, you always have the inequality $\mu(S) \le \inf \frac{\vert NS/N\vert}{\vert G/N \vert}$ for any measurable subset $S$. In fact the right-hand side is the measure of the closure of $S$. If $S$ is closed it is an equality. If $G$ is the profinite completion of an abstract countable group $\Gamma$, then $\mu(\Gamma)=0$, but the closure of $\Gamma$ is $G$.


text:
Q: Return back redirects me to home page in laravel 5.4 So what I'm trying to do is to redirect the user to his previous location whenever a 404 error appears. That means, I want to simply not allow him to reach unexisting http addresses and to return him back instead. I did as follows in the App/Exceptions/Handler.php:
public function render($request, Exception $exception)
{
    if($this->isHttpException($exception))
    {
        switch ($exception->getStatusCode())
        {
            // not found
            case '404':
            return back();
            break;

            default:
                return parent::render($request, $exception);
            break;
        }
    }
    else
    {
        return parent::render($request, $exception);
    }
}

The problem - I'm getting redirected to my home page each time. What could cause it? Thanks in advance!

A: I had the same problem today. I fixed it by removing the following meta tag in the head section.
<meta name="referrer" content="origin">


text:
Q: Select by Attribute Sum Fields Is it possible to sum fields together in the select by attribute tool with a SQL query?
I'm working in ArcMap 10.3.

A: If you are wanting to select features based on 3 fields, if [Field 1] + [Field 2] = [Field 3], you can do a query that says exactly that.  Put field1 + field2 = field3 into the WHERE clause (where field1 etc. are the names of your fields)

Or if you want to check that two fields add up to a specific value, eg if [Field 1] + [Field 2] = 57, again you just enter exactly that into the WHERE clause:
field1 + field2 = 57

Again, field1 etc. refers to your field names, and 57 is the value the values from the two fields need to add up to in order to be selected.


text:
Q: Returning a Future from an akka Mapper My problem is best described by the following (simplified) example:
Given an asynchronous HTTP client which returns Future< JSON > on calls to its get-Method.
Given a link to a resource which in turn contains a link to another resource. How then do I code the following:

*

*perform GET for Resource A

*as soon as that GET has finished, perform GET for Resource B

My specific problem is, how to return a Future from within the Mapper, without resourceB having to be of type Future< Future < JSON > >. Basically, what I'd like to write is the following:
Future< JSON > resourceA = httpClient.get( "http://..." );
Future< JSON > resourceB = resourceA.map( new Mapper< JSON, Future< JSON > >() {
     public JSON apply( JSON resourceARepr )
     {
        return httpClient.get( resourceARepr.getString( "linkToResourceB" ) );
     }
} );

However, that does not compile, because httpClient#get returns a Future, while the Future#map method expects me to pass a mapper which maps from the supplied value  synchronously.
From Promises/A in the JavaScript world I am used to promise handlers being able to return a promise to a value or a value.

A: I just found out the answer to my problem is as simple as using flatMap instead of map. Oops.


text:
Q: How to get "normal" spawning behavior after installing Spigot? My brother in law is running a small server for a few of us to play on. He recently installed Spigot so that we could have a Dynamic Map. However, after he did that, I noticed that spawning behavior (among other things) has changed. I have two questions:

*

*Why does Spigot default to changing spawning behavior? Why not leave it vanilla and have the option to change?

*What are the best settings in the bukkit.yml file that will most closely mimic vanilla spawning? He and I have worked on it, and we've gotten hostile spawns close to normal - they're still a bit high, but better than before when they were maxing out at about 30. Passive mobs, however, are spawning in huge numbers compared to normal - I feel like I'm playing Beta where you can spawn passives just by lighting up grass at night!

A: The first thing to remember is that Spigot's entire reason for existence is to increase the normal server performance.  With this being the main intent server managers would have when installing Spigot the default settings are set to a base "improved" performance level.
To bring your server back to "vanilla like" mob spawning you need to adjust two files.

*

*In your spigot.yml file (in your server root directory) you should check to ensure that the  mob-spawn-range is set to 4 (chunks).
mob-spawn-range: 4
You can disable experience orb and item grouping by setting the merge-radius to zero.
merge-radius: exp: 0 item: 0
At the bottom of this file you can adjust most of these settings on a per world basis.  If you want all worlds to use the same setting you can just remove the entire separate world groupings and just leave the default grouping.

*In your bukkit.yml file (in your server root directory) you need to ensure that the spawn-limits for each type are set as follows:
spawn-limits: monsters: 70 animals: 10 ambient: 15 water-animals: 5
Also within this file you will want to check your ticks-per setting to make sure it is set to 1 for hostiles and 400 for animals (all others).
ticks-per: animal-spawns: 400 monster-spawns: 1

A: Johonn, that number is a variable used in the formula to decide how many mobs can spawn.
The formula is:
value * chunk_count / 256.

*

*value is the spawn limit number from the bukkit.yml

*chunk_count is the number of chunks currently loaded across all worlds

Another piece of information to know is that, by default on a SMP server, there is a 10 x 10 chunk square loaded around each player (you can modify this by changing the view distance in the spigot.yml or, if you're not running spigot, in the server.properties file).
So, with all of this in mind:
If you're alone on the server and in The End (If you're in the Overworld, spawn chunks would also be loaded but they're not since you're in The End.) that means there are 100 chunks loaded. So, plug that in to the formula along with the 70 from the bukkit.yml file and you get:
70 * 100 / 256
which equals, drum roll please....
27.34375

That number look familiar? Bump your spawn limit up to about 250 and you'll get ~70 mobs all by your lonesome. :)
Edit: One last edit, as I was playing around with this on my own Spigot server. Given the case of an Enderman farm in The End, you can also increase gains by increasing the view distance for the server. Instead of 10, you can make it 12, or even max it at 15. This has pretty significant gains on spawn count for minimal impact considering you're in The End where there's basically nothing to render. You will be able to see back to the main island, but only faintly and it's still too far away for mobs to spawn.
Considering a monster limit of 70 and a view distance of 10 will get you ~27 Endermen, changing the view distance to 12 will get you 70 * 144 / 256, or ~39 Endermen. Maxing the view distance at 15 will get you 70 * 225 / 256, or ~61 Endermen.
Of course, if you have a lot of people on your server, this can significantly drag down performance because of all the chunk loading it has to do (unless everyone is close together and it can load the same chunks for everyone).


text:
Q: Exported GeoPackage from R not drawing in ArcMap I am trying to export multiple layers of point data from R as a single GeoPackage. The code works fine (included below), however when I try and load the resulting GeoPackage into ArcMap (10.6) I get the following pop-up:

Followed by this error:

I've not had this issue before when exporting GeoPackages from R and loading them in ArcMap and am not sure what is causing these problems (especially when it loads into QGIS fine). I have tried both writeOGR and st_write to export as a GeoPackage but encounter the same issue with both.
require("raster")
require("sf")

Data1 <- read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", "1RHAqtsPXgD5rH-ppIu7cLblHXyXzv_39"))
Data2 <- read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", "1Mzi6A6L_cXOrT9dTbm8gggGdtNQnZYkY"))
Data3 <- read.csv(sprintf("https://docs.google.com/uc?id=%s&export=download", "1ZzYiFIJxs2Coeb4kBNsWhmiF5NZDUhrL"))

Data1_Coords <- cbind(Easting = as.numeric(as.character(Data1$OSEAST1M)),Northing = as.numeric(as.character(Data1$OSNRTH1M)))
Data2_Coords <- cbind(Easting = as.numeric(as.character(Data2$OSEAST1M)),Northing = as.numeric(as.character(Data2$OSNRTH1M)))
Data3_Coords <- cbind(Easting = as.numeric(as.character(Data3$OSEAST1M)),Northing = as.numeric(as.character(Data3$OSNRTH1M)))

Data1_Points <- SpatialPointsDataFrame(Data1_Coords, data = Data1, proj4string = CRS("+init=epsg:27700"))
Data2_Points <- SpatialPointsDataFrame(Data2_Coords, data = Data2, proj4string = CRS("+init=epsg:27700"))
Data3_Points <- SpatialPointsDataFrame(Data3_Coords, data = Data3, proj4string = CRS("+init=epsg:27700"))

Data1_Points_ST <- st_as_sf(Data1_Points)
Data2_Points_ST <- st_as_sf(Data2_Points)
Data3_Points_ST <- st_as_sf(Data3_Points)

st_write(Data1_Points_ST, "DataGPKG.gpkg", "Data1")
st_write(Data2_Points_ST, "DataGPKG.gpkg", "Data2", update = TRUE)
st_write(Data3_Points_ST, "DataGPKG.gpkg", "Data3", update = TRUE)


text:
Q: Manually Release Postgres LOCK I would like to know if there´s any command to unlock or release a lock made by the same transaction.
Pseudo-code
FUNCTION
    TRANSACTION
        LOOP
            TABLE LOCK
            table operations...
            "TABLE UNLOCK WANTED"
        END
    END OF TRANSACTION
END OF FUNCTION

The function query can take a while as the LOOP might be large, so I would like to be able to unlock before the transaction is fully finished.

A: No, it isn't possible. Locks are held until end of transaction, no exceptions.
Thus, you need to either:

*

*Use a nonstandard lock like an advisory lock, which requires everyone to check for it and respect it; or

*Do your work in transactions that commit autonomously, before the outer transaction is done. In PostgreSQL, lack of autonomous subtransaction support means that you must use dblink for this.


text:
Q: cmake execute_process TIMEOUT uses We have TIMEOUT 3600 used across many execute_process calls.
Some of our slow servers often exceed the timeout and builds fail as expected.
However, this is often causing issues and we keep increasing the timeout intervals.
Now I'm thinking to remove timeout completely.
Is there a reason for using the TIMEOUT option other than failing?
Why should we have TIMEOUT at all (e.g., none of add_custom_target commands has this feature)? Why use it only in execute_process (request is not meant for CTest)?

A: Turning my comment into an answer
Generally speaking I would remove the individual timeouts.
I have a timeout for the complete build process running on a Jenkins server. There it calculates an average over the last builds and you can give a percentage value of how much your build may differ (I use a "Timeout as a percentage of recent non-failing builds" of 400% so only the really hanging tasks will be terminated).


text:
Q: How to write a testthat unit test for a function that returns a data frame I am writing a script that ultimately returns a data frame. My question is around if there are any good practices on how to use a unit test package to make sure that the data frame that is returned is correct. (I'm a beginning R programmer, plus new to the concept of unit testing)
My script effectively looks like the following:
# initialize data frame
df.out <- data.frame(...)

# function set
function1 <- function(x) {...}
function2 <- function(x) {...}

# do something to this data frame
df.out$new.column <- function1(df.out)

# do something else
df.out$other.new.column <- function2(df.out)

# etc ....

... and I ultimately end up with a data frame with many new columns. However, what is the best approach to test that the data frame that is produced is what is anticipated, using unit tests?
So far I have created unit tests that check the results of each function, but I want to make sure that running all of these together produces what is intended. I've looked at Hadley Wickham's page on testing but can't see anything obvious regarding what to do when returning data frames.
My thoughts to date are:

*

*Create an expected data frame by hand

*Check that the output equals this data frame, using expect_that or similar

Any thoughts / pointers on where to look for guidance? My Google-fu has let me down considerably on this one to date.

A: Your intuition seems correct. Construct a data.frame manually based on the expected output of the function and then compare that against the function's output.
# manually created data
dat <- iris[1:5, c("Species", "Sepal.Length")]

# function
myfun <- function(row, col, data) {
    data[row, col]
}

# result of applying function
outdat <- myfun(1:5, c("Species", "Sepal.Length"), iris)

# two versions of the same test
expect_true(identical(dat, outdat))
expect_identical(dat, outdat)

If your data.frame may not be identical, you could also run tests in parts of the data.frame, including:

*

*dim(outdat), to check if the size is correct

*attributes(outdat) or attributes of columns

*sapply(outdat, class), to check variable classes

*summary statistics for variables, if applicable

*and so forth

A: If you would like to test this at runtime, you should check out the excellent ensurer package, see here. At the bottom of the page you can see how to construct a template that you can test your dataframe against, you can make it as detailed and specific as you like.

A: I'm just using something like this
d1 <- iris
d2 <- iris
expect_that(d1, equals(d2)) # passes
d3 <- iris
d3[141,3] <- 5
expect_that(d1, equals(d3)) # fails


text:
Q: Как вызвать переменную/метод вложенного класса при условии что вложенный класс private? День добрый!
Изучаю тему вложенных классов, не совсем пониманию, как мне вызвать метод или переменную вложенного класса с модификатором private.(Если я использую public с вложенным class, то все работает)
Может быть необходимо создать метод в классе A (так называемый сеттер), чтобы обращаться к приватному вложенному классу или это технически невозможно? Не понимаю, подскажите, пожалуйста.
class A
{
private:
    int m_a;

    class Inside_class
    {
    private:
        int m_b;
    public:
        Inside_class(int b) :m_b(b)
        {}
        void showDataOfInsideClass() { std::cout << m_b; }
    };

public:
    A(int a = 0): m_a(a) { }
    int showData() { return m_a; }
};

int main() {
    A object;
    A::Inside_class obj(5);//невозможно обратиться к private class, объявленному в классе "A"

}

A: Для начала перестаньте писать "метод". В плюсах это все таки функция или функия-член (member function). На русскоязычном пространстве это ещё ок, на англоязычном Вас будут поправлять.
Да, просто так достучатся к приватным внутренностям нельзя. На то они и приватные. И это скорее всего ошибка в дизайне, если хочется просто так получать доступ к приватным внутренностям.
Скорее всего Вам нужны функции в основном классе, который будет изменять внутренности приватного класса и сам за ним следить, а внешний код не будет ничего знать об этом.


text:
Q: htmlspecialchars is dropping characters I'm trying to use htmlspecialchars but it doesn't seem to be working. I'm using OSX 10.9.1 and PHP 5.4.17. I write:
var_dump(htmlspecialchars("Test", ENT_QUOTES, 'UTF-8'));
echo htmlspecialchars("Test", ENT_XHTML, 'UTF-8');

and get:
string '<a href='test'>Test</a>' (length=45)
Test</a

Any ideas?

A: It works, but you expect something else.
The output is interpreted by your browser as HTML. You can get the plain output by setting the content type to plain or using a command line.
<?php

header('Content-Type: text/plain');

var_dump(htmlspecialchars("Test", ENT_QUOTES, 'UTF-8'));
echo htmlspecialchars("Test", ENT_XHTML, 'UTF-8');


text:
Q: How to split a string every two characters then implement them in a four-square cipher? I am trying to write an encyption method that takes a string and splits it after every two characters. For example the word messages would be me ss ag es.
Then take the first string, me, and find where m corresponds on a plain1 square while also finding where e also fits on plain2 square. I can assume the string is always even numbered. I already have a getPosition method that will return the coordinates given a string. This is what I have so far:
public String encrypt(String message) {
String[] splitMessage = message.split("(?<=\\G..)");
        for (int i =0; i < message.length(); i++)
        {
            int [] pos = plain1.getPos(splitMessage[i]);
        }

My problem is I need the splitMessage[i] to be a char

A: This method will split a String into chunkSize Strings:
public static String[] splitIntoChunks(String s, int chunkSize)
{
    int numberOfChunks = (s.length() / chunkSize)
        + (s.length() % chunkSize > 0 ? 1 : 0);

    String[] chunks = new String[numberOfChunks];

    for (int i = 0, k = 0; i < s.length(); i += chunkSize, k++) {
        chunks[k] = s.substring(i, Math.min(i + chunkSize, s.length()));
    }

    return chunks;
}

A simple test program:
public static void main(String[] args)
{
    System.out.println(Arrays.toString(splitIntoChunks("messages", 2)));
}

Results in this output:

[me, ss, ag, es]


text:
Q: Image Linear Transformation graph interpretation While revesing some image processing material, I was faced to some grahs which I can't understand.
How should I interpret these graphs?

A: The graphs simply plot the function that describes a gray value transformation in image processing.
Looking at a graph is more intuitive than looking at a formula. Like in other disciplines, function graphs are just a quick and convenient way to discuss what's going on.
It shows two very simple examples.
The first one inverts the image.
O(x,y) or better O(I(x,y)) = 255 - I(x,y)
The second example clips anything below I1 and above I2 and normalizes the interval [I1,I2] to [0,255].
O(I(x,y)) =

*

*0,  if I(x,y) < I1

*255, if I(x,y) > I2

*(I(x,y) - I1) * 255/(I2-I1), else

Of course these graphs gain value with more complex or even non-linear tranformations.


text: Q: Share 50off coupon with friends and earn wallet 50 when that friend use that coupon on checkout I want to share a coupon 50off with friend and when that friend uses that coupon they will earn 50 as wallet money .how do i do that on magento 1?


text:
Q: When testing on iPod Touch, why are some images appearing huge?
Possible Duplicate:
Running app built in iOS4 on iOS 3.0, why is everything huge?

My images in my app are all 2x (or more) the size that they appear at. But for some reason, some of these images are appearing at their original size on the screen, when testing on a device, and so appear twice as large as they do in Interface Builder and on the simulator. And some are appearing at the size they should be.
Any ideas why this could be? My iPod Touch is 1st generation, so it's on 3.0 software.

A: The app probably only includes double resolution images for the Retina Display, and they're not suffixed with "@2x" to indicate that they're double.


text:
Q: Periodically run a cloud function every second without client input I am working on an app, where I need to periodically (every second) need to write a new timestamp in a field in firestore, this write should be performed when a specific property of the document equals true, if not the periodic execution should stop - how can I do that?

A: The easiest solution I can offer is to use Cloud Task. When a user create a session, create a dedicated task queue with a rate limit of 1 per seconds and a bunch of task in that queues (for instance 3600 task per hour).
That task will trigger a HTTP endpoint (typically a Cloud Functions or a Cloud Run endpoint) that will increment the counter.

The main question that I had was about the firestore choice. As far as I understand, if you have 10 users in parallel, you have 10 counter and you write 10 times the same thing in firestore. not really efficient.
I have 2 propositions here:

*

*Can you use a single counter and have several user object using the same count down?

*Did you consider Cloud Memorystore to use in memory database to perform your per-user-timestamp-write and save only the result in Firestore document.

A: As you see here in the doc, the maximum execution frequency for scheduled Cloud Functions is one execution per minute.
Since you need a higher frequency, you cannot fulfill your requirement with only a Cloud Function. You'll need to use another approach.

A: You can solve this issue by doing the following

*

*Create a cloud function that runs every minute

*Add in 4 timers that executes every 15 seconds

NOTE: Depending on you logic this might cost you... Don't do this without understanding what your usage costs will be, and don't forget about it. I take no responsibility for servers catching fire with this.
   export const my15SecondTimer = functions.pubsub
   .schedule("* * * * *")
   .onRun(async (context) => {

    // Some logic (1)
    setTimeout(async () => {
     // Some logic (2)
    }, 15000);

   setTimeout(async () => {
     // Some logic (3)
    }, 3000);

   setTimeout(async () => {
     // Some logic (4)
    }, 4500);

   });


text:
Q: Trying to iterate through files in a data lake and load them into a table in SQL Server I'm using Azure Data Bricks and trying to think of a way to write PySpark code to iterate through patterns of letters and numbers.  I have a bunch of files that look like this:
starts like this...
ABS0630.N.006134.gz
ABS0630.N.006135.gz

etc., etc., etc

ends like this...
ABS0630.J.000157.gz
ABS0630.J.000158.gz

The 'ABS' stays the same the the '0630' is June 30th.  Is there some brute force way to create a loop that iterates through patterns of letters and numbers and if a pattern matches the name of a file in our data lake, the file gets loaded into a table in SQL Server?  The table and related schema are all setup on the SQL Server side.  If I use ADF to load these one at a time, everything works fine.  I just can't figure out how to iterate through the files, and there are hundreds of files per day, sometimes over a thousand files per day.  The wildcard characters, like '*' and '?' don't work for some weird reason.  All I get is weird errors when I try to use the wildcard characters.
I am trying to used ADF to copy all these files into my SQL Server DB.


text:
Q: How to write inline Event Handler? I have written a change event handler in JS, but I want to write it inline in the HTML. How can I write the below action as inline like onchange="javascript: function() { return false; };"?

function changed(element) {
  if (element.value == 1 || element.value == 2) {
    $(element).removeClass('hide').addClass('show');
  }
}
<select class="chosen" name="content_media" style="width: 200px; display: none;" onchange="changed(this)" required="">
  <option value="default">--Select--</option>
  <option value="0">Press Ad</option>
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
  <option value="4">option4</option>
  <option value="5">option5</option>
  <option value="6">option6</option>
  <option value="7">option7</option>
</select>

A: You can just write the javascript code, example:
onchange="alert('Value was changed to ' + event.target.value);"

This might make your code messier though...

A: Since you're using jQuery it's better to attach your event in the js side instead of inline-events, like :

$('.chosen').on('change', function(){
  var selected_value = $(this).val();

  if ( selected_value == 1 || selected_value == 2 )
     console.log(selected_value+' selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="chosen" name="content_media" style="width: 200px;" required="">
  <option value="default">--Select--</option>
  <option value="0">Press Ad</option>
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
  <option value="4">option4</option>
  <option value="5">option5</option>
  <option value="6">option6</option>
  <option value="7">option7</option>
</select>

Hope this helps.


text:
Q: Prove that $d$ is a metric It is given that $d$ is a real-valued function on $X \times X$ which for all x, y and z in X satisfies $d(x,y)=0$ iff x=y and $$d(x,y)+d(x,z)\geq d(y,z)$$
In order to show that $d$ is a metric is left for me to show that $d(x,y)=d(y,x)$.
I guess I cannot wrap my head around it at the time. I am working on it now.
Thank you for your help!
Now $$d(y,x)\leq d(z,y)+d(z,x)$$

A: $$\underline{d(x,y)}=d(x,y) + d(x,x)+d(y,y)\underline{\geq d(y,x)}+d(y,y)\underline{\geq d(x,y)}.$$
For non-negativity a similar argument applies:
$$2d(x,y)=d(x,y)+d(x,y)\geq d(y,y)=0\implies d(x,y)\geq 0.$$

A: $d(x,y)=d(x,y)+d(x,x) \geq d(y,x) $  and $d(y,x)=d(y,x)+d(y,y)\geq d(x,y)$
So $d(x,y) = d(y,x)$


text:
Q: Xamarin.Forms - ListView change height at runtime I'm developing a cross-platform app using Xamarin.Forms. In one of the pages I've an avatar image, some info, and then a ListView. The thing is that I've all this wrapped in a ScrollView, so I'm able to scroll all over the content. The issue with this is that I'm losing the ListView scroll behaviour. This're some screenshots:

As you can see the XAML view is basically, the avatar Image (the firetruck image), then the "Last check step" info, and then we've the ListView. I hardcoded a HeightRequest in the ListView so It has a bigger height. But the thing is that when I scroll to the bottom of the page I can't keep scrolling through the ListView because the ScrollView messes with that behaviour. I need to use a ListView because the list of check reports that I'm showing there is populated from a webservice, and I update that list when I enter and exit the page. This is the XAML code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:checkReport="clr-namespace:HalliganTL.View;assembly=HalliganTL"
              xmlns:controls="clr-namespace:ImageCircle.Forms.Plugin.Abstractions;assembly=ImageCircle.Forms.Plugin.Abstractions"
             x:Class="HalliganTL.View.ApparatusDetailPage" BackgroundColor="#FFFFFFFF">
  <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
    <ScrollView x:Name="GeneralScrollView"
                Orientation="Vertical" VerticalOptions="FillAndExpand"
                HorizontalOptions="FillAndExpand">
      <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <Grid.RowDefinitions>
          <RowDefinition Height="180"></RowDefinition>
          <RowDefinition Height="40"></RowDefinition>
          <RowDefinition Height="80"></RowDefinition>
          <RowDefinition Height="40"></RowDefinition>
          <RowDefinition Height="360"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <!-- Top Image -->
        <ContentView Grid.Column="0" Grid.Row="0" Padding="15">
          <controls:CircleImage x:Name="ApparatusImage"
            HeightRequest="150" WidthRequest="150"
            VerticalOptions="Center"
            BorderColor="#3B5685"
            BorderThickness="2"
            HorizontalOptions="Center"
            Aspect="AspectFill">
          </controls:CircleImage>
        </ContentView>

        <!-- Last Check Separator -->
        <AbsoluteLayout Grid.Column="0" Grid.Row="1" x:Name="LastCheckContainerTitle" BackgroundColor="#FFE4E4E9" Padding="5,15,15,5" VerticalOptions="End" >
          <Label Text="LAST CHECK" Style="{StaticResource separatorLabel}" />
        </AbsoluteLayout>
        <!-- Last Check Detail -->
        <checkReport:CheckReportViewPage Grid.Column="0" Grid.Row="2" x:Name="LastCheckReportView">
          <checkReport:CheckReportViewPage.GestureRecognizers>
            <TapGestureRecognizer Tapped="OnLastCheckReportClicked" NumberOfTapsRequired="1" />
          </checkReport:CheckReportViewPage.GestureRecognizers>
        </checkReport:CheckReportViewPage>

        <AbsoluteLayout  Grid.Column="0" Grid.Row="3"  x:Name="CheckHistoryTitle" BackgroundColor="#FFE4E4E9" Padding="5,15,15,5" >
          <Label Text="CHECK HISTORY" Style="{StaticResource separatorLabel}" FontAttributes="None" VerticalOptions="End" />
        </AbsoluteLayout>

        <!-- Apparatus check history -->
        <ListView x:Name="CheckHistoryListView"
                  HeightRequest="380"
                   Grid.Column="0" Grid.Row="4"
                  HorizontalOptions="FillAndExpand"
                  HasUnevenRows="True"
                  IsPullToRefreshEnabled="False"
                  VerticalOptions="FillAndExpand" ItemTapped="OnItemTapped">
          <ListView.ItemTemplate>
            <DataTemplate>
              <ViewCell>
                <checkReport:CheckReportViewPage/>
              </ViewCell>
            </DataTemplate>
          </ListView.ItemTemplate>
        </ListView>
      </Grid>
    </ScrollView>

    <Label Text="Start Check" HeightRequest="60"  VerticalOptions="End" BackgroundColor="#3B5685" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" FontSize="18" TextColor="White">
      <Label.GestureRecognizers>
        <TapGestureRecognizer
                Tapped="OnStartCheckClicked"
                NumberOfTapsRequired="1" />
      </Label.GestureRecognizers>
    </Label>

  </StackLayout>

</ContentPage>

So basically what I'm asking is how can achieve something like a parallax effect, scrolling down and then delegate the scroll behaviour to the ListView that way I can scroll through every item in the ListView. Currently I'm just able to see the items that fit in the ListView HeightRequest dimension. In the example screenshot that I'm shoing for example, there are several other items in that ListView but I can't scroll through them because the ScrollView is messing with the ListView scroll behaviour.

A: The recommended approach for putting content on a page with a ListView is to use the Footer and Header properties of the ListView.
Have a look at ListView Headers and Footers
<ListView x:Name="listView">
  <ListView.Footer>
    <Label Text="Footer" />
  </ListView.Footer>
</ListView>

This way you don't need to wrap in another scroll.

A: ListView should never be placed inside of a scrolling container. When you do this, you lose all benefits of the ListView (virtualization, scrolling, etc).
If you need to implement a parallax effect by scrolling some other content in sync with the ListView position, then you can always overlay the list on top of another scrolling view (but not as a child of that scrolling view).

A: I believe that you need a RepeaterView , a control that repeats items but is not scrolable and you can bind it to an ObservableCollection.
It just works
using System;
    using System.Collections;
    using System.Collections.Specialized;
    using Xamarin.Forms;

    public delegate void RepeaterViewItemAddedEventHandler(object sender, RepeaterViewItemAddedEventArgs args);

    // in lieu of an actual Xamarin Forms ItemsControl, this is a heavily modified version of code from https://forums.xamarin.com/discussion/21635/xforms-needs-an-itemscontrol
    public class RepeaterView : StackLayout
    {
        public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create<RepeaterView, IEnumerable>(
            p => p.ItemsSource,
            null,
            BindingMode.OneWay,
            propertyChanged: ItemsChanged);

        public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create<RepeaterView, DataTemplate>(
            p => p.ItemTemplate,
            default(DataTemplate));

        public event RepeaterViewItemAddedEventHandler ItemCreated;

        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public DataTemplate ItemTemplate
        {
            get { return (DataTemplate)GetValue(ItemTemplateProperty); }
            set { SetValue(ItemTemplateProperty, value); }
        }

        private static void ItemsChanged(BindableObject bindable, IEnumerable oldValue, IEnumerable newValue)
        {
            var control = (RepeaterView)bindable;
            var oldObservableCollection = oldValue as INotifyCollectionChanged;

            if (oldObservableCollection != null)
            {
                oldObservableCollection.CollectionChanged -= control.OnItemsSourceCollectionChanged;
            }

            var newObservableCollection = newValue as INotifyCollectionChanged;

            if (newObservableCollection != null)
            {
                newObservableCollection.CollectionChanged += control.OnItemsSourceCollectionChanged;
            }

            control.Children.Clear();

            if (newValue != null)
            {
                foreach (var item in newValue)
                {
                    var view = control.CreateChildViewFor(item);
                    control.Children.Add(view);
                    control.OnItemCreated(view);
                }
            }

            control.UpdateChildrenLayout();
            control.InvalidateLayout();
        }

        protected virtual void OnItemCreated(View view) =>
            this.ItemCreated?.Invoke(this, new RepeaterViewItemAddedEventArgs(view, view.BindingContext));

        private void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            var invalidate = false;

            if (e.OldItems != null)
            {
                this.Children.RemoveAt(e.OldStartingIndex);
                invalidate = true;
            }

            if (e.NewItems != null)
            {
                for (var i = 0; i < e.NewItems.Count; ++i)
                {
                    var item = e.NewItems[i];
                    var view = this.CreateChildViewFor(item);

                    this.Children.Insert(i + e.NewStartingIndex, view);
                    OnItemCreated(view);
                }

                invalidate = true;
            }

            if (invalidate)
            {
                this.UpdateChildrenLayout();
                this.InvalidateLayout();
            }
        }

        private View CreateChildViewFor(object item)
        {
            this.ItemTemplate.SetValue(BindableObject.BindingContextProperty, item);
            return (View)this.ItemTemplate.CreateContent();
        }
    }

    public class RepeaterViewItemAddedEventArgs : EventArgs
    {
        private readonly View view;
        private readonly object model;

        public RepeaterViewItemAddedEventArgs(View view, object model)
        {
            this.view = view;
            this.model = model;
        }

        public View View => this.view;

        public object Model => this.model;
    }

Read this thread in Xamarin Forms Forums


text:
Q: Custom HashMap Code Issue I have following code, where I used HashMap (using two parallel arrays) for storing key-value pairs (key can have multiple values). Now, I have to store and load it for future use that's why I store and load it by using File Channel. Issue with this code is: I can store nearly 120 millions of key-value pairs in my 8 GB server (actually, I can allocate nearly 5 gb out of 8 gb for my JVM, and those two parallel arrays takes nearly 2.5 gb, other memory are used for various processing of my code). But, I have to store nearly 600/700 millions of key-value pairs. Can anybdoy help me how to modify this code thus I can store nearly 600/700 millions of key-value pairs. Or any comment on this will be nice for me. Another point, I have to load and store the hashmap to/from memory. It takes little bit long time using file channel. As per various suggestions of Stack Overflow, I didn't find faster one. I have used ObjectOutputStream, Zipped output stream also, however, slower than below code. Is there anyway to store those two parallel arrays in such a way thus loading time will be much faster. I have given below in my code a test case. Any comment on that will also be helpful to me.
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Arrays;
import java.util.Random;
import java.nio.*;
import java.nio.channels.FileChannel;
import java.io.RandomAccessFile;

public class Test {

    public static void main(String args[]) {

        try {

            Random randomGenerator = new Random();

            LongIntParallelHashMultimap lph = new LongIntParallelHashMultimap(220000000, "xx.dat", "yy.dat");

            for (int i = 0; i < 110000000; i++) {
                lph.put(i, randomGenerator.nextInt(200000000));
            }

            lph.save();

            LongIntParallelHashMultimap lphN = new LongIntParallelHashMultimap(220000000, "xx.dat", "yy.dat");
            lphN.load();

            int tt[] = lphN.get(1);

            System.out.println(tt[0]);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class LongIntParallelHashMultimap {

    private static final long NULL = -1L;
    private final long[] keys;
    private final int[] values;
    private int size;
    private int savenum = 0;
    private String str1 = "";
    private String str2 = "";

    public LongIntParallelHashMultimap(int capacity, String st1, String st2) {
        keys = new long[capacity];
        values = new int[capacity];
        Arrays.fill(keys, NULL);
        savenum = capacity;
        str1 = st1;
        str2 = st2;
    }

    public void put(long key, int value) {
        int index = indexFor(key);
        while (keys[index] != NULL) {
            index = successor(index);
        }
        keys[index] = key;
        values[index] = value;
        ++size;
    }

    public int[] get(long key) {
        int index = indexFor(key);
        int count = countHits(key, index);
        int[] hits = new int[count];
        int hitIndex = 0;

        while (keys[index] != NULL) {
            if (keys[index] == key) {
                hits[hitIndex] = values[index];
                ++hitIndex;
            }
            index = successor(index);
        }

        return hits;
    }

    private int countHits(long key, int index) {
        int numHits = 0;
        while (keys[index] != NULL) {
            if (keys[index] == key) {
                ++numHits;
            }
            index = successor(index);
        }
        return numHits;
    }

    private int indexFor(long key) {
        return Math.abs((int) ((key * 5700357409661598721L) % keys.length));
    }

    private int successor(int index) {
        return (index + 1) % keys.length;
    }

    public int size() {
        return size;
    }

    public void load() {
        try {
            FileChannel channel2 = new RandomAccessFile(str1, "r").getChannel();
            MappedByteBuffer mbb2 = channel2.map(FileChannel.MapMode.READ_ONLY, 0, channel2.size());
            mbb2.order(ByteOrder.nativeOrder());
            assert mbb2.remaining() == savenum * 8;
            for (int i = 0; i < savenum; i++) {
                long l = mbb2.getLong();
                keys[i] = l;
            }
            channel2.close();

            FileChannel channel3 = new RandomAccessFile(str2, "r").getChannel();
            MappedByteBuffer mbb3 = channel3.map(FileChannel.MapMode.READ_ONLY, 0, channel3.size());
            mbb3.order(ByteOrder.nativeOrder());
            assert mbb3.remaining() == savenum * 4;
            for (int i = 0; i < savenum; i++) {
                int l1 = mbb3.getInt();
                values[i] = l1;
            }
            channel3.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public void save() {
        try {
            FileChannel channel = new RandomAccessFile(str1, "rw").getChannel();
            MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0, savenum * 8);
            mbb.order(ByteOrder.nativeOrder());

            for (int i = 0; i < savenum; i++) {
                mbb.putLong(keys[i]);
            }
            channel.close();

            FileChannel channel1 = new RandomAccessFile(str2, "rw").getChannel();
            MappedByteBuffer mbb1 = channel1.map(FileChannel.MapMode.READ_WRITE, 0, savenum * 4);
            mbb1.order(ByteOrder.nativeOrder());

            for (int i = 0; i < savenum; i++) {
                mbb1.putInt(values[i]);
            }
            channel1.close();
        } catch (Exception e) {
            System.out.println("IOException : " + e);
        }
    }
}

A: I doubt this is possible, given the datatypes you have declared. Just multiply the sizes of the primitive types.
Each row requires 4 bytes to store an int and 8 bytes to store a long.
600 million rows * 12 bytes per row = 7200 MB = 7.03 GB. You say you can allocate 5 GB to the JVM. So even if it was all heap and stored only this custom HashMap, it will not fit. Consider shrinking the size of the datatypes involved or storing it somewhere other than RAM.

A: Have the database on disk, and not in memory. Rewrite your operations so that they don't operate on arrays, but instead operate on buffers. Then you can open a sufficiently large file, and have the operations access the portion they need using a mapped buffer. Try whether your application performs better when you implement a cache of the few most recently mapped memory regions, so you won't have to map and unmap common regions too often, but instead can keep them mapped in.
This should give you the best of both worlds, disk and ram:

*

*Random access to any portion of the data structure is easy to implement

*Access to often used portions of the table will be cached

*Seldom used portions of the table will not occupy any memory

As you can see, this depends a lot on locality: if some keys are more common than others, things will perform well, whereas nicely distributed keys will cause a new disk operation for each access. So while nice distributions are desirable for most in-memory hash maps, other structures which map often-used keys to similar locations will perform better here. Those will interfere with collision handling, though.

A: Better to use in-memory database like sqlite, which will give good result.


text:
Q: How to get the pixel coordinates from a SVG path String I want to display geometric objects on a map using go.js in combination with leaflet.js
It is important for me that the geometric object sticks to their geo-position. I simply translate the pixel coordinates to lat/lng geo-coordinates.
However, for some geometric objects it is not that easy for me to get all the necessary geo-coordinates.
For a polygon I get an SVG-Path String like :
"F M54 77 L39 128 L0 146 L18 178 L45 215 L87 220 L79 321 L79 400 L153 371 L246 340 L296 325 L332 255 L324 207 L355 164 L338 138 L368 105 L380 23 L336 0 L282 35 L222 10 L147 10 L95 38 L60 44z"

as well as the pixel coordinates of the middle Point.
So I would need the pixel coordinate of every corner point.
Do you have any idea or suggestion how I could translate the SVG path to its pixel coordinates?
Hope you guys can help me.
Best regards!
enter image description here

A: Do you have a GoJS Part (or Node) that holds a Shape whose Shape.geometryString is what you posted?
If so, I suggest that you look at the Shape.geometry and look at its Geometry.figures' PathFigures and their PathSegments.  For each of those points you can convert to GoJS document coordinates by adding the Part.position plus half the Shape.strokeWidth.  Then you can convert document coordinates to LatLng by calling Leaflet map's containerPointToLatLng method.


text:
Q: List of Abbreviations not showing I had a list of abbreviations, which worked fine, but now it's not showing any more. And I have no idea what I could've changed. It is shown in the table of content, but also on the wrong position.
My preamble:
\newcommand{\Abkuerzung}{
    \printnomenclature
    \newpage
}

The place where it should be displayed:
\addcontentsline{toc}{chapter}{\noname}
\Abkuerzung

My abbreviations
    \abbrev{dex}{Dalvik Executable}
    :
How I build it:
pdflatex file.tex
makeindex file.nlo -s nomencl.ist -o file.nls
pdflatex file.tex
pdflatex file.tex

my output of makeindex:
Scanning style file /usr/share/texmf-dist/makeindex/nomencl/nomencl.ist....done(10 attributes redefined, 3 ignored).
Scanning input file file.nlo...done (0 entries accepted, 0 rejected).
Nothing written in file.nls
Transctipt written in file.ilg

I see that there is nothing written into the nls file and nothing happens and so, but what can I do?
EDIT
\documentclass[11pt,a4paper]{report}

\usepackage{graphicx}
    \usepackage{a4}
\usepackage[english, ngerman]{babel}
%That Headings have Kapitälchen:
\usepackage[T1]{fontenc}

\usepackage{xcolor}

%%%%%%%%%BIBLIOGRAPHY + PICTURES IN TABLE OF CONTENTS
\usepackage[nottoc]{tocbibind}
\usepackage{breakcites}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%ABKÜRZUNGEN
\usepackage{nomencl}
\let\abbrev\nomenclature
\renewcommand{\nomname}{List of Abbreviations}
\setlength{\nomlabelwidth}{.25\hsize}
\renewcommand{\nomlabel}[1]{#1 \dotfill}
\setlength{\nomitemsep}{-\parsep}
\makenomenclature
\newcommand{\Abkuerzung}{
\printnomenclature
\newpage
}

\begin{document}

\include{cover}
\include{title}
\include{abstract}
\include{affidavit}

\selectlanguage{english}
\tableofcontents
\listoffigures
\renewcommand{\lstlistlistingname}{Listings}
\lstlistoflistings
\addcontentsline{toc}{chapter}{Listings}
\newpage
\addcontentsline{toc}{chapter}{\nomname}
\Abkuerzung

%%% Chapters
\include{Chapters/introduction}
\include{Chapters/overview}
\include{Chapters/migration}
\include{Chapters/analysis}
\include{Chapters/conclusion}

%%%%%%%%%%%%%%%%%%BIBLIOGRAPHY%%%%%%%%%%%%%%%%%%%%%
%\nocite{*}
\bibliography{bibliography}{}
%\bibliographystyle{apalike}
\bibliographystyle{abbrv}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%makeindex thesis.nlo -s nomencl.ist -o thesis.nls
\abbrev{dex}{Dalvik Executable}
\abbrev{XML}{Extensible Markup Language}
\abbrev{VM}{Virtual Machine}
\abbrev{JIT}{Just In Time}
\abbrev{DVM}{Dalvik Virtual Machine}
\abbrev{JVM}{Java Virtual Machine}

\end{document}

A: First off, are you making your definitions inline with the text? Since the nomenclature is a specialized index, it's really meant to be used as you're introducing new terms, and not as a big list of items at the end of the document.
That having been said, as long as there's body text in the document, it looks like your code works. Not having any of your included content, the following works fine:
\documentclass{report}

\usepackage{nomencl}
\let\abbrev\nomenclature
\makenomenclature
\newcommand{\Abkuerzung}{
\printnomenclature
\newpage
}

\begin{document}

\tableofcontents
\listoffigures
\addcontentsline{toc}{chapter}{\nomname}
\Abkuerzung

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%makeindex thesis.nlo -s nomencl.ist -o thesis.nls
Uncomment this text, so the abbrev command will have something to reference. Otherwise, nothing works.
\abbrev{dex}{Dalvik Executable}
\abbrev{XML}{Extensible Markup Language}
\abbrev{VM}{Virtual Machine}
\abbrev{JIT}{Just In Time}
\abbrev{DVM}{Dalvik Virtual Machine}
\abbrev{JVM}{Java Virtual Machine}
\end{document}

But it didn't work at all until I had actual text in the body of the document. I'll edit or remove this answer depending on what else you find out.


text:
Q: GridView images drag and drop flutter I have a code using Flutter framework which allows to select multiple images and view the images before uploading to firebase.
After selecting images, I would like to have the possibility to drag and drop these images in order to reorder these images and save them later with the order chooses by the user.
I tried to implement this drag and drop but all the examples I saw are for ListView, which is not the case in my situation :(
Here is my code:
import 'package:drag_and_drop_gridview/devdrag.dart';
import 'package:drag_and_drop_gridview/drag.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:async';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:path/path.dart' as Path;

import 'package:flutter/services.dart';

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {

  bool uploading = false;
  double val = 0;
  CollectionReference imgRef;
  firebase_storage.Reference ref;

  List<File> _image = [];
  final picker = ImagePicker();

  int variableSet = 0, variableSetHeader = 0;
  ScrollController _scrollController;
  double width;
  double height;

  @override
  Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('Horizontal DragAndDropGridView'),
          actions: [
            // ignore: deprecated_member_use
            FlatButton(
                onPressed: () {
                  setState(() {
                    uploading = true;
                  });
                  uploadFile().whenComplete(() => Navigator.of(context).pop());
                },

                child: Text(
                  'upload',
                  style: TextStyle(color: Colors.white),
                )),
          ],

        ),

        body: Stack(
          children: [
          Container(
              padding: EdgeInsets.all(4),
             child: DragAndDropGridView.horizontal(
              controller: _scrollController,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 5,
                childAspectRatio: 3 / 4.5,
              ),
              padding: EdgeInsets.all(20),
              itemBuilder: (context, index) => Container(
                padding: EdgeInsets.all(4),
                child: GridView.builder(
                    itemCount: _image.length + 1,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3),
                    itemBuilder: (context, index) {
                      return index == 0
                          ? Center(
                        child: IconButton(
                            icon: Icon(Icons.add),
                            onPressed: () =>
                            !uploading ? chooseImage() : null),
                      )
                          : Container(
                        margin: EdgeInsets.all(3),
                        decoration: BoxDecoration(
                            image: DecorationImage(
                              image: FileImage(_image[index - 1]),
                              fit: BoxFit.cover,
                            )
                        ),
                      );
                    }
                ),
              ),
              itemCount: _image.length,
              onWillAccept: (oldIndex, newIndex) => true,
              onReorder: (oldIndex, newIndex) {
                int indexOfFirstItem = _image.indexOf(_image[oldIndex]);
                int indexOfSecondItem = _image.indexOf(_image[newIndex]);

                if (indexOfFirstItem > indexOfSecondItem) {
                  for (int i = _image.indexOf(_image[oldIndex]);
                  i > _image.indexOf(_image[newIndex]);
                  i--) {
                    var tmp = _image[i - 1];
                    _image[i - 1] = _image[i];
                    _image[i] = tmp;
                  }
                } else {
                  for (int i = _image.indexOf(_image[oldIndex]);
                  i < _image.indexOf(_image[newIndex]);
                  i++) {
                    var tmp = _image[i + 1];
                    _image[i + 1] = _image[i];
                    _image[i] = tmp;
                  }
                }
                setState(() {});
              },
            ),
          ),

            uploading
                ? Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      child: Text(
                        'uploading...',
                        style: TextStyle(fontSize: 20),
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),

                    CircularProgressIndicator(
                      value: val,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
                    ),

                  ],
                )
            )
                : Container(),
          ],
        )
    );
  }

  chooseImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image.add(File(pickedFile?.path));
    });
    if (pickedFile.path == null) retrieveLostData();
  }

  Future<void> retrieveLostData() async {
    final LostData response = await picker.getLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      setState(() {
        _image.add(File(response.file.path));
      });
    } else {
      print(response.file);
    }
  }

  Future uploadFile() async {
    int i = 1;
    var firebaseUser =  FirebaseAuth.instance.currentUser.email;
    for (var img in _image) {
      setState(() {
        val = i / _image.length;
      });
      ref = firebase_storage.FirebaseStorage.instance
          .ref()
          .child('${firebaseUser}/Livres/${Path.basename(img.path)}');
      await ref.putFile(img).whenComplete(() async {
        await ref.getDownloadURL().then((value) {
          imgRef.add({'url': value});
          i++;
        });
      });
    }
  }

  @override
  void initState() {
    var firebaseUser =  FirebaseAuth.instance.currentUser.email;

    super.initState();
    imgRef = FirebaseFirestore.instance.collection(firebaseUser);
  }
}

A: Use Draggable widget or use this plugin draggable gridView

A: You can use reorderable_grid_view package. It is null-safe & easy to use.
reorderable_grid_view
Its ReorderableGridView.count method has same properties as of GridView.count with some extra properties like reorder to drag-n-drop/reorder the gridview.
Below youtube video will help you to get more details on gridview drag & drop.
Flutter - Drag & drop items in Gridview


text:
Q: Silverlight 4 UserControl? For Silverlight 4 did TemplatedControl replace UserControl?  Because when I goto add a new item in Visual Studio 2010 that is the only thing that closely resembles a user control in the dialog?

A: No, they should both be there, are you sure the silverlight tools for visual studio 2010 are installed correctly?


text:
Q: What is the proper English for forcefully occupying tenders? In some places, when governments and local authorities call for tenders from potential contractors for various projects, incoming tenders are physically delivered into a box where they are stored until the tender process is complete. In some parts of the world, tenders can be the root of rather serious and violent clashes (e.g., in South Africa or Bangladesh).
Suppose in such a place one bidder physically occupies that tender box, preventing anyone else from dropping in any tenders of their own and thus making sure they themselves win the tender.
From a certain point of view it can be considered tender theft; but that's quite a broad term, and I remember reading a specific term for this kind of 'hogging' the tender box itself in a newspaper once.
What is the proper English term for 'tender box hogging'?


text:
Q: SMTP email for office365 I want to send an email through python, I followed the below code from this link:
import smtplib

mailserver = smtplib.SMTP('smtp.office365.com',587)
mailserver.ehlo()
mailserver.starttls()
mailserver.login('myemail@company.com', 'mypassword')
msg = ('this is a message')
mailserver.sendmail('myemail@company.com','receiver@company.com',msg)

The issue:
The email is in my sentbox, and the receiver's inbox, however there is no text. It is empty.
There is no error, or output, the script just runs, so I am unsure where to start troubleshooting, as I am not an expert in this area; could anyone explain why there is no message/text?

A: You need a \n between subject and email body in the 3rd argument to sendmail
msg = 'Subject: Email Subject.\n{}'.format('this is a message')
mailserver.sendmail('myemail@company.com','receiver@company.com', msg)


text:
Q: OpenMAX and the NDK: Where I can get the surface? I'm writing an application that shows video. The application is written using the Android NDK and JNI.
I want to use OpenMAX. In the OpenMAX example, it retrieves the surface from Java, but where I can get the surface to render? I can get a nativeWindow only through applicationContext.
Example:
void Java_com_example_nativemedia_NativeMedia_setSurface(JNIEnv *env, jclass clazz, jobject surface)
{
    theNativeWindow = ANativeWindow_fromSurface(env, surface);
}

But I don't have the surface.
Thanks

A: The surface is retrieved from the SurfaceHolder that is passed in as a parameter in the methods in SurfaceHolder.Callback, ie surfaceChanged or surfaceCreated.
Look for where the JNI function setSurface is called by Java:
wilhelm\tests\native-media\src\com\example\nativemedia\NativeMedia.java


text:
Q: In or Contains query using System.Linq.Dynamic Background: I would like to use System.Linq.Dynamic library to post In/Contains query to MS SQL
Please note I am trying to use System.Linq.Dynamic in generic function so that I could apply customer filter to any class having CustomerId(integer) property. Also CustomerId property could be nullable
All SO posts redirects me to this solution. After implementing the same I keep getting this exception: "No generic method 'Contains' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic."
And now this is how my code looks like:
public static IQueryable<T> ApplyCustomerFilter<T>(this IQueryable<T> collection, int[] customerIds)
{
    return collection.Where("@0.Contains(outerIt.CustomerId)", customerIds);
}

public class MyUser : IdentityUser
{
    [Required]
    [MaxLength(50)]
    public string FirstName { get; set; }
    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }
    public int? CustomerId { get; set; }
    [ForeignKey(nameof(CustomerId))]
    public virtual Customer Customer { get; set; }
}

Could you please guide me where I am going wrong?

A: Because your MyUser.CustomerId property is nullable - you should pass nullable int array as customerIds in this case. For example:
public static IQueryable<T> ApplyCustomerFilter<T>(
    this IQueryable<T> collection,
    int?[] customerIds) { // < - note here
        return collection.Where("@0.Contains(outerIt.CustomerId)", customerIds);
}

or convert passed array to array of nullable ints:
public static IQueryable<T> ApplyCustomerFilter<T>(
    this IQueryable<T> collection,
    int[] customerIds) {
        return collection.Where("@0.Contains(outerIt.CustomerId)",
             customerIds.Cast<int?>()); // <- note here
}

Alternatives proposed by Ivan Stoev in comments (with them customerIds array can be regular int[] array, no need for it to be array of nullables):
"@0.Contains(outerIt.CustomerId.Value)"

And this one will work in both cases (whether CustomerId is nullable or not):
"@0.Contains(Int32(outerIt.CustomerId))"


text:
Q: Checking if an element created by javascript exists using only javascript The question is quite straightforward. Is there a javascript only (no jQuery/other library pls) method of checking if an element created via javascript exists?
For instance, if I did this:
var foo=document.createElement("div");
document.getElementById("bar").appendChild(foo);

Would there be a way to check if foo already exists?

A: You could simply get the element by id and see if its not null.
var foo=document.createElement("div");
document.getElementById("bar").appendChild(foo);
foo.setAttribute("id","foo");
var ele = document.getElementById("foo");
if(ele !== null){ alert("Hi");}

A: foo is not an element, it's a variable whose value is an element. There are different ways to interpret your question.
Is the value of the variable foo a DOM element?
If you want to check if the variable foo exists and has as its value an element, you can say
foo && typeof foo === 'object' && foo.nodeType

or something similar. This will check whether the element is any kind of Node. To check for an element, use foo.nodeType === Node.ELEMENT_NODE.
Is a particular HTML element in the DOM?
If you want to check if the element held in variable foo is in the DOM, as opposed to having been created, but not yet inserted, then:
foo.baseURI

since baseURI is set only upon DOM insertion. You might think you could check parentNode, which is also not set until DOM insertion, but children of the non-inserted element, if any, will report a parentNode, as will elements appended to a document fragment.
The other alternative is to use Node#contains:
document.body.contains(foo)

which essentially does the same thing as scanning the entire DOM for the element:
Array.prototype.some.call(document.querySelector('*'), function(elt) {
    return elt === foo;
})

In any case, this all seems pointless, because as far as I can imagine, if you hold a reference to a DOM element, and it's not not in the DOM, then it is in the DOM.
Is there already an element in the place I'm going to be inserting this one?
If you know where the element is going to go, in this case as a child of bar, and that's enough to convince you that the "element already exists", you can check easily enough with something like:
document.getElementById("bar").children.length > 0

Is there already an element with this ID?
As other commenters and responders have noted, you can obviously find an element in the DOM if you have arranged to provide it with some uniquely identifiable characteristics, most likely an id.
I hope it's obvious that element ID is completely separate from the name of any JavaScript variables which happen to be holding references to that element. It is true that elements become available on the root (window) object under their ID or name attributes, a feature best left unused.
Was the element in the source HTML, or created by JavaScript?
From the wording of your question, it seems that you might be interested in whether the element was created by JS, as opposed to originating from the source HTML. There is no way I know of to detect that. If you are intent on doing so, override document.createElement as follows:
document.createElement = (function() {
    var old = document.createElement;
    return function(tagName) {
        var elt = old.call(document, tagName);
        elt.I_CREATED_THIS = true;
        return elt;
    };
}());

> document.body.I_CREATED_THIS
undefined
> elt = document.createElement('span');
> elt.I_CREATED_THIS
true


text:
Q: Can you say "events that have impacted their lives" Can you say the characters are struggling with "events that have impacted their lives" or would you have to say events that have impacted on their lives?

A: The first is correct. You could also phrase it "the characters are struggling with the events that have had an impact on their lives," which sounds a little wordy and stuffy to me.


text:
Q: XCode Storyboard - View appearing in Landscape? Building an application which started as fairly simple, but now got pretty complicated. I am facing a strange problem. I am now using only storyboards to define all of my views. The problem I am facing is, some view-controllers in storyboard are appearing in Landscape mode and others in Portrait mode.
I know it won't make a difference in final application, but it is making it hard for me to design and visualize things. Has someone else faced this problem?

A: Click on the view in storyboards , click on the attributes inspector (third from the top left) in simulated metrics change the orientation to portrait


text:
Q: How do Shadertoy's audio shaders work? To start off, I couldn't really find any appropriate community to post this question in so I picked this one. I was wondering how the audio shaders of the popular webGL based shader tool worked, because when, even though I had obviously heard of 'normal' GLSL shaders, I first heard of shaders for procedurally generating audio, I was amazed. Any clues?

A: They are basically a function that given time returns 2 values for an audio single (left and right channel). The values go from -1 to 1.
paste in this shader and maybe you'll get it
vec2 mainSound( float time )
{
    return vec2( sin(time * 1000.0), sin(time * 1000.0) );
}

You can see a more live example of a similar style of making sounds here.
You can imagine it like this
function generateAudioSignal(time) {
   return Math.sin(time * 4000); // generate a 4khz sign wave.
}

var audioData = new Float32Array(44100 * 4); // 4 seconds of audio at 44.1khz
for (var sample = 0; sample < audioData.length; ++sample) {
  var time = sample / 44100;
  audioData[sample] = generateAudioSignal(time);
}

Now pass audioData to the Web Audio API
For stereo it might be
function generateStereoAudioSignal(time) {
   return [Math.sin(time * 4000), Math.sin(time * 4000)]; // generate a 4khz stereo sign wave.
}

var audioData = new Float32Array(44100 * 4 * 2); // 4 seconds of stereo audio at 44.1khz
for (var sample = 0; sample < audioData.length; sample += 2) {
  var time = sample / 44100 / 2;
  var stereoData = generateAudioSignal(time);
  audioData[sample + 0] = stereoData[0];
  audioData[sample + 1] = stereoData[1];
}

There's really no good reason for them to be in WebGL (assuming they are). In WebGL you'd use them to generate data into a texture attached to a framebuffer. Then the data they generate would have to be copied back from the GPU into main memory using gl.readPixels and then passed into the Web Audio API which would be slow and, at least in WebGL it would block processing as there's no way to asynchronously read data back in WebGL. On top of that you can't easily read back float data in WebGL. Of course if shadertoy really is using WebGL then it could re-write the audio shader to encode the data into 8bit RGBA textures and then convert it back to floats in JavaScript. Even more reason NOT to use WebGL for this. The main reason to use WebGL is it just makes it symmetrical. All shaders using the same language.
The bytebeat example linked above is fully run in JavaScript. It defaults to bytebeat meaning the value the function is expected to return is 0 to 255 unsigned int but there's a setting for floatbeat in which case it expects a value from -1 to 1 just like shadertoy's shaders.

Update
So I checked Shadertoy and it is using WebGL shaders and it is encoding the values into 8bit textures
Here's an actual shader (I used the chrome shader editor to easily look at the shader).
precision highp float;

uniform float     iChannelTime[4];
uniform float     iBlockOffset;
uniform vec4      iDate;
uniform float     iSampleRate;
uniform vec3      iChannelResolution[4];
uniform sampler2D iChannel0;
uniform sampler2D iChannel1;
uniform sampler2D iChannel2;
uniform sampler2D iChannel3;

vec2 mainSound( float time )
{
    return vec2( sin(time * 1000.0), sin(time * 1000.0) );
}

void main() {
   // compute time `t` based on the pixel we're about to write
   // the 512.0 means the texture is 512 pixels across so it's
   // using a 2 dimensional texture, 512 samples per row
   float t = iBlockOffset + ((gl_FragCoord.x-0.5) + (gl_FragCoord.y-0.5)*512.0)/iSampleRate;

   // Get the 2 values for left and right channels
   vec2 y = mainSound( t );

   // convert them from -1 to 1 to 0 to 65536
   vec2 v  = floor((0.5+0.5*y)*65536.0);

   // separate them into low and high bytes
   vec2 vl = mod(v,256.0)/255.0;
   vec2 vh = floor(v/256.0)/255.0;

   // write them out where
   // RED   = channel 0 low byte
   // GREEN = channel 0 high byte
   // BLUE  = channel 1 low byte
   // ALPHA = channel 2 high byte
   gl_FragColor = vec4(vl.x,vh.x,vl.y,vh.y);
}

This points out one advantage to using WebGL in this particular case is that you get all the same inputs to the audio shader as the fragment shaders (since it is a fragment shader). That means for example the audio shader could reference up to 4 textures
In JavaScript then you'd read the texture with gl.readPixels then convert the sample back into floats with something like
   var pixels = new Uint8Array(width * height * 4);
   gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
   for (var sample = 0; sample < numSamples; ++sample) {
     var offset = sample * 4;  // RGBA
     audioData[sample * 2    ] = backToFloat(pixels[offset + 0], pixels[offset + 1]);
     audioData[sample * 2 + 1] = backToFloat(pixels[offset + 2], pixels[offset + 3]);
   }

   float backToFloat(low, high) {
     // convert back to 0 to 65536
     var value = low + high * 256;

     // convert from 0 to 65536 to -1 to 1
     return value / 32768 - 1;
   }

Also, while I said above I didn't think it was a good idea I assumed that shadertoy was constantly calling the audio shader and therefore the issue I brought up about blocking processing would be true but, ... apparently shadertoy just pre-generates N seconds of audio using the shader when you press play where N is apparently 60 seconds. So, there's no blocking but then again the sound only lasts 60 seconds.


text:
Q: Prove that a Truncated Gaussian is log-concave Is the truncated Gaussian a log-concave distribution?
I read here at Section 2.2.5 that whatever log-concave truncated distribution (and hence also Gaussian) is log-concave and the proof is trivial. How to prove this statement?

A: the density of a truncated rv is the following
$$f_{X|X>c}=\frac{1}{1-F_X(c)}f_X(x)$$
This prove your statement

Proof of the truncated density
Let's$X$ a rv (assuming it is continuous) with CDF $F_X(x)$ and let $B=\{X>c\}$
Thus, by definition
$$F(x|B)=\frac{\mathbb{P}[c<X<x]}{\mathbb{P}[X>c]}=\frac{F_X(x)-F_X(c)}{1-F_X(c)}$$
if $x>c$ and zero  if $x\leq c$
derivating F you get the density I showed before


text:
Q: Why when I instantiate a class extending Activity and calling a method that uses openFileInput I get null pointer exception? Hello I am trying to call a method (fileReader) that is using openFileInput(filename) from another class.
I am doing some processing in a class which extends BroadcastReceiver, and I need to read a file, I can't call openFileInput() inside of this class, so I have created a helper class which extends Activity or IntentService (tried both) so that I can instantiate it and call it like that:
    HelperClass hc = new HelperClass();
    hc.fileReader();

I get a NullPointerException on the line in fileReader where openFileInput is Called.
In my opinion it has to do something with the context or teh constructor not being properly initialized, its just HelperClass(){super();} .
How can I over come this?

A: When you are calling openFileInput you are trying to open a file associated with the given context. Since you are instantiating your HelperClass without supplying it a Context, it is trying to open your file using a null context (Hence your null pointer exception). What you can do is make your method fileReader() accept a Context object and then call openFileInput using the provider context.
Ex.
public void fileReader(Context context) //change the return type if you need
{
  //your code
  //..

  FileInputStream fos = context.openFileInput(filename);
}

To call it
hc.fileReader(context); //get the context using "this" or getContext() depending on where you're calling it

Alternatively, you can make fileReader a static method so you do not need to create an instance of HelperClass just to use it.
public static void fileReader(Context context) //change the return type if you need
{
      //your code
      //..

      FileInputStream fos = context.openFileInput(filename);
}

Then call it using
HelperClass.fileReader(context);


text:
Q: how to catch an exception and modify with an error custom dialog i have already this exception in my app but i want to create a custom dialog
heres my exception:
10-11 01:41:49.420: E/AACPlayer(649): playAsync():
10-11 01:41:49.420: E/AACPlayer(649): java.lang.RuntimeException:
Cannot start native decoder

and instead of show this java.lang.RuntimeException: Cannot start native decoder to person, show like Error!! stream is down.
i tried something like this:
 try
        {
            aacPlayer.playAsync( getUrl());
        }
        catch(Exception e)
        {
            AlertDialog alertDialog = new AlertDialog.Builder(Activity.this).create();
            alertDialog.setTitle("Error in radio");
            alertDialog.setMessage("out of service");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
                  // here you can add functions
               }
            });
            alertDialog.setIcon(R.drawable.icon);
            alertDialog.show();
        }

but without luck it doesnt shows the custom dialog what can recommend me for this?
thanks very much.

A: See it, maybe it can help you ;)
How to catch a 'java.lang.RuntimeException' or Throwing and Catching Exceptions

A: Will it work if the there is a custom message in the dialog that already pops up? If yes then you may want to do this in your catch block:
CustomException ce = new CustomException();
throw ce;

And have a custom exception like this
public static class CustomException extends Exception {

    String errorMsg; // this is the string that the your alert box will show

    public CustomException() {
        super();
        errorMsg = "YOU DID THIS ALL"; // set string here for your custom message
    }

    public CustomException(String err) { // set custom string in the constructor itself
        super(err);
        errorMsg = err;
    }

    public String getError() {
        return errorMsg;
    }

    public String toString() {
        return errorMsg;
    }
}


text:
Q: The constructor JSONArray(Object[]) is undefined I just get this api class from the internet now i am integrating in my project everything is working fine but only getting one error is that constructor JSONArray is undefined .
private void fireEvent(mEvent event, Object obj) {
    try {
        //Called for EVERY event.         //getting error here
        JSONArray arrayObj = obj instanceof JSONArray ? (JSONArray) obj : new JSONArray(new Object[] {obj});
        for (mEventListener listener : listeners) {
            listener.eventFired(this, event, arrayObj);
        }
        //Call the appropriate handler.
        switch (event) {
        case waiting:
            for (mEventListener listener : listeners) {
                listener.chatWaiting(this);
            }
            break;
        case connected:
            for (mEventListener listener : listeners) {
                listener.chatConnected(this);
            }
            break;

A: That constructor is only available from API19: JSONArray(Object array)
Therefore the most likely explanation is you are compiling against a lower API level.
You can use the collection constructor though, by passing a list:
JSONArray arrayObj = obj instanceof JSONArray
                      ? (JSONArray) obj
                      : new JSONArray(Arrays.asList(obj));


text:
Q: SQL: Count references to item in same table I have the following SQL table:
id     int(11) NOT NULL AUTO_INCREMENT,
name   varchar(200),
parent int(11),

This stores some structured information in a tree:

*

*"id" is the primary (uniq) key of the entries

*"name" is some string

*"parent" is the "id" of the parent entry (0: root element)

A sample table could be:
id name              parent
--+-----------------+----------------
1  root_a             0
2  root_b             0
3  sub_b1             2
4  sub_sub_b1_1       3
5  sub_sub_b1_2       3

This could be a directory with folder ("root_"), sub-folder ("sub_"), sub-sub-folder ("sub_sub_*"), ...
Now I would like to have a SQL query, that returns for each entry how many child entries there are:
SELECT id,name,count(....) as child_count FROM table WHERE ...

For the example table this query shall return:
 id  name         child_count
 --+--------------+---------
 1  root_a         0
 2  root_b         1
 3  sub_b1         2
 4  sub_sub_b1_1   0
 5  sub_sub_b1_2   0

How to perform such a count inside the same table?
Thanks

A: How about a correlated subquery?
select t.*,
       (select count(*)
        from t t2
        where t2.parent = t.id
       ) as child_count
from t;

A: with qry1 as (
    select      parent,
                count(*) as child_count
    from        table
    group by    parent
)
select      table.id,
            table.name,
            isnull(qry1.child_count, 0) as child_count
from        table
left join   qry1
on          table.id = qry1.parent
order by    table.id

Note: Left Join. Inner join would exclude rows with no children.


text:
Q: How to get mapStateToProps value from a function to class component I using react to develop a web application.
Requirement:
My requirement is, i have a function component which will content my mapStateToProps function and i will call that function component from my class component.So that my repetition of the code will get reduce.
Problem:
Now the problem with this is, when i write the mapStateToProps in my function component and then i call it from my class component it dose't get executed
class: A.js
import React, { Component } from 'react'
import b from './B'

export class A extends Component {

    submit = () => {
        b();
    }
    render() {
        return (
            <div>
                <Button onClick={this.submit}>Submit</Button>
            </div>
        )
    }
}

export default A

functional Component: B.js
import { connect } from "react-redux";

const b = () => {
    let data = {
        name = props.details.name
    }
    return data;
}

const mapStateToProps = (state) => {
    return {
        name: state.detailReducer.name
    }
}
export default connect(mapStateToProps)(b);

Help:
So can any one help me how i can achieve this requirement. It will be very helpful.
And also please tell me is it a good way to call the mapStateToProps from the other function compoent.

A: You have to distinguish functions and function components. In your Component A you are using b as a function, although it should be be a function component. That you cannot do. A function component is meant being rendered not executed.
Also to make b an actual function component, b is missing props in the argument list and it should be props.name instead of props.details.name and it needs to return JSX. And finally it should called B.


text:
Q: Dual-screen beamer and zoom conferencing I have made a beamer presentation for my Zoom conference. Is there a way I can share only the slides and not my notes using zoom platform? I plan to open the slides with the Dual-Screen PDF viewer.

A: When you choose to "share" in a Zoom session, you should be given an option of sharing a single window or sharing an entire screen/desktop.
Use one of the tools specified in existing questions/answers like mine, How to share a beamer PDF by teleconference (Zoom/etc) using the "show notes on second screen" option?, or this one, Is there a specialized Pdf viewer for Latex-Beamer presentations on Linux?
These can display the audience material and the presenter material separately, each in windows that can be sized and moved around.  So perfect for zoom.


text:
Q: How to end function in Python I am fiddling with some code i received from the CSGO reddit to implement a bomb timer using the game state integration that was just released, i have managed to make the code work with a HTTP Post JSON as shown below:
import time
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import sys
import json
import signal

PORT = 3000
planted = False

#If we ctrl+C out of python, make sure we close the serial port first
#handler catches and closes it
def signal_handler(signal, frame):
    ser.close()
    sys.exit(0)

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    #SimpleHTTPServer doesn't handle post by default. Hacked up way to do it here
    def do_POST(self):
        length = int(self.headers["Content-Length"])
        jsonString = str(self.rfile.read(length))
        print jsonString
        print "---"
        jsonDict = json.loads(jsonString)
        #From here we have a JSON dict, that has whatever data CS is sending

        #For the timer, all we care about is the the 'round' key

        if 'round' in jsonDict:
            rounds = jsonDict['round']
            if 'bomb' in rounds:
                if rounds['bomb'] == "planted":
                    planted = True
                    print "Bomb has been planted"

                    #timer code here

                    def main():
                        x = 10
                        for i in range(x + 1):
                            time.sleep(1)
                            print(formatTime(x))
                            x -= 1
                    def formatTime(x):
                        minutes = int(x / 60)
                        seconds_rem = int(x % 60)
                        if (seconds_rem < 10):
                            return(str(minutes) + ":0" + str(seconds_rem))
                        else:
                            return(str(minutes) + ":" + str(seconds_rem))
                    main()

                #If bomb has been defused, then send the 'C' message
                if rounds['bomb'] == "defused":
                    planted = False
                    print "bomb has been defused"

                #if the round ends, either bomb exploded or everyone died.
                #Send the 'C' message to stop timer.
                if 'previously' in jsonDict:
                    if 'round' in jsonDict['previously']:
                        if 'bomb' in jsonDict['previously']['round']:
                            planted = False
                            print "Round ran out"

        #not sure if a response is really required. Send it anyway
        response = bytes("This is the response.") #create response

        self.send_response(200) #create header
        self.send_header("Content-Length", str(len(response)))
        self.end_headers()
        self.wfile.write(response) #send response

Handler = ServerHandler
#On windows, Serial ports are usually COM1-3
#On mac/linux this will be different
#Set up our handler for ctrl+c
signal.signal(signal.SIGINT, signal_handler)

#Start server
httpd = SocketServer.TCPServer(("", PORT), Handler)

#Run server
httpd.serve_forever()

however, this part of the code:
def main():
    x = 10
    for i in range(x + 1):
        time.sleep(1)
        print(formatTime(x))
        x -= 1
def formatTime(x):
    minutes = int(x / 60)
    seconds_rem = int(x % 60)
    if (seconds_rem < 10):
        return(str(minutes) + ":0" + str(seconds_rem))
    else:
        return(str(minutes) + ":" + str(seconds_rem))
main()

runs itself twice  as shown in the python shell logs, and it says that the bomb has been planted even though the round as already ended completely, was wondering if anyone has any idea why it would run itself twice.


text:
Q: Typo3 - How to add dynamic value in TCA MM table I'm trying to add a column to the relation table (MM table) in Typo3. Let's say I have my tables user, wanted_car and wanted_car_mm which is my relation table. So in wanted_car_mm I'll know what user want which car, but I want to add the column need_faster in wanted_car_mm, which is a boolean, that tells me who should have it faster. A lot of users could need it faster, there's no order.
How do I add this column, map the value and correctly retrieve this information when I get all my users?
I currently have this in my TCA config for user:
'wanted_cars' => array(
    'exclude' => 1,
    'label' => 'LLL:EXT:caa_my_plugin/Resources/Private/Language/locallang_db.xlf:my_title',
    'l10n_mode' => 'exclude',
    'config' => array(
        'type' => 'select',
        'foreign_table' => 'wanted_car',
        'MM' => 'wanted_car_mm',
        'MM_insert_fields' => array('need_faster' => '???'),
        'MM_table_where' => ' AND wanted_car_mm.need_faster = ???',
        'maxitems' => 9999,
        'multiple' => 0,
        'renderType' => 'selectCheckBox',
    ),
),

I feel like this is how I should add the column and retrieve it correctly, but I have no clue how to map the correct value.. that I should also put in my where clause.. I don't know how this can be possible going like this, but I can't find any other way of doing it.
The value must be specified when creating a user.

A: You need an intermediate table for that. The full docs for that can be found on https://docs.typo3.org/m/typo3/reference-tca/master/en-us/ColumnsConfig/Type/Inline.html
a screenshot and old example which still should work can also be found on https://wiki.typo3.org/Inline_Relational_Record_Editing_Attributes


text:
Q: How to dynamically pass the property in Spring FTP Outboud channel context xml The FTPapplicationContext.xml has the configuration to create the beans for FTPchannel. here it takes the property values from the application.proprty. Now my question is how to dynamically set the property while on the run time.
Context.xml:

<bean id="ftpClientFactory" class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
    <property name="host" value="${host}"/>
    <property name="port" value="${availableServerPort}"/>
    <property name="username" value="${userid}"/>
    <property name="password" value="${password}"/>
</bean>

<int:channel id="ftpChannel"/>

<int-ftp:outbound-channel-adapter  id="ftpOutbound"
            channel="ftpChannel"
            remote-directory="/temp"
            session-factory="ftpClientFactory">
    <int-ftp:request-handler-advice-chain>
        <int:retry-advice />
    </int-ftp:request-handler-advice-chain>
</int-ftp:outbound-channel-adapter>

application.prperties:
userid=Administrator
password=password
availableServerPort=21
host=Testfar

FTP code:
ConfigurableApplicationContext context =
          new FileSystemXmlApplicationContext("context.xml");

 MessageChannel ftpChannel = context.getBean("ftpChannel",MessageChannel.class);
  File file1 = new File("test.txt");
  Message<File> fileMessage = MessageBuilder.withPayload(file1).build();
  ftpChannel.send(fileMessage);
  context.close();

In application.properiites file, I can setup a default host address but Here I need to pass the host address dynamically based on the user input. Could you please advice me on how to achieve that. It would be great If you suggest/provide some ideas.