text:
Q: Search button to activate autocomplete googl maps places (React.js) I am using AutoComplete button from material/ui for searching Google Maps Places. Everything is working properly so when user clicks on the one offered field in autocomplete it leads him to next page.
My question is: is it possible to add search button to active autocomplete if user clicks on button?
Here is code for autocomplete and I have added button but still nothing happens if someone clicks on it.
<div className="search">
        <Autocomplete
          id="google-map-demo"
          key={reset}
          ListboxProps={{ style: { maxHeight: 400, overflow: 'auto',fontSize:'0.7rem' } }}
          getOptionLabel={(option) =>
            typeof option === "string" ? option : option.description
          }

          filterOptions={(x) => x}
          options={options}
          onChange={(e, l) => {
            customer.setMyaddress(l.description);
            getMyDestination(l.place_id);
          }}
          renderInput={(params) => (
            <TextField

              {...params}
              className={classes.root}
              variant="standard"
              fullWidth
              onChange={(e, v) => {
                setInputValue(e.target.value);
              }}
            />
          )}
          renderOption={(option) => {
            const matches =
              option.structured_formatting.main_text_matched_substrings;
            const parts = parse(
              option.structured_formatting.main_text,
              matches.map((match) => [
                match.offset,
                match.offset + match.length,
              ])
            );

            return (
              <Grid container alignItems="center">
                <Grid item>
                  <LocationOnIcon className={classes.icon} />
                </Grid>
                <Grid item xs>
                  {parts.map((part, index) => (
                    <span
                      key={index}
                      style={{ fontWeight: part.highlight ? 700 : 400 }}
                    >
                      {part.text}
                    </span>
                  ))}

                  <Typography variant="body2" color="red" className={classes.noOptions} >
                    {option.structured_formatting.secondary_text}
                  </Typography>
                </Grid>
              </Grid>
            );
          }}
        />
                <button className="btn btn-primary" style={{position: "absolute",
    right: "0"}}
              onClick={(e, v) => {
                setInputValue(e.target.value);
              }}>Find</button>
</div>

Anyone has idea how to fix this so when clicked on button I got same result as clicked on autocomplete field?
Thank you

A: you use the open prop which is in the Autocomplete , i've forked the  Autocomplete example from material-ui check it out:
https://codesandbox.io/s/material-demo-forked-3n5lw?file=/demo.js


text:
Q: Yii2 get role of the logged in user Can someone please explain to me how to use this function
getRoleByUser()

for related tables to get role of logged in user
I tried this
$Role = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
    print_r($Role);
    exit();

but I got the following error
Getting unknown property: yii\web\Application::findByUsername

A: Try this
\Yii::$app->authManager->getRolesByUser($user_id);

From the auth manager you can get it.

A: use
$userRole = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());

like
if ($userRole) {

  foreach ($userRole as $role) {
     $roles[] = $role->name;
  }

  // if user have 1 role then $userRole will be a string containing it
  // othewhise let $userRole be an array containing them all

   $userRole = count($roles) === 1 ? $roles[0] : $roles ;
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: \RequirePackage within \if\else\fi Why does the package iftex have to be loaded outside of a \if...\else\fi structure?
(The same goes for packages ifpdf, ifluatex, ifxetex.)
Consider:
\documentclass{myclass}\begin{document}\end{document}

This works:
i.e., when \RequirePackage{iftex} is outside of \ifodt\else\fi
\NeedsTeXFormat{LaTeX2e}[1996/06/01]
\ProvidesClass{myclass}[2013/12/15 v0.1 My Class]
\LoadClass{article}
\newif\ifodt\odttrue

\RequirePackage{iftex}
\ifodt
 \RequirePackage[utf8]{inputenc}
 \RequirePackage[T1]  {fontenc}
\else
 \ifLuaTeX\RequirePackage{fontspec}\fi
 \ifXeTeX \RequirePackage{fontspec}\fi
 \ifPDFTeX \RequirePackage[utf8]{inputenc}
           \RequirePackage[T1]  {fontenc}\fi
\fi

But not this:
i.e., when\RequirePackage{iftex} is within \ifodt\else\fi
\NeedsTeXFormat{LaTeX2e}[1996/06/01]
\ProvidesClass{myclass}[2013/12/15 v0.1 My Class]
\LoadClass{article}
\newif\ifodt\odttrue

\ifodt
 \RequirePackage[utf8]{inputenc}
 \RequirePackage[T1]  {fontenc}
\else
 \RequirePackage{iftex}
 \ifLuaTeX\RequirePackage{fontspec}\fi
 \ifXeTeX \RequirePackage{fontspec}\fi
 \ifPDFTeX \RequirePackage[utf8]{inputenc}
           \RequirePackage[T1]  {fontenc}\fi
\fi

Error:
! Undefined control sequence.
l.12      \ifXeTeX
                   \RequirePackage{fontspec}\fi
?

A: In your \else branch you have
\else
 \RequirePackage{iftex}
 \ifLuaTeX\RequirePackage{fontspec}\fi
 \ifXeTeX \RequirePackage{fontspec}\fi

Now \ifXeTeX is an undefined command which is OK as this is being skipped but the \fi is \fi so terminates the outer \ifodt and things go wrong. Never define conditionals within a TeX primitive \if.. as this always happens:-)

A: You have to delay the conditionals when (and if) the iftex package has been loaded.
\NeedsTeXFormat{LaTeX2e}[1996/06/01]
\ProvidesClass{myclass}[2013/12/15 v0.1 My Class]

\newif\ifodt
\DeclareOption{odt}{\odttrue}
\ProcessOptions\relax

\LoadClass{article}

\ifodt
  \RequirePackage[utf8]{inputenc}
  \RequirePackage[T1]  {fontenc}
  \expandafter\@gobble
\else
  \RequirePackage{iftex}
  \expandafter\@firstofone
\fi
 {\ifLuaTeX
    \RequirePackage{fontspec}
  \fi
  \ifXeTeX
    \RequirePackage{fontspec}
  \fi
  \ifPDFTeX
    \RequirePackage[utf8]{inputenc}
    \RequirePackage[T1]{fontenc}
  \fi}

When \ifodt is true, the part in braces is gobbled, while if it is false, it's evaluated; since iftex has already been loaded, the conditionals will be defined and so matched with the corresponding \fi.
There should be a better control, though, because when
 \documentclass[odt]{myclass}

is found and LuaLaTeX or XeLaTeX are used, the packages inputenc and fontenc would be loaded, which is discouraged.


text:
Q: Is there a way to run two programs simultaneously in C and records the output I have two programs in C almost the same (with a little different) and I have (key/value) dictionary in another C file
The following steps are done for both programs
compile the first program
gcc file1.c dict.c

compile the second program
gcc file2.c dict.c

and inside the file.c I called both functions update(to fill the dictionary) and printDic (to print the content of dictionary)
//file1.c
int func(int w){
  update("w",w)
  if ((w >= w) && ((w % w) == 0))
  {
    w= w*4
    update("w",w)
    printDic();
  }
  else
  {
    w=1;
    update("w",w)
    printDic();
  }
  return 0; }

//file2.c
int func(int w){
  update("w",w)
  if ((w >= 4) && ((w / w) == 0))
  {
    w = w/2;
    update("w",w)
    printDic();

  }
  else
  {
    w=0;
    update("w",w)
    printDic();
  }
  return 0; }

and both files have the same main
//main
 int main(int argc, char *argv[]){
     func(10);
     func(5);
     func(2);
     func(0);
     func(180);

    return 0; }

So, the update() will fill the dictionary with the values of w once they change and then print them.
Is there a way to run these two files with the dictionary at once, in order to compare the output e.g. if I pass 10 in both programs will end up with a different value of w (which is stored in the dictionary).
Note: I need to call the func many times and in the same file I don't want to run the program each time with only one call.
the dictionary is working very well with one file and in each call to func the value of w is append to txt file.

A: you can use the threading to achieve your goal, for example:
#include "pthread.h"
#include <stdio.h>

#define bool int
#define true 1
#define false 0
#define thread pthread_t
#define thread_fire pthread_create
#define thread_wait pthread_exit

int get_mul(int num, bool even)
{
    if (even)
        return (2 * num);
    else
        return ((2 * num) + 1);
}

void* func_odd(void *arg)
{
    int num =  *((int *)arg);
    printf("%s: [%d]\n", __func__, get_mul(num, false));

    return NULL;
}

void* func_even(void *arg)
{
    int num = *((int *)arg);
    printf("%s: [%d]\n", __func__, get_mul(num, true));

    return NULL;
}

void func(int num)
{
    thread tid;
    thread_fire(&tid, NULL, func_odd,  (void *)&num);
    thread_fire(&tid, NULL, func_even, (void *)&num);
    thread_wait(NULL);
}

int main(int argc, char **argv)
{
    int i, num = atoi(argv[1]);

    func(num);

    return 0;
}

**compiling:**
gcc -g -c thread.c
gcc -o thread thread.o -lpthread

**Output:**
./thread 3
func_odd: [7]
func_even: [6]

In above example, replace func_odd() and func_even() with your two functions (with same name) defined in two different files.
For example, you can call "func_odd" to "func_file1", and "fund_even" to "func_file2".
Power of multithreading!!!!


text:
Q: Python - Looking for a solution to prevent duplicates in lists generated via text file As the title mentions, I'm looking for a way for my code to not only detect duplicates in a list, but to separate the items, moving them to other lists.
I am relatively new at programming, having just finished an introductory course to python at my local JC. During the course of the semester, I had an idea to create a program that would read lines in a .txt file, place them in a list, shuffle the list, and split the single list into two new lists before printing them. This would be used for quickly distributing uniquely named objects to two players in a game, for example. Here is what the code looks like so far:
Given that list.txt = apple, apple, banana, pear, orange, kiwi
import random
#create list from text file
list = [line.strip() for line in open("list.txt", 'r')]

#Copy list to preserve the original
list2 = list[::]
random.shuffle(list2) #shuffle the order

#If # of items = odd, remove one
if len(list2) % 2 == 1:
    del list2[-1]

#Divide items into two lists
A = list2[:len(list2)//2]
B = list2[len(list2)//2:]

print("The items in group A are: ", A)
print("The items in group B are: ", B)

I've gotten everything to work so far, but something I want to implement is having the program detect if, say, both "apple"'s are in list A and, if they are, move one to list B. I've come up with three solutions, but not one of them works. Solution 1 would be to take the two "apple"'s as they are and detect/sort from there.
def moveDuplicates(in_list):
    unique = set(in_list)
    for each in unique:
        count = in_list.count(each)
        if count > 1:
            return True
        else:
            return False

The problem is that I can detect duplicates just fine like this, but I don't know how to specify moving one of them since I won't know the position of either in the new lists, since it's shuffled every time.
Solution 2 is to rename the "apple"s to apple1 and apple2, or something similar. With this solution, I can choose to delete and append either item easily, but I don't know how to get the program to detect that two items with sequential numbers are in the same list.
Solution 3 is the worst one imo, since it involves writing conditions for every potential duplicate to make sure before the shuffle that one of each would be placed in each list, which violates DRY principles.
I feel that the most ideal solution would be to use solution 2 or 3 while somehow using something similar to how google uses asterisks in searches to denote that anything can be in place of the asterisk.

A: I'm assuming if you have more than 2 copies of any word, you can ignore everything after the first two. My suggested solution splits the list into repeated values, which will be shared by both groups and single values, which will be shuffled and split among the two groups.
import collections

list = ['a', 'a', 'a', 'b', 'b', 'c', 'd']

# Split the list into words that occur once and ones that are repeats
single = []
repeats = []
for word, count in collections.Counter(list).items():
    if count > 1:
        repeats.append(word)
    else:
        single.append(word)

# Each group gets a copy of the repeats
group_a = repeats[:]
group_b = repeats[:]

# Now shuffle/divide the single values
random.shuffle(single)
half = len(single) // 2
group_a.extend(single[:half])
group_b.extend(single[half:2*half])

You could add additional shuffles for the individual groups, if you like.

A: How about just to use simple for-cycle? I will try to make it simple for you. If I understood your idea correctly then it can be implemented like this:
# Some input into this example
fruits = ["apple", "apple", "banana", "pear", "orange", "kiwi"]

# The code you're probably looking for
first_basket = []
second_basket = []

for fruit in fruits:
    if fruit not in first_basket:
         first_basket.append(fruit)
    elif fruit not in second_basket:
         second_basket.append(fruit)

print first_basket
print second_basket

So, if your first basket not contains fruit from fruits, it will be added to first_basket. Else if your second basket not contains fruit, it will be added to second_basket. So if both baskets already have fruit from your list it won't be added to any basket.
This example will print ["apple", "banana", "pear", "orange", "kiwi"] (this is your first_basket) and then ["apple"] (this is your second_basket).


text:
Q: Github, Github for Windows, on every commit generates us.stackdump Since I started using Github for managing my projects I receive dump file on every commit.
I am using
 a) GitHub (private repositories for my personal projects)
 b) GitHub for windows GitHub client

When I sync my commits after finish (or may be during commit) it generates "us.stackdump" file.
This is the file contents:
@@ -0,0 +1,18 @@
+MSYS-1.0.12 Build:2011-07-20 17:52
+Exception: STATUS_ACCESS_VIOLATION at eip=68085E34
+eax=68560000 ebx=000073CC ecx=00001CF3 edx=00000000 esi=00000000 edi=68560000
+ebp=0028FE48 esp=0028FE3C program=us
+cs=0023 ds=002B es=002B fs=0053 gs=002B ss=002B
+Stack trace:
+Frame     Function  Args
+0028FE48  68085E34  (68560000, 00000000, 000073CC, 00000004)
+0028FE98  68001CB0  (00442D24, 00000001, 0028FEE8, 680044EA)
+0028FEE8  680045C7  (00000000, 00000000, 0028FF28, 0040C1AC)
+0028FF08  68004C5F  (00401A40, 00000000, 00000000, 00000000)
+0028FF28  68004C98  (00000000, 00000000, 00000000, 00000000)
+0028FF58  0040C0BC  (00401A40, 00000000, 00000000, 00000000)
+0028FF88  0040103D  (7EFDE000, 0028FFD4, 77C69EF2, 7EFDE000)
+0028FF94  76AC33AA  (7EFDE000, 772F991B, 00000000, 00000000)
+0028FFD4  77C69EF2  (00401000, 7EFDE000, 00000000, 00000000)
+0028FFEC  77C69EC5  (00401000, 7EFDE000, 00000000, 78746341)
+End of stack trace

A: This is similar to the msysgit issue (in progress) 25, with one only suggestion for now:

replace msys-1.0.dll by a new one in "documents and settings\administrator\local setting\application data\github\portablegit_xxxx..."

Try first to commit with the msysgit included in GitHub for Windows, and see if the issue persists.
Launch a session through
C:\Users\YourUsername\AppData\Local\GitHub\PortableGit_93...\git-cmd.bat

Or through the icon "Git Shell", which launches:
C:\Users\YourUsername\AppData\Local\GitHub\GitHub.appref-ms --open-shell

A: VonC's answer didn't work for me but along the same lines:

*

*Download MSYS

*Copy the whole MSYS bin directory into the Git bin directory.


text:
Q: Code formatter doesn't working in Eclipse I'm need setting in Eclipse width of line and select "use modifier "final" where possible".  I go to Windows->Preferences->Java->Code Style->Clean Up. Press Edit, in the tab Code Style selected "Use modifier "final" where possible". Wrote a new profile name. Apply->Ok.
Then go to Windows-Preferences-Java-Code Style-Formatter. Press Edit, in tab Line Wrapping, in field "Maximum line width" wrote 180.Wrote a new profile name. Apply->Ok.
Before this actions close the Preferences window and press Ctrl+Shift+F, but unfortunately the settings of edditing not changed.Restart of Eclipse not help. I'm using the Eclipse luna. Help me please. Can I do something wrong?


text:
Q: The number of ways in which 45000 can be expressed as product of 3 Co- primes? The number of ways in which 45000 can be expressed as product of 3 Co- primes ?

A: That slightly depends on whether you regard $1$ as coprime with itself, which would allow $(1,1,45000)$. Otherwise the distinct prime factors of $45000=2^3\cdot 3^2\cdot 5^4$ are $2,3,5$ and none of these can occur in more than one factor if those factors are to be coprime. So we can have each prime represented in separate factors,  $(8,9,625)$, or we can include two of the prime-power factors in one factor and take $1$ as a factor: $(1,72,625)$, and two more.

A: Hint:
Not many, as $45,000$ has only $3$ prime divisors.

A: $45000=2^3\cdot 3^2\cdot 5^4$
Case 1
$1, \text{(factor consisting one of } 2^3,3^2,5^4), \text{(last factor)}$

Count: $\dbinom{3}{1}$

Case 2
$1, \text{(factor consisting two of } 2^3,3^2,5^4), \text{(last factor)}$

Count: $\dbinom{3}{2}$

Case 3
$1, \text{(factor consisting all the three of } 2^3,3^2,5^4), \text{(last factor)}$

Count: $\dbinom{3}{3}$

Case 4
$\text{(factor consisting one of } 2^3,3^2,5^4), \text{(factor consisting one of } 2^3,3^2,5^4), \text{(last factor)}$

Count: $\dbinom{3}{2}$

Required count: $10$


text:
Q: Trouble POSTing multiple related objects at once to api created with django rest framework I'm making a ToDo app but having difficulties getting the api to allow a user to create a new list with multiple items via one api call.  Each list belongs to a specific "room".
I get 400 Bad Request.  If I leave the 'todo_items' off the POST data it works fine to create the ToDoList object.
Also, if I remove "user" from the Meta fields attribute for the CreateToDoItemSerializer, it'll create both the ToDoList object and the ToDoItem objects, but the "content" for each ToDoItem will be an empty string.  Inside the create method of NewToDoListSerializer, the validated_data is returning a list of empty OrderedDict() objects for the key "todo_items".  I'm not sure what to make of that.
my models:
class Room(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    slug = models.SlugField(max_length=255, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="rooms")

class ToDoList(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, blank=True)
    room = models.ForeignKey(Room, related_name="todo_lists")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="todo_lists")

class ToDoItem(models.Model):
    todo_list = models.ForeignKey(ToDoList, related_name="todo_items")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="replies")
    content = FroalaField(options={'placeholder': '''Just start writing...
                                                 Highlight any text to bring up the editor.'''})

my serializers
class CreateTodoItemSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(many=False, read_only=False, queryset=User.objects.all())

    class Meta:
        model = ToDoItem
        fields = ['pk', 'user', 'content']

    def create(self, validated_data):
        reply = ToDo.objects.create(**validated_data)

class NewToDoListSerializer(serializers.ModelSerializer):
    room = serializers.PrimaryKeyRelatedField(many=False, read_only=False, queryset=Room.objects.all())
    user = UserSerializer(read_only=True)
    todo_items = CreateTodoItemSerializer(many=True, read_only=False)

    class Meta:
        model = ToDoList
        fields = ['pk', 'slug', 'title', 'user', 'room', 'todo_items']
        lookup_field = "slug"
        depth = 1

    def create(self, validated_data):
        todo_items_data = validated_data.pop('todo_items')
        todo_list = ToDoList.objects.create(**validated_data)
        for todo_item_data in todo_items_data:
            todo_item = ToDo.objects.create(user=todo_list.user, todo_list=todo_list, **todo_item_data)

my viewset (the relevant bits):
class ToDoListViewSet(viewsets.ModelViewSet):
    queryset = ToDoList.objects.all()
    serializer_class = ToDoListSerializer
    authentication_classes = [TokenAuthentication, SessionAuthentication]
    permission_classes = [IsAuthenticated]
    renderer_classes = (renderers.TemplateHTMLRenderer, renderers.JSONRenderer, renderers.BrowsableAPIRenderer)
    template_name = "react_base.html"
    lookup_field = "slug"

def create(self, request, **kwargs):
    self.serializer_class = NewToDoListSerializer
    return super(ToDoListViewSet, self).create(request, **kwargs)

def perform_create(self, serializer):
    instance = serializer.save(user=self.request.user)

the data I'm POSTing:
todoListTitle, todoItemContent, moreTodoItemContent are all strings.  this.props.room.pk is an integer.  this.props.csrfmiddlewaretoken is the csrfmiddlewaretoken
var newToDoListData = {
        "room": this.props.room.pk,
        "title": todoListTitle,
        "todo_items": [{"content": todoItemContent}, {"content": moreTodoItemContent}],
        "csrfmiddlewaretoken": this.props.csrfmiddlewaretoken
    };

A: You need to make the todo_items in your serializer required = false. I am not sure I understand what your second issue is.
class NewToDoListSerializer(serializers.ModelSerializer):
room = serializers.PrimaryKeyRelatedField(many=False, read_only=False, queryset=Room.objects.all())
user = UserSerializer(read_only=True)
todo_items = CreateTodoItemSerializer(many=True, required=False)

class Meta:
    model = ToDoList
    fields = ['pk', 'slug', 'title', 'user', 'room', 'todo_items']
    lookup_field = "slug"
    depth = 1

def create(self, validated_data):
    todo_items_data = validated_data.pop('todo_items')
    todo_list = ToDoList.objects.create(**validated_data)
    for todo_item_data in todo_items_data:
        todo_item = ToDo.objects.create(user=todo_list.user, todo_list=todo_list, **todo_item_data)


text:
Q: nginx: trying to enable https results in 'This webpage has a redirect loop' In my nginx configuration, if I have the following setup, whenever i go to the site i get 'This webpage has a redirect loop'
server {
    listen 80;
    merge_slashes off;
    server_name domain.com www.domain.com
    rewrite ^(.*) https://$host$1 permanent;
}

server {
     listen 443;
     merge_slashes off;
     server_name domain.com www.domain.com;

     location / { try_files $uri @app; }
       location @app {
          include uwsgi_params;
          uwsgi_pass 0.0.0.0:5002;
     }
}

A: Try to add:
ssl on;
ssl_certificate      /xxx/bundle.pem;
ssl_certificate_key  /xxx/server.key;


text:
Q: A2 on four A4 pages? | Convert A4 PDF to "A2 on four A4" PDF? Given e.g. pdf (in any size) how to enlarge it to A2 size and print on four A4 pages?
(if possible it would be great if pdf having multiple pages we could split like this, so if there is pdf with posters to print multiple at once)
(of course command line solutions proffered ;) )

A: Starting from the pdf A2 format object, crop it with either pdftilecut or with pdfposter.

*

*See the pdftilecut github page for examples and source code, or consult the man page for pdftilecut once installed.

*If you decide to use pdfposter to tile your pdf file:
$ pdfposter -s4 infile.pdf outfile.pdf
Both solutions are cli.


text:
Q: infer byte size of JSON file stored in cassandra column for each row I'm querying a vendor's cassandra database to fetch data from a table. The data returned is a JSON file stored as text. I want to determine the average size of the json file in the cassandra table.
Also other stats like max size and min size for each partition.
Can we achieve the above requirement using SELECT+Aggregate functions queries?
Please suggest to get the desired output

A: nodetool tablestats will tell you the min/max/avg for the partitions in a given table.  nodetool tablehistograms will give you even finer grained information.


text:
Q: Getting error when I create variable outside the render method Why this does not work outside the render method
 class MyComponentClass extends React.Component{
        const n = Math.floor(Math.random()* 10 + 1);
        render(){
            return
The number is {n}

    }
}
ReactDOM.render(<MyComponentClass/>,document.getElementById("app"));

But it works inside?
 class MyComponentClass extends React.Component{
        render(){
            const n = Math.floor(Math.random()* 10 + 1);
            return
The number is {n}

    }
}
ReactDOM.render(<MyComponentClass/>,document.getElementById("app"));

A: Because in the first one you are defining a class property with a new proposal: class-fields You can't use const there. Try like this:
n = Math.floor(Math.random()* 10 + 1);

Then you can reach it via:
this.n

I don't know why this answer downvoted but with a proper setup, class-fields plugin like Babel, for example, we can use this.

class App extends React.Component {
  n = Math.floor(Math.random() * 10 + 1);
  render() {
    return
{this.n}
;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

This is not different other than initializing the property in the constructor without using class-fields proposal.

class App extends React.Component {
  constructor( props ) {
    super( props );
    this.n = Math.floor(Math.random() * 10 + 1);
  }

  render() {
    return
{this.n}
;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));


text:
Q: Настройка отображения блоков Цель: Мне нужно чтобы блоки красиво и ровно размещались внутри родительского. Как на скриншоте

Я же имею ситуацию где блоки растягивают родительский по высоте и не умещаются друг с другом как будто им не хватает ширины.
.left-box
float: left;
width: 35%;
text-align: left;
max-width: 100%;

.left-box.profile-details
width: 49%;
float: none;

.column2
float: right;
clear: right;
width: 49%;

Единственный вариант сейчас для меня добиться нужного мне отображения это поменять left-box details profile-details и column2 местами в html

Но в этом случае в мобильной версии блоки смешиваются друг с другом, а мне хотелось бы настроить css, чтобы отображалось ровно и не нужно было ничего менять в html.
Благодарю душевно за любые попытки помочь :)

A: Добавьте к каждому блоку свойство display: inline-block;


text:
Q: GatsbyJS Burger Menu close menu on AnchorLink click I have created a working burger menu in my Gatsby application using react-burger-menu. I am trying to get it so that when an AnchorLink in the burger is clicked, the Burger menu closes. I have tried doing <Menu isOpen={ false }> as suggested in the docs but not working. Any help?
This is my Burger menu code:
import React from "react"
import { slide as Menu } from "react-burger-menu"
import { AnchorLink } from "gatsby-plugin-anchor-links"

const Burger = () => {
  return (

      <Menu right isOpen={ false }>
        <AnchorLink to="/#about">About Me</AnchorLink>

        <AnchorLink to="/#experience">Experience</AnchorLink>

        <AnchorLink to="/#projects">Projects</AnchorLink>

        <AnchorLink to="/#contact">Contact</AnchorLink>

      </Menu>

  )
}

export default Burger

A: You can provide event handlers for Menu and AnchorLink and add a state menuOpen to close/open sidebar.
const Burger = () => {
  const [menuOpen, setMenuOpen] = React.useState(false)

  // This keeps your state in sync with the opening/closing of the menu
  // via the default means, e.g. clicking the X, pressing the ESC key etc.
  const handleStateChange = state => {
    setMenuOpen(state.isOpen)
  }

  // This can be used to close the menu, e.g. when a user clicks a menu item
  const closeMenu = () => {
    setMenuOpen(false)
  }

  return (

      <Menu
        right
        isOpen={menuOpen}
        onStateChange={state => handleStateChange(state)}
      >
        <AnchorLink
          to="/#about"
          onClick={() => {
            closeMenu()
          }}
        >
          About Me
        </AnchorLink>

        <AnchorLink
          to="/#experience"
          onClick={() => {
            closeMenu()
          }}
        >
          Experience
        </AnchorLink>

        <AnchorLink
          to="/#projects"
          onClick={() => {
            closeMenu()
          }}
        >
          Projects
        </AnchorLink>

        <AnchorLink
          to="/#contact"
          onClick={() => {
            closeMenu()
          }}
        >
          Contact
        </AnchorLink>
      </Menu>

  )
}


text:
Q: OLS regression for not normally distributed data? In a college course I try to measure the abnormal returns (the returns that are below or over the returns of the market) of a companies stock after a specific event based on linear OLS regression. When interpreting the results with t-statistic and corresponding p-value, the professor of the course told me that these abnormal returns I observe have to be normally distributed. Otherwise the t-test would lead to miss specified results. If I am not mistaken, OLS assumes the normal distribution of the error terms. Unfortunately I don't really get why the effect I would like to observe has to be normally distributed in order to get unbiased results. What Problems arise when the data i observe are not normally distriuted? Do I have to work with approach in this case (not OLS regression)?
Thanks in advance

A: what you care about is the distribution of the sample mean of the errors.  This is where the central limit theorem helps, because even if your individual errors are not normally distributed, the mean of say 100 (ie the number of datapoints) of them will be.
the p-value is calculated based on an assumption that the (sample mean) of the underlying data is normally distributed, if its not, then you would have to use a different formula to calculate probability. [however, as I say, I don't believe it should be a problem, assuming your t-statistic is calculated from a large enough sample]


text:
Q: Unable to get the Chrome debugger to work via launch in Visual Studio Code for an Angular 8 project Upon upgrading Angular to version 8, I am now unable to run the Chrome debugger within Visual Studio Code.
I have not changed my launch.json which is similar to the following:
{
  "type": "chrome",
  "request": "launch",
  "name": "Launch Chrome (https)",
  "url": "https://myhost.domain.com:4200",
  "webRoot": "${workspaceFolder}"
},

I launch the Angular app via the following command
ng serve --host myhost.domain.com --ssl --disableHostCheck

This was working for a long time until the upgrade. I was able to launch Chrome and debug different components in Angular. Now all it does is state "Unverified Breakpoint"
I tried the following:

*

*Changing the webRoot folder location to different possible locations. I did notice that there is a new message on the output, when I serve the app. (https://myhost.domain.com:4200/webpack-dev-server/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: 404s will fallback to //index.html)

*Uninstalling and Reinstalling the Visual Studio Code Extension

*Adding SourceMap: true

*Creating a brand new Angular project using ng new test-project and attempting to debug this project and it does the same.

Here is what my package.json looks like:
{
  "name": "my-application",
  "version": "0.7.2",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.1.1",
    "@angular/cdk": "^8.1.0",
    "@angular/common": "^8.1.1",
    "@angular/compiler": "^8.1.1",
    "@angular/core": "^8.1.1",
    "@angular/forms": "^8.1.1",
    "@angular/material": "^8.1.0",
    "@angular/platform-browser": "^8.1.1",
    "@angular/platform-browser-dynamic": "^8.1.1",
    "@angular/router": "^8.1.1",
    "@datorama/akita": "^4.5.0",
    "angular-oauth2-oidc": "^5.0.2",
    "angular-pipes": "^9.0.2",
    "buffer": "^5.2.1",
    "chart.js": "^2.8.0",
    "core-js": "^3.1.4",
    "material-design-icons": "^3.0.1",
    "ng2-charts": "^2.3.0",
    "rxjs": "~6.5.2",
    "speed-measure-webpack-plugin": "^1.3.1",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.801.1",
    "@angular/cli": "^8.1.1",
    "@angular/compiler-cli": "^8.1.1",
    "@angular/language-service": "^8.1.1",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.6",
    "@types/node": "^12.6.3",
    "codelyzer": "^5.1.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.2.0",
    "karma-chrome-launcher": "~3.0.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.2",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "^3.4.5"
  }
}

Here is what ng version looks like:
Angular CLI: 8.1.1
Node: 10.15.0
OS: darwin x64
Angular: 8.1.1
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.801.1
@angular-devkit/build-angular     0.801.1
@angular-devkit/build-optimizer   0.801.1
@angular-devkit/build-webpack     0.801.1
@angular-devkit/core              7.3.9
@angular-devkit/schematics        7.3.9
@angular/cdk                      8.1.0
@angular/material                 8.1.0
@ngtools/webpack                  8.1.1
@schematics/angular               8.1.1
@schematics/update                0.801.1
rxjs                              6.5.2
typescript                        3.4.5
webpack                           4.35.2

A: The debugging launch.json and tasks.json configurations have changed for Angular 8 (both were recently updated July 2019)
You can find links and details for the most popular Debugging Recipes on the VSCode documentation site.
The specific one for Angular is on the vscode-recipies GitHub page:
https://github.com/Microsoft/vscode-recipes/tree/master/Angular-CLI
They change too often to make it worth while posting the full configs here, so just putting in the links


text:
Q: Handling moment objects out of scope I pass an array of moment objects in electron using ipc from main to the renderer, both include moment library, but when I try to call moment's functions on those objects in the renderer, it's like they're not moment objects anymore.
That's the object:

If I try to call format or other moment methods I get an error.
I'd rather not use the private fields in that object, so how can I make those objects be moment's objects again?
Edit:
This is how I pass the objects:
main.js: mainWindow.webContents.send('error-lines', errorLines);
Printing errorLines (part of it):
[ { id: '6',
    date: moment("2017-11-01T07:25:36.000"),
    start: false },
  { id: '5',
    date: moment("2017-11-01T08:01:40.000"),
    start: false },
  { id: '5', date: moment("2017-11-01T16:46:32.000"), start: true },
  { id: '6', date: moment("2017-11-01T17:11:11.000"), start: true },

renderer:
ipc.on('error-lines', function (event, data) {
    console.log(data);
}

A: electron's ipc between process does not allow non-serializable objects and only sends plain object over, so this is expected. You may send only plain object and reconstruct object on receiver process side to have full object you want.


text:
Q: Creating Javascript function called ReadName() I want to create a form which has a text entry box where a user can enter their name and then I want a button as well. But what I want this button to have a function called ReadName() where what will happen is when the user clicks on the button it will come up with a message saying "Hello user name will appear here
I have tried my self and but I don't think I am not getting what I want. Any help will be appreciated.
<form>
    <label for="name">Name:</label>
    <input type="text" name="name" id="name"/>
    <input type="text" name="name" onfocus="ReadName()"/>
</form>

A: function ReadName() {
    var name = document.getElementById('name').value;
    alert('Hello '+ name);
}


text:
Q: NGINX -Rewrite url keeping part of url Please help me to create nginx redirect like below:
https://mypage.com?via=181696076 -> https://newpage.com/checkout/?cc=GS950N&short_id=gi&via=181696076

The parameter(181696076) will change, will be only a number and will not have a fixed length
Can I do this using location?
rewrite ^/(.*)$ https://newpage.com/checkout/?cc=GS950N&short_id=gi&$1;

I tried few combination, but it does not work for me - like the rewriting on server level
Thanks

A: I found such solution for this problem:
  location ~ ^/(.*)$ {
return 301 https://newpage.com/checkout/?cc=GK960N&short_id=gi&via=$1;

}


text:
Q: Java application unable to access Blob stream in Oracle after upgrade to 11g This issue below might be an application problem, but I cannot seem to rule out a poor database setup, I was hoping to get some insights into potential database issues.
I am maintaining a legacy Java application, our hosting provider provides DBA support for our Oracle database. We were on 10g, several months ago we upgraded to 11g. I in turn upgraded the Java drivers from ojdbc5.jar to ojdbc6.jar. Everything mostly seems fine....
The application uses Hibernate ORM tool, one of the fields of this one entity happens to be a Blob type. When the application saves changes to this entity, the generated SQL is an update statement that includes this Blob column regardless if it has changed or not.
On this one operation, the user updates their annual subscription, so they do it once a year, but when it calls the update here Java throws "Unable to access blob stream!" and then claims the underlying connection is closed.  This ONLY occurs for this one operation.
If I completely shut down and restart the server, and then perform the same operation again it works perfectly fine and continues to work fine for that one record forever and ever amen.
But it seems to happen here for every single record in this one table at least once.
Needless to say this is a nightmare to debug because I cannot reproduce it on a single record, just observe it once per record on my test system, then never see it happen again, and yes the same behavior occurs on my test environment that is a mirror of my production database.
My question is if it is possible that when the Oracle 11g upgrade occurred that it corrupted the LOB space in some way to where this seems to be happening?
EDIT:
Now I can't reproduce it on any record....
its like the database felt that I was trying to debug it and temporarily reverted into a state of good behavior
Maybe the LOB space was sleeping, then woke up?
EDIT 2:
The problem happened again this morning, after I left the database to sit unused for several hours.
As requested here is the exact error:

Unable to access blob stream!
  Cause: Closed Connection
  SQL State: 08003
  Vendor Code: 17008

Preliminary research seems to suggest that this might be an issue with the Oracle JDBC drivers?  Oracle JDBC 11.2.0.3 ojdbc6.jar

A: I have faced similar situation for a procedure call with input Blob parameter. Same piece of code was working just fine on 11.2.0.2, but began to throw
"java.io.IOException: I/O Exception: Connection reset by peer: socket write error"
on 11.2.0.3. I have downgraded from ojdbc6.jar to ojdbc14.jar+ocrs12.jar now it is working. I don't know why but it seems ok for now.


text:
Q: PHP while loop is not working properly for URL Shortner script I am trying to make URL Shortner website and my problem is that PHP while loop is not working properly. Problem is that I am allowing users to enter five links at a time to make shorten URL. I was testing it in my localhost and I got this issue. If I add single link then it works properly. But if I add multiple all five links then its not working properly. My codes are
add_url.php
<form method="post" enctype="multipart/form-data" style="padding:10px;" autocomplete="off" >
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." required />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="url" style="padding:5px; margin:5px; width:90%" name="link[]" placeholder="Insert link to make shorten url." />
     <input type="hidden" name="cool" value="<?php echo $_SESSION['CSRF_TOKEN'];?>" />
     <button style="padding:5px; margin:5px; float:right;" type="submit" class="btn btn-small btn-success" name="shorten" value="sortn">Shorten</button>
     </form>

     <?php

     if(isset($_POST['shorten']) AND ($_POST['shorten'] == 'sortn')){

         $post_links = $_POST;

         include 'usrShortenLink.php';
         Shorten::new_shorten_link($post_links);
         echo "<meta HTTP-EQUIV=\"REFRESH\" content=\"3; url=$site\">";

     }
     ?>

I need to echo mets tag because if user will refresh the page then it will post all data once again. and $site = localhost which I've set to use it for other functions.
usrShortenLink.php codes are
<?php

class Shorten{

    public static function check_archived_link($link, $user_email){

        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        $check_archived_query = "SELECT * FROM `url_table` WHERE BINARY (`url` = '$link' AND `u_email` = '$user_email' AND `archived` != '0')";

        if($result = $db->query($check_archived_query)){
            if($result AND $db->affected_rows > 0){

                $update_archived_link = "UPDATE `url_table` SET `archived` = '0' WHERE BINARY (`url` = '$link' AND `u_email` = '$user_email')";

                if(($db->query($update_archived_link)) AND ($db->affected_rows > 0)){
                    throw new Exception('Your entered link is already in use with your account and it was deactivated by you. We\'ve activated your link.
');
                    return true;
                } else {
                    throw new Exception('Your entered link is already in use with your account and it was deactivated by you. We tried to activate the links but we got some error. Please try again.
');
                }

            }
            else {
                self::check_link($link, $user_email);
            }
        }

        else {
            throw new Exception('We faced some unwanted errors. Please try once again.
');
        }

    }

    public static function check_link($link, $user_email){

        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        $check_query = "SELECT * FROM `url_table` WHERE BINARY (`url` = '$link' AND `u_email` = '$user_email')";

        if($result = $db->query($check_query)){
            if($result AND $db->affected_rows > 0){
                throw new Exception('Your entered link is already in use with your account. We don\'t do duplicates.
');
            }

        }

        else {
            throw new Exception('We faced some unwanted errors. Please try once again.
');
        }

    }

    public static function check_details_from_db($link, $user_email){
        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        if(!filter_var($link, FILTER_VALIDATE_URL)){
            throw new Exception('Entered link is not in valid format. Please check it.
');
        } else

            if(strlen($link) > 1000){
                throw new Exception('Entered link is too long to process.
');
            } else

                //check links are in database and archived or not
                self::check_archived_link($link, $user_email) ;

    }

    public static function gen_code(){
        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        //generate random code for shorten url

        $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
        $len = 6;
        $numrows = 1;
        $code = empty($code);

        while($numrows != 0){
            for($i = 0; $i <= $len; $i++){
                $rand = rand()% strlen($charset);
                $temp = substr($charset, $rand, 1);
                $code .= $temp;
            }

            $find = $db->query("SELECT `id` FROM `url_table` WHERE BINARY `code` = '$code'");
            $numrows = $find->num_rows;
        }
        return $code;
    }

    public static function insert_link($link, $user_email, $blah){

        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        try {
            self::check_details_from_db($link, $user_email);
        }
        catch(Exception $e) {
            echo 'Message: ' .$e->getMessage();
        }

        if(empty($e)){

            $code = self::gen_code();
            if(strlen($code) > 7){
                $code = '';
                $code .= "";
                $code .= self::gen_code();

            }

            $ip = $_SESSION['ip'];
            $date = time();
            $site_name = $site;

            $hash_string = $user_email.'/'.$date.'/'.$ip.'/'.$code;
            $hash  = $blah->encode($hash_string);

            $insert_link_query = "INSERT INTO `url_table` (`url`, `site`, `code`, `u_email`, `create_time`, `ip`, `hash`, `archived`)
                                                                  VALUES ('$link', '$site_name', '$code', '$user_email', '$date', '$ip', '$hash', '0')";

            if($result = $db->query($insert_link_query)){
                if($result AND $db->affected_rows > 0){
                    echo 'Message: Successful! Check your all links at right side. You can manage all links from the same table.
';
                    $refresh_url = $site.'user/v1/home';
                } else {
                    echo 'Message: We got an error. Please try again.
';
                }
            } else {
                echo 'Message: Ooopps! We got an error. Please try again.
';
            }
        }

    }

    public static function new_shorten_link($post_links){
        include $_SERVER['DOCUMENT_ROOT'].'/db.php';

        $cool = $db->real_escape_string(htmlentities($post_links['cool']));
        $user_email = $_SESSION['email'];
        include $_SERVER['DOCUMENT_ROOT'].'/encryption.php';
        $blah = new Encryption;
        foreach($post_links['link'] as $links){
            $link = $db->real_escape_string(htmlentities($links));

            if(!empty($link)){
                $code = '';
                self::insert_link($link, $user_email, $blah);
            }
        }
    }

}

?>

Now, the problem is that if I add single link then it will generate shorten code and its string length will be 7 characters. But if I add multiple links then I get increased string length of shorten code. I've allowed only 20 characters to be inserted in database in code column. SO it is inserting max 20 characters but still its an issue for me. I want only 7 characters to generate. So can anyone help me with this?
Here are my last few test links which I've added to test script.
1.2/257986542 ----    locho/1tqjoV8f
1.2/2558351 ----    locho/15-FS1k7
1.2/258645312 ----    locho/11k7yXwxeTIZWPUpCL6R    <---- second link's copy and then
                                                                followed by code generated by loop.
1.2/2576531 ----    locho/1WPUpCL6RiHgh0D
1.2/254886 ----    locho/1h0DsJGz
1.2/25654 ----    locho/1fAlObMN
1.2/256845 ----    locho/13KnctqjoV8fAlObMNu9
1.2/257865 ----    locho/1AlObMNu9Yda5-F
1.2/25879 ----    locho/1yXwxeTI
1.2/2578 ----    locho/11k7yXwxeTIZWPU          <---- second links with issue
1.2/252 ----    locho/1JGzE_mvQB4r23K           <---- copy of 1st links
1.2/253 ----    locho/1_mvQB4r
1.2/254 ----    locho/1ctqjoV8
1.2/255 ----    locho/1a5-FS1k
1.2/256 ----    locho/1S1k7yXw
1.2/25  ----    locho/1JGzE_mv                   <---- 1st links
You can find some similar codes in generated results.

A: public static function gen_code(){
            include $_SERVER['DOCUMENT_ROOT'].'/core/db_config_inc.php';

                    //generate random code for shorten url

                    $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
                    $len = 6;
                    $numrows = 1;
                    $code = '';

                    while($numrows != 0 AND strlen($code) < 8 ){
                        for($i = 0; $i <= $len; $i++){
                            $rand = rand()% strlen($charset);
                            $temp = substr($charset, $rand, 1);
                            $code .= $temp;
                        }

                        $find = $db->query("SELECT `id` FROM `url_table` WHERE BINARY `code` = '$code'");
                        $numrows = $find->num_rows;
                    }
        return $code;
    }

Try this... this will help you... ;)


text:
Q: Integrate Doxygen API documentation with Codeplex website We use Doxygen to generate API documentation, this works well. But we cannot host the files on Codeplex, because when using the SVN url of the HTML files the file code is shown not the parsed HTML.
Here's a simple test: https://mapwingis.svn.codeplex.com/svn/MapWinGIS/trunk/Doxygen/index.html
How can we share our Doxygen documentation with our users through the codeplex site?
I know the alternative is to host the Doxygen files on a separate hosting provider. But I would like to have all data on one place.


text:
Q: Ada: polymorphic callbacks I'm trying to implement an Observer pattern using OOP and dynamic dispatching, but I'm not able to create an access-to-subprogram constant because the argument types of the named access and the procedure of the type extension don't match.
I provide a minimal reproducibable example, ommiting subscription:
package Alarms is

  type time_t is mod 2**32;

  type AlarmObserver_t is interface;
  type Callback_t is access procedure (this : in out AlarmObserver_t);

  type AlarmPublisher_t (<>) is tagged limited private;
  function fConstructor (capacity : in Positive) return AlarmPublisher_t;

private

  type AlarObserverAcc_t is access AlarmObserver_t'Class;

  type dummy_t is new AlarmObserver_t with null record;
  procedure pEventDummy (this : in out dummy_t) is Null;

  dummy : constant AlarObserverAcc_t := new dummy_t;
  dummyCallback : constant Callback_t := pEventDummy'Access; --Fails

  type Node_t is limited
    record
      Observer : AlarObserverAcc_t := dummy;
      Callback : Callback_t := dummyCallback;
      time : time_t := time_t'Last;
    end record;

  defaultNode : constant Node_t := Node_t' (Observer => dummy,
                                            Callback => dummyCallback,
                                            time     => time_t'Last);

  type ObserverArray_t is array (Positive range <>) of Node_t;

  type AlarmPublisher_t (capacity : Positive) is tagged limited
    record
      --Member "observers" has default initialisation because Node_t is initialised
      observers : ObserverArray_t (Positive'First .. capacity);
    end record;

end Alarms;

And the implementation to let you reproduce it:
package body Alarms is

  function fConstructor (capacity : in Positive) return AlarmPublisher_t is
  begin
    return Obj : AlarmPublisher_t (capacity => capacity) do
      Null;
    end return;
  end fConstructor;

end Alarms;

I was inspiring in Matthew Heaney callbacks Observer pattern
He use a class-wide argument for the access-to-subprogram procedure, but I would like to use OOP notation and let the concrete observers to have those procedures as primitives.
Why procedure pEventDummy is not compatible if dummy_t implements AlarmObserver_t interface?
Can I do what I want?
I provide an example below to show what I would like to do. I want concrete observers to be flexible and allow them to subscribe to the method they want to be notified when the subscribed alarm expires. I don't know in advance which primitives will be used for that purpose so I don't want to type all the possibilities as abstract primitives of the AlarmObserver_t interface, I would like let the concrete observers to subscribe to an access to procedure for that purpose, and they will be notified through them at different moments:

with Alarms;

package ConcreteObserver is

  type ConcreteObserver_t is new Alarms.AlarmObserver_t with private;

  --Procedure evTimeout to be notified for an alarm expirancy.
  --Null implementation to let you compile
  procedure evTimeout (this : in out ConcreteObserver_t) is null;

  --Procedure evAnotherTimeout to be notified for another alarm expirancy
  --Null implementation to let you compile
  procedure evAnotherTimeout (this : in out ConcreteObserver_t) is null;

private

  --This will fail as dummyCallback in Alarms package
  evTimeoutCallback : constant Alarms.Callback_t := evTimeout'Access;

  --This will fail as dummyCallback in Alarms package
  evAnotherTimeoutCallback : constant Alarms.Callback_t := evAnotherTimeout'Access;

  type ConcreteObserver_t is new Alarms.AlarmObserver_t with
    record
      --Any attribute
      Null;
    end record;

end ConcreteObserver;

A: I would suggest adding a polymorphic operation to your interface type:
package Alarms is

  type time_t is mod 2**32;

  type AlarmObserver_t is interface;

  type TimeoutObserver is interface and AlarmObserver_t;
  procedure Timeout_Callback(This : in out TimeoutObserver) is abstract; -- polymorphic operation

  type AnotherTimeoutObserver is interface and AlarmObserver_t;
  procedure AnotherTimeout_Callback(This : in out AnotherTimeoutObserver) is abstract; -- polymorphic operation

  type AlarmPublisher_t (<>) is tagged limited private;
  function fConstructor (capacity : in Positive) return AlarmPublisher_t;

private

  type AlarObserverAcc_t is access AlarmObserver_t'Class;

  type dummy_t is new TimeoutObserver and AnotherTimeoutObserver with null record;
  overriding procedure Timeout_Callback(This : in out dummy_t) is null;  -- local type override
  overriding procedure AnotherTimeout_Callback(This : in out dummy_t) is null;  -- local type override

  dummy : constant AlarObserverAcc_t := new dummy_t;

  type Node_t is limited
    record
      Observer : AlarObserverAcc_t := dummy;
      time : time_t := time_t'Last;
    end record;

  defaultNode : constant Node_t := Node_t' (Observer => dummy,
                                            time     => time_t'Last);

  type ObserverArray_t is array (Positive range <>) of Node_t;

  type AlarmPublisher_t (capacity : Positive) is tagged limited
    record
      --Member "observers" has default initialisation because Node_t is initialised
      observers : ObserverArray_t (Positive'First .. capacity);
    end record;

end Alarms;

package body Alarms is

    function fConstructor (capacity : in Positive) return AlarmPublisher_t is
    begin
        return Obj : AlarmPublisher_t (capacity => capacity) do
            Null;
        end return;
    end fConstructor;

end Alarms;

with Alarms;

package ConcreteObserver is

  type ConcreteObserver_t is new
        Alarms.TimeoutObserver
    and Alarms.AnotherTimeoutObserver
  with private;

  --Procedure evTimeout to be notified for an alarm expirancy.
  --Null implementation to let you compile
  overriding
  procedure Timeout_Callback (this : in out ConcreteObserver_t) is null;

  --Procedure evAnotherTimeout to be notified for another alarm expirancy
  --Null implementation to let you compile
  overriding
  procedure AnotherTimeout_Callback (this : in out ConcreteObserver_t) is null;

private

  type ConcreteObserver_t is new
        Alarms.TimeoutObserver
    and Alarms.AnotherTimeoutObserver
  with
    record
      --Any attribute
      Null;
    end record;

end ConcreteObserver;

You can use Object.Operation notation to call Callback for your AlarmPublisher_t object.  EX:
for Node of Observers loop
    if Node.observer in TimeoutObserver'Class then
        TimeoutObserver'Class(Node.observer).Timout_Callback;
    end if;

    if Node.observer in AnotherTimeoutObserver'Class then
       AnotherTimeoutObserver'Class(Node.observer).AnotherTimeout_Callback;
    end if;
end loop;


text:
Q: JS: Converting json and allowing client to download as csv without saving to server In this question several ways were proposed to parse a json array into csv.
However in the answers given, fs is used to write the csv too. I am wondering whether it is possible to just convert a csv and make it available for the client to download without having to write it somewhere in the server? After all, the json already exists and writing a csv seems like duplication.
In my case I have a server with a mongodb collection which I'd like to make available portions of to clients as a csv.
thank you for your help!

A: You can convert the JSON to csv with client side javascript like in the question you linked.
Then you can make the browser download that file as a csv as described here
So like this:
function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

var json = getYourJSONObject();
var csv = convertJSONToCsv(json);

var name = "filename";
download(name+".csv",csv);

Hope this help :)


text:
Q: perl convert lines to columns when values match I have a tab-delimited text file with the following structure
col1    col2    col3    col4    col5    col6
T1      a       b       c       d       x
T5      a       b       c       d       x
T3      a       b       c       e       y
T50     e       f       g       h       y
T2      e       f       g       h       y
T60     a       b       c       d       y

*If the values in col2, col3, col4 & col5 are the same for two or more lines, I want the value of col6 for all the matching lines to be put in an extra column that has the value of col1 in the header.
So in this case lines 1 and 2 should be considered as the same, because there values for col2,3,4,5 are the same (abcd). The same holds for lines 4 and 5 (efgh)
*If the values in col2, col3, col4 & col5 are unique, then it's just the value of the col6 for that one line that should be put in a new column.
So in this case line 3 is unique, because none of the other lines has abce as values for col2,3,4,5.
So the output should look like this.
col1    col2    col3    col4    col5    col6    T1    T2    T3    T5    T50  T60
T1      a       b       c       d       x       x     -     -     x     -    y
T5      a       b       c       d       x       x     -     -     x     -    y
T3      a       b       c       e       y       -     -     y     -     -    -
T50     e       f       g       h       y       -     y     -     -     y    -
T2      e       f       g       h       y       -     y     -     -     y    -
T60     a       b       c       d       y       x     -     -     x     -    y

I want to do this in perl. But I have no idea how to do this. Should I work with a hash to store the values of col2-col3-col4-col5? Below is just the start of the script to open input and output files
#! /usr/bin/perl
use strict;
use warnings;

open(my $table1,'<', "input.txt") or die "$! - [$input]"; #input file
open(my $table2, '+>', "output.txt") || die ("Can't write new file: $!"); #output file

A: This solution does two passes of the file. It has some special treatment for __DATA__ that you can remove if you work with files.
use strict;
use warnings 'all';
use feature 'say';
use List::MoreUtils 'uniq';
use Fcntl 'SEEK_SET';

# grab the header and split up the headings
chomp( my $header = <DATA> );
my @fields = split /\s+/, $header;

# we need this because __DATA__ is not a regular filehandle
my $data_start = tell DATA;

# this name is bad, because we don't know what this the column really contains
my %col6;

# first pass
while ( my $row = <DATA> ) {
    chomp $row;
    my @cols = split /\s+/, $row;

    # in a hash with col2 to col5 as key, use col1 as key and col6 as value
    $col6{ join q{::}, @cols[ 1 .. 4 ] }->{ $cols[0] } = $cols[5];
}

# reset DATA to beginning, this is not needed if you work with a file
seek DATA, $data_start, SEEK_SET;

# get the additional headings from the col1 mapping
my @new_fields = sort +uniq map { keys %{ $col6{$_} } } keys %col6;

# output them
say join "\t", @fields, @new_fields;

# second pass
while ( my $row = <DATA> ) {
    chomp $row;
    my @cols = split /\s+/, $row;

    # go through all the new headings and either print the value of the col6, or a dash
    say join "\t", @cols, map { $col6{ join q{::}, @cols[ 1 .. 4 ] }->{$_} || q{-} } @new_fields;
}

__DATA__
col1    col2    col3    col4    col5    col6
T1      a       b       c       d       x
T5      a       b       c       d       x
T3      a       b       c       e       y
T50     e       f       g       h       y
T2      e       f       g       h       y

Output:
col1    col2    col3    col4    col5    col6    T1  T2  T3  T5  T50
T1  a   b   c   d   x   x   -   -   x   -
T5  a   b   c   d   x   x   -   -   x   -
T3  a   b   c   e   y   -   -   y   -   -
T50 e   f   g   h   y   -   y   -   -   y
T2  e   f   g   h   y   -   y   -   -   y

A: You need to break down the problem:

*

*Identify all unique combinations for col2 .. col6 and associate the corresponding col1 value with them. This screams for a hash:
my ( %unique, %label);
while ( <$table1> ) {
    my @record = split;
    my $id = $record[0];
    my $label = $record[5];
    my $result = join '~', @record[1..4];
    push @{ $unique{$result} }, $id;
    $label{$id} = $label;
}

*Generate the output matrix as per your requirement


text:
Q: How to show specific content based on 3 drop down selections? I would like to display a div depending on a user's selection from two drop down lists.
While I'm going to display 3 dropdown options to the users, I'm only going to generate the output based on the selection of the first two:

This means that I will have a total of 9 possible outputs based on the user's selection:

*

*Beaches --> Chill

*Beaches --> Fast-Paced

*Beaches --> Both

*Museums --> Chill

*Museums --> Fast-Paced

*Museums --> Both

*Mountains --> Chill

*Mountains --> Fast-Paced

*Mountains --> Both

Just for similar reference, a few months ago, I used the following script to generate a specific output based on 2 drop down selections:
http://jsfiddle.net/barmar/ys3GS/2/

Find your Animal Name

Select your birth month and your favorite color and find your animal name.

<form>
        <select id="month">
            <option value="">- birth month -</option>
            <option value="January">January</option>
            <option value="February">February</option>
            <option value="March">March</option>
            <option value="April">April</option>
            <option value="May">May</option>
            <option value="June">June</option>
            <option value="July">July</option>
            <option value="August">August</option>
            <option value="September">September</option>
            <option value="October">October</option>
            <option value="November">November</option>
            <option value="December">December</option>
        </select>
        January Name
        February Name
        March Name
        April Name
        May Name
        June Name
        July Name
        August Name
        September Name
        October Name
        November Name
        December Name

        <select id="color">
            <option value="">- favorite color -</option>
            <option value="Green">Green</option>
            <option value="Blue">Blue</option>
            <option value="Red">Red</option>
        </select>
        Green Name
        Blue Name
        Red Name
    </form>

But this need is a little different. Any thoughts on how I can achieve this? In other words – once the user selected the two options, I want the corresponding div (out of the 9 options) to show up below.
Thanks so much!

A: You can create 9 div elements and each div element will have two data attributes. One for travel preference and one for style. Like so:

Also, let's go ahead and add some CSS to hide these div elements, and then setup an active class so that we can display the div once the user has made their selections.
The select elements where the user makes a choice will have options, and each value will have to be identical to the data-preference and data-style values. When a user has made a selection in both of the dropdowns we'll grab all the div's and filter out the one that has the matching data attributes.
$('#preference, #style').on('change', function(){
    // set reference to select elements
    var preference = $('#preference');
    var style = $('#style');

    // check if user has made a selection on both dropdowns
    if ( preference.prop('selectedIndex') > 0 && style.prop('selectedIndex') > 0 ) {
        // remove active class from current active div element
        $('.result.active').removeClass('active');

        // get all result divs, and filter for matching data attributes
        $('.result').filter('[data-preference="' + preference.val() + '"][data-style="' + style.val() + '"]').addClass('active');
    }
});

jsfiddle: http://jsfiddle.net/EFM9b/1/

A: The following is jQuery will work for any number of select fields. It uses the values of the options as CSS classes which are then used to match against the results boxes.
No hiding or showing of the results happens until all select boxes are chosen.
JSFiddle
http://jsfiddle.net/chnZP/
CSS
#results-container > div { display: none; }

HTML

    <select>http://jsfiddle.net/9Qpjg/15/#update
        <option value='none'>Select Option</option>
        <option value='alpha'>Alpha</option>
    </select>
    <select>
        <option value='none'>Select Option</option>
        <option value='red'>Red</option>
        <option value='blue'>Blue</option>
    </select>
    <select>
        <option value='none'>Select Option</option>
        <option value='dog'>Dog</option>
        <option value='cat'>Cat</option>
    </select>

 Alpha Red Dog

 Alpha Blue Dog

 Alpha Red Cat

 Alpha Blue Cat

JavaScript
jQuery(function($){

    var
        selects = $('#select-container select'),
        results = $('#results-container > div');

    selects.change(function(){
        var values = '';
        selects.each(function(){
            values += '.' + $(this).val();
        });
        results.filter(values).show().siblings().hide();
    });

});

A: Careful naming of your divs will get you most of the way there, e.g.

...

...

...

...

Now show or hide these based on your dropdowns:
$('#preference, #style').change(function() {
  $('.itinerary').hide();
  $('#' + $('#preference option:selected').val() + '_' + $('#style option:selected').val()).show();
});

(Another answer here suggests using attributes--that's nicer than using the id, so do that.)


text:
Q: Can I say "got up" or "waked up"? Are the following sentences correct?

He just got up. -- Can I say this, informally?
He just waked up.

A: We can say either sentence, but waked is used far less often than woke.
He just woke up.
wake (base/infinitive)
woke (simple past)
woken (past participle)
The two sentences have almost the same meaning, and we often use them interchangeably.
There is a slight distinction: "He just woke up" tells us that the person is now awake. "He just got up" tells us that the person is now awake and implies that the person also got out of bed.

A: It's fine!

He just got up = He just waked up

Both mean informally that he's not sleeping now. He just finished his sleep.
However, it's worth knowing that 'wake up' and 'get up' mean many things other than the context of 'sleeping'. And I consider that you are talking about his state of 'sleeping'.
Note that 'woke up' is way more common than 'waked up'.

A: My answers honestly is that woke up is the best and some times you could say got up but of course you can't say than with someone you can use it in a diary that was an example
But it's not common saying waked it's not from proper English


text:
Q: Slow response in chat messages using cronjob I have several accounts in Mercado Libre, the idea of the project is to be able to respond to messages (post-sales chat) and questions (pre-sales) from customers through my own platform.
The question section works great (It has a small delay maybe by the same cronjob). However, the messages section does not work well at all, you send a message and it takes a long time to send, you select something and it takes too long to select, it is a functioning problem, the chat should deliver instantly.
The code used is php, ajax, curl and js. Database used is mysql
Why can I do?


text:
Q: Disk corrupted ? One folder cannot access I have one Disk for backup on my PC that I copy some files.
I have a lot of Folders and Data on this disk but I get this error message only for one folder. Do I need another disk?
I Run  sudo ntfsfix /dev/sdb1 but with no luck same error message.
Should I delete the Downloads folder?
I try to delete Downloads but no luck also
└─[0] <> ls -lh
ls: cannot access 'Downloads': Input/output error
total 69K
d????????? ? ?      ?         ?            ? Downloads
drwxr-xr-x 1 me me 4,0K Dec 26 19:32 me

I also ran smartctl and it said healthy.
=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

Disk
Model Family:     SAMSUNG SpinPoint F4 EG (AF)
Device Model:     SAMSUNG HD204UI
Type: HPFS/NTFS/exFAT

dmesg
[92409.430263] ata5.00: exception Emask 0x0 SAct 0x800000 SErr 0x0 action 0x0
[92409.430269] ata5.00: irq_stat 0x40000008
[92409.430274] ata5.00: failed command: READ FPDMA QUEUED
[92409.430283] ata5.00: cmd 60/08:b8:00:ec:34/00:00:04:00:00/40 tag 23 ncq dma 4096 in
                        res 41/40:00:00:ec:34/00:00:04:00:00/40 Emask 0x409 (media error) <F>
[92409.430288] ata5.00: status: { DRDY ERR }
[92409.430293] ata5.00: error: { UNC }
[92409.442525] ata5.00: configured for UDMA/133
[92409.442546] sd 4:0:0:0: [sdb] tag#23 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_SENSE
[92409.442551] sd 4:0:0:0: [sdb] tag#23 Sense Key : Medium Error [current]
[92409.442554] sd 4:0:0:0: [sdb] tag#23 Add. Sense: Unrecovered read error - auto reallocate failed
[92409.442559] sd 4:0:0:0: [sdb] tag#23 CDB: Read(10) 28 00 04 34 ec 00 00 00 08 00
[92409.442563] blk_update_request: I/O error, dev sdb, sector 70577152 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 0
[92409.442570] Buffer I/O error on dev sdb1, logical block 8821888, async page read
[92409.442591] ata5: EH complete

A: Does dmesg or mount -l tell you anything interesting?
Usually the question marks imply that file attributes cannot be found. Something could be corrupted with the way the disk/filesystem has been mounted and/or inodes cannot be read or found. I've seen it plenty of times before over a network with CIFS.
Have you tried remounting?

A: Usually, the
d????????? ? ?      ?         ?            ? Downloads

means you currently have only r permission (= read directory listing) to the parent directory of Downloads, but the x permission (= to access the contents of the directory) is missing. As a result, when the ls command is running stat() on the Downloads directory, it gets an "access denied" error and cannot report any information other than just the name and the fact that it's a directory.
But the ls: cannot access 'Downloads': Input/output error certainly suggests it's not a permissions issue, but possibly something worse.
On the other hand, if the filesystem on the disk is NTFS, the error response might just mean there is some NTFS-specific permissions issue that does not exactly fit the POSIX standard definition of error responses from stat().
For NTFS, I think Windows's "Check this disk for errors" is still better at NTFS checking than any NTFS fsck implementation on Linux I've seen so far.
The dmesg output confirms the bad news: the disk is reporting a media error while trying to read the disk - so the disk surface is no longer readable at that particular block. It also says Unrecovered read error - auto reallocate failed so even repeated retries failed to recover the data from the failing block, so the disk could not automatically relocate the data to a spare block. A write operation into that block would allow the disk to "give up" on the old data and just switch into using the spare block for the new data, so the error may appear to "repair itself" as the disk is being used. But apparently the failing block contained important metadata about your Downloads folder, and that metadata is now gone.
That disk model (Samsung SpinPoint HD204UI) has been reviewed in March 2011, so this disk might be quite old. If it is actually older than about 5 years, you should definitely consider replacing it. Errors like this are your early warning that the disk is starting to fail by old age.


text:
Q: Can't run SSIS package in Visual Studio. The directory name is invalid I am attempting to run a simple SSIS package in Visual Studio (15.9.0). This is the first time I've used SSIS. My error message is at the bottom, because it's quite lengthy. Directly below is my attempt to fix the error.
I followed the directions of this link:
https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017
1.) I selected the checkboxes for "Data Storage and Processing" in Visual Studio Installer
2.) I uninstalled SSDT
3.) I downloaded SSDT for Visual Studio (15.8.2)
4.) I selected the "SSIS" checkbox on the installation of SSDT.
I am continuing to get the error message below. Thanks for any help in advance!

>
Failed to start project (Microsoft Visual Studio)
===================================
The directory name is invalid
  (Microsoft.DataTransformationServices.VsIntegration)
------------------------------ Program Location:
at
  Microsoft.DataTransformationServices.Project.DataTransformationsPackageDebugger.LaunchVsDebugger(IVsDebugger
  iVsDebugger, DataTransformationsProjectConfigurationOptions options)
  at
  Microsoft.DataTransformationServices.Project.DataTransformationsPackageDebugger.ValidateAndRunDebugger(Int32
  flags, IOutputWindow outputWindow,
  DataTransformationsProjectConfigurationOptions options)    at
  Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.LaunchDtsPackage(Int32
  launchOptions, ProjectItem startupProjItem,
  DataTransformationsProjectConfigurationOptions options)    at
  Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.LaunchActivePackage(Int32
  launchOptions)    at
  Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.LaunchDtsPackage(Int32
  launchOptions, DataTransformationsProjectConfigurationOptions options)
  at
  Microsoft.DataTransformationServices.Project.DataTransformationsProjectDebugger.Launch(Int32
  launchOptions, DataTransformationsProjectConfigurationOptions options)
  >

A: Answer 2
See the response from Microsoft.
https://social.msdn.microsoft.com/Forums/Windowsserver/en-US/aa3a46fb-2f09-4808-b6db-baa1553f6401/failed-to-start-project-microsoft-visual-studio?forum=sqlintegrationservices
Answer 1
Based on the question and user comments, I think you may have installed SSDT incorrectly. When installing SSDT, you need to select Install SSDT for 2017 with a new instance of VS 2017. Then, Select Integration services (kind of mandatory here b/c thats what you are installing), Reporting Services and/or Analysis Services.
https://developercommunity.visualstudio.com/comments/345539/view.html
Update 1
SSIS has a long and tortuous history with Visual Studio integration - it used to  just install as a new set of Business Intelligence projects (i.e., SSIS, SSRS, and SSAS) within Visual Studio itself, without requiring a new standalone installation (at least up through VS 2013, I never used VS 2015). Even the product's name has gone through a circus show: it went from DTS, to SSDT-BI, to SSDT - stay tuned for more changes from the marketing department folks!
As of VS 2017, SSDT has to be installed as a new instance of Visual Studio. This means that you will effectively have two instances of Visual Studio installed on your machine:

*

*For all SSDT related projects (i.e., Integration Services [IS], Reporting Services [RS], and Analysis Services [AS]).

*For all other non-SSDT related projects.

Note: I do not fully understand why Microsoft chose to split the development of SSDT into a standalone instance of VS 2017, but personally (and this is my own 2 cents) I hate it. The new Preview release cadence model has led to more problems than solutions and has made the relationship between VS2017 and VS2017 SSDT so unstable that I only install new preview releases on test boxes before installing them on my own. Microsoft has released some really bone-headed bugs (i.e., unable to deploy package from project, unable to open VSTA for script tasks/components due to regression issue with VS2017). It is enough to drive one bonkers. I currently use the following:

*

*Visual Studio 2017 (SSDT): 15.8.2

*Visual Studio 2017: 15.7.6

A: I finally got my SSIS package to run successfully! I was previously running Windows 7 64 bit OS and the version of SQL Server was 32 bit. I installed Windows 10 64 bit OS and now my SSIS package ran successfully. It seems that the OS and SQL Server must both be 64 bit.
Below are the different versions of technology I'm running
Windows 10 64-bit Operating System
 - SQL Server Standard 2012 (64-bit)
 - Visual Studio Professional 2017 (Version 15.9.4)
 - SQL Server Data Tools for VS 2017 (Version 15.8.2)
 - SQL Server Management Studio (Version 17.9.1)
 - The Project Template inside of VS was named "Integration Services Project" under the "Business Intelligence" tab.
Links

*

*SSIS Tutorial I was executing: https://www.youtube.com/watch?v=zwUhHIpRoIA

*SSDT: https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017

A: Script editor in VS 2017:::::::::::::::


text:
Q: SSE / Optimisation - duplicating array into larger array I'm trying to optimize the following function:
(Basically it takes a line  of 32bit Ints, and duplicates each int into a larger destination arrray, and then duplicates each line
for(int i = 0; i < numLines; i++)
{
    pStartOfLine  = pDest;
    for(int j = 0; j < intsPerLineSrc; j++)
    {
        *pDest = *pSrc;                     // copy pixel A to FullSizeBuffer A
        pDest++;                            // Move dest Ptr to next Pixel
        *pDest = *pSrc;                     // Copy pixel A to FullsizeBuffer AGAIN

        pDest++;                            // Move Src and Dst Pointrs to next pixels
       pSrc++;
    }

   memcpy(pDest, pStartOfLine, (8*intsPerLineSrc) );            // Duplicate the Line written to pDest, to next line of pDest.
   pDest = pDest + (2*intsPerLineSrc);                          // move pDest to Start of Next Line
}

Effectively scaling an image up to 2 * it's original size in both dimensions.
Now this strikes me as something that should benefit massively from SIMD, however i cannot seem to find the right set of intrinsic instructions that will assist me in this specific case.
Anyone care to help me out?
Or will i always be memory limited in such a simple operation that re-factoring in SIMD is a waste?
Yes this section of code ends up running in multiple threads, so it is already heavily multi-threaded, but i think that SIMD optimization may be even more helpful.
Cheers, for any help / advice,
James

A: Your current operation is memory bandwidth bound.
If you can find a way to not process the entire image but instead process blocks (e.g. 16x16 pixel blocks to 32x32 pixel blocks) and do other computations each block then you may be able to make your operations less memory bandwidth bound.
But if you have to process the entire image there are a few things you should consider to achieve the maximum memory bandwidth:

*

*For memory bandwidth bound operations they don't scale with the number of cores but they do scale with the number of sockets. So if you have a dual socket system the memory bandwidth is twice a single socket system (assumption both sockets use the same processor which they usually do). However, achieving twice the bandwidth can be tricky.

*The memcpy function is typically not optimized for copying large sizes. One of the main reasons is that many implementations of it don't use non-temporal stores. The rule of thumb for non-temporal stores is to use them when the size is larger than twice the size of slowest cache. Let's assume your processor has a 12 MB L3 cache. Then if the size of the destination image is larger than 6MB you should consider using non-temporal stores. This is almost certainly your case since you're code is writing 32 MB.

Here is an example of how you can use both SSE2 and non-temporal stores
int main() {
    int n = 16;
    int *src = (int*)_mm_malloc(n*sizeof(int),   16); //16 byte aligned
    int *dst = (int*)_mm_malloc(2*n*sizeof(int), 16); //16 byte aligned
    for(int i=0; i<n; i++) src[i] = rand();
    for(int i=0; i<n; i+=4) {
        __m128i  x = _mm_load_si128((__m128i*)&src[i]);
        __m128i lo = _mm_shuffle_epi32(x, 0x50); // 0x50 = 1100 in base 4
        __m128i hi = _mm_shuffle_epi32(x, 0xfa); // 0xfa = 3322 in base 4
        _mm_stream_si128((__m128i*)&dst[2*i+0], lo); //non-temporal store
        _mm_stream_si128((__m128i*)&dst[2*i+4], hi); //non-temporal store
        //_mm_store_si128((__m128i*)&dst[2*i+0], lo);
        //_mm_store_si128((__m128i*)&dst[2*i+4], hi);
    }
    //for(int i=0; i<n; i++) printf("%x ", src[i]); printf("\n");
    //for(int i=0; i<(2*n); i++) printf("%x ", dst[i]); printf("\n");
}

In your case replace n by the number of pixels. If n is not a multiple of four then you have to do a little clean up which I did not do here.  The temporal stores have to be 16 byte aligned in order to do this which is why I aligned dst. However, src does not have to be 16 byte aligned so you could use _mm_loadu_si128 and not align src.
Once you achieve maximum bandwidth for a single thread and assuming you have a multi-socket system you should try and achieve maximum bandwidth from both sockets. I don't have enough experience with this to help but I think it can be achieved using numactl.  See why-doesnt-this-code-scale-linearly for an example.


text:
Q: Does flask_json extension support top-level array JSON responses? I've been using flask_json's as_json decorators in my Flask API for a project. This has worked fine for json responses that are dicts/hashes at the top-level ({name: ... }) but I'd like to do a JSON response that is a list/array at the top-level:
[
  {
    "created_at": "02/07/2016 00:01:43",
    ...
  },
  {
    "created_at": "02/07/2016 00:02:43",
    ...
  }
]

When I tried to return an array, though, it raises a ValueError: "Unsupported return value" exception. And when I consult the module's documentation it seems it only supports dict return values. It looks like all the example outputs for json_response() also produces hash JSONs. Does this mean I should use jsonify instead?

A: Prior to 0.11, Flask's jsonify function only accepted dicts at the top level.  This was due to a security issue with very old versions of Internet Explorer that was open to attacks by overriding the Array prototype.
As of Flask 0.11, jsonify accepts any valid JSON value at the top level.
Flask-JSON allows the same types as jsonify as of 0.3.2.


text:
Q: Techniques of EL on Java I interest in creating my own service for some EL language for POJO.
For example, I have some object structure with inner POJO objects, A and B for example.
So, I want pass to my service string like "a.b.name" and than get this property value.
Are there any utils in java reflection api or 3rd part libraries?
I can parse this string by myself and then get fields and methods, but I think this is common feature. Any ideas?

A: Maybe you should look at the Spring Expression language or Groovy.
Spring EL is a full featured expression language (you should be able to use it without using the rest of the framework).
Groovy is a JVM language that can be easily integrated into java applications and it powerfull syntax can be very useful for such tasks. Since its compatible to Java you can access and modify your Java objects from groovy code.
You can also look at Jexl. I haven't used this one so far but it looks useful for your task.

A: Here are some more options that are available:

*

*OGNL

*MVEL

*Velocity

A: I used MVEL
It really reduced the code.


text:
Q: How to send real time stream of data from Arduino to a mobile phone via bluetooth I am doing a project which uses an accelerometer ADXL345 to detect the movement in X,Y,Z axis. And I also use an Arduino Nano.
Now I got the sketch of Arduino so that I can see the graph in the serial monitor in the Arduino software.
But once I Tried to connect HM-10 bluetooth with Arduino, the code cannot be uploaded into the software.
Is there anyone can tell me how to code the bluetooth part so that I can send the data in real time to an Android phone. Thank you!
The sketch I have:
#include<Wire.h>
#define accel_module (0x53)
byte values[6] ;
char output[512];
void setup(){
Wire.begin();
Serial.begin(9600);
Wire.beginTransmission(accel_module);
Wire.write(0x2D);
Wire.write(0);
Wire.endTransmission();
Wire.beginTransmission(accel_module);
Wire.write(0x2D);
Wire.write(16);
Wire.endTransmission();
Wire.beginTransmission(accel_module);
Wire.write(0x2D);
Wire.write(8);
Wire.endTransmission();
}
void loop(){
int xyzregister = 0x32;
int x, y, z;
Wire.beginTransmission(accel_module);
Wire.write(xyzregister);
Wire.endTransmission();
Wire.beginTransmission(accel_module);
Wire.requestFrom(accel_module, 6);
int i = 0;
while(Wire.available()){
values[i] = Wire.read();
i++;
}
Wire.endTransmission();
x = (((int)values[1]) << 8) | values[0];
y = (((int)values[3])<< 8) | values[2];
z = (((int)values[5]) << 8) | values[4];
sprintf(output, "%d %d %d", x, y, z);
Serial.print(output); Serial.write(10);
delay(100); }

A: The TX pin of HM-10 conflicts with the TX signal of the on board usb-to-uart IC. So you cannot upload code when connected HM-10.
In you case, just connect the Power/RX/GND of HM-10 to arduino Power/TX/GND will be good.


text:
Q: Including external libraries in CodeRunner 2 app? I've always used Xcode to compile OpenCV based code in c++. The procedure in Xcode was quite simple, I just had to mention the paths and add the necessary lib files to the project. Theres this app called CodeRunner 2 for macOS. Theres no proper documentation on how to include external libraries to compile code in this app. Is it possible to link OpenCV headers and compile them in CodeRunner ? If yes, could someone post the steps?

A: You can run OpenCV in CodeRunner by setting up a new language. Go to Preferences -> Languages, right-click C++, and select Duplicate. Name the new language "C++ OpenCV". On the right side of the preferences window, click Settings then the Edit Script button. Look for this line (or something similar):
xcrun clang++ -x c++ -lc++ -o "$out" "${files[@]}" "${@:1}"

Add the clang++ command line parameters for OpenCV after "$out". Here's my version:
xcrun clang++ -x c++ -lc++ -o "$out" -I/usr/local/opt/opencv3/include -L/usr/local/opt/opencv3/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs -lopencv_videoio -lopencv_calib3d "${files[@]}" "${@:1}"

Modify the -I and -L parameters to match your OpenCV install path. On this machine I used Homebrew to install OpenCV so it was installed in /usr/local/opt. On other machines I've compiled from source so OpenCV is installed in /usr/local/lib.
Modify the -l parameters to include the libraries you typically use.
After saving the compile script, go back to Preferences -> Languages and select the Templates button. You can set up a template for OpenCV programs. Here's mine:
#include <iostream>

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace std;

int main(int argc, char *argv[]) {
    cv::Mat image;
    // read an image
    if (argc < 2)
        image = cv::imread("img.jpg");
    else
        image = cv::imread(argv[1]);

    if (!image.data) {
        std::cout << "Image file not found\n";
        return 1;
    }

    // create image window named "asdfasdf"
    cv::namedWindow("asdfasdf");
    // show the image on window
    cv::imshow("asdfasdf", image);
    // wait for key
    cv::waitKey(0);

    return 0;
}

A: The previous reply by SSteve is great and also helps me sort out linking Boost library in CodeRunner.
Because the solution in the previous reply is specific to OpenCV library, a carelessly adding to the clang++ command line for external libraries in general might just generate massive building errors, which was the case when I tried to link Boost library.
Here, I want to clarify the unclear bit in SSteve's reply so everyone knows how and where to modify the command line before compiling their code with external library in Mac OS system.
I will use my case to explain, but in some point I will inform you of the tricky bits in CodeRunner setting or general command line typing.
I use macport to install the Boost library by
sudo port install boost

*

*header file is located at /opt/local/include

*library is located at /opt/local/lib/
If you cannot find the specific sub-library in Boost, open your terminal and type
cd /opt/local/lib/
find . -iname "*boost*"

and you should see all sub-libraries of Boost ( static library ends with .a and dynamic library ends with .dylib ) as below.

Before you start to modify the original command line ( supporting c++ 14 version ) such as
xcrun clang++ -x c++ -std=c++14 -stdlib=libc++ -lc++ -o "$out" "${files[@]}" "${@:1}" ${CR_DEBUGGING:+-g}

you need to know the directory of header file is after -I and the directory of Boost library is after -L, like
-I /opt/local/include/
-L /opt/local/lib/

In order to use a compiled static or dynamic sub-library in Boost ( see figure above ), you have to include it specifically after -L /opt/local/lib/. However, simply copying the library name without file extension either .a or .dylib would never let CodeRunner find the library you expect to run !!!
The detail is explained here and I just quota the important bit below
clang -dynamiclib -o libtest.dylib file1.o file2.o -L/some/library/path -lname_of_library_without_lib_prefix

To run such an example code in Boost Quickstart Document
#include <boost/regex.hpp>
#include <iostream>
#include <string>

int main()
{
    std::string line;
    boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" );

    while (std::cin)
    {
        std::getline(std::cin, line);
        boost::smatch matches;
        if (boost::regex_match(line, matches, pat))
            std::cout << matches[2] << std::endl;
    }
}

the way to include <boost/regex.hpp> now is by
xcrun clang++ -x c++ -std=c++14 -stdlib=libc++ -lc++ -o "$out" -I /opt/local/include/ -L /opt/local/lib -lboost_regex-mt "${files[@]}" "${@:1}" ${CR_DEBUGGING:+-g}

By using this command line, you should be able to compile the example code with Boost library.

Just remember to replace the prefix -lib with -l and exclude the file extension in the command line.

At last, there are some alternative solution to include the external library by using Xcode, which is in here


text:
Q: efficient way to compare datetime Am trying to execute the formula like below,just wondering what's the efficient method to do,
Below is the formula to calculate
result=  min(max(dtmealstart1,dtbkgstart),dtbkgend)
dtmealstart1= 11/02/13 8AM
dtbkgstart=11/02/13 9AM
dtbkgend=11/02/13 17.00 (5PM)
result=min(max(11/02/13 8AM,11/02/13 9AM),11/02/13 17.00 )
result=11/02/13 9AM

I just wrote this piece of code in c# to do the above logic but am just wondering is there any best way to do
int result = DateTime.Compare(dtmealStart1, dtBkgStart);
DateTime break1;
if (result < 0)
{
    break1 = dtBkgStart;
}
else
{
    break1 = dtmealStart1;
}
int result1 = DateTime.Compare(break1, dtBkgEnd);
DateTime mealstart1;
if(result1<0)
{
    mealstart1 = break1;
}
else
{
    mealstart1 = dtBkgEnd;
}

my mealstart1 value also bring it back 11/02/13 9AM

A: You could use the Math class on the DateTime Ticks
Something like:
 DateTime result = new DateTime(Math.Min(Math.Max(dtmealStart1.Ticks, dtBkgStart.Ticks), dtBkgEnd.Ticks));

 // result = 11/02/13 9AM