text:
Q: How do I make one single array of all selected radio buttons in vuejs? First of all, I am very new to vue. I just learned it in a crash course and google in a couple hours. so forgive me if this is obvious.
My Code from a vue cli: https://github.com/Cerezze/testSnowJoe/tree/main/vue-project
So I have a problem where I have to make a single array of all the groups of radio buttons. This array is supposed to be filled by the index of radio button groups and is supposed to represent whether they are changed or not (wether they are checked or not). They can only pick one per group, its a quiz.
The problem I am having is that, even though I feel Im using the correct logic, the array starts from [0,0,0,0,0], for every single group of radio buttons. Which means that I can only produce an array with a button mapping from one group or another. Below Ill walk through the code and explain further.
App.vue
Here is a simple component where I just import a json file. It is an array of objects and each object contains: an id, question, answer and an array of choices (for the radio buttons). I send the entire array as props to Panels.
<template>
    HELLO
    <Panels :questions="questions"/>
    </template>

Panels.vue
This component iterates through the the array of objects in the json file and creates a Panel for each index in the json file. I send the question and the questionsArray to Panel.
<template>

    <Panel :question="question" :questionsArray="questions"/>

</template>

Panel.vue
This component just provides the panel layout and transfers the choices array and the json array to question.
<template>

{{question.question}}

        <Question :choices = "question.choices" :questionsArray = "questionsArray"/>

</template>

Question.vue
And here is where my troubles lie. As I explained above, I am attempting to collect a single array to represent what is clicked for every group of questions. I would like it to be a one to one array because I want to check whether a radio button is clicked or not.
When I tried testing by simply pushing to the array, for each group it would push content properly, then when I went to another group of radio buttons, the array would start from the initialization again and proceed to push.
<template>

    <input type="radio" :id = "choice" @change="onChange($event)" v-model="mChoice" :name = "choices" :value = "choice">
    {{choice}}

{{mChoice}}

</template>

A: Observations :

*

*e.target.name will return the string of the choices with comma separated and i.choices will return the array of choices. Hence, below condition will always return false.
this.questionsArray.forEach((i, index) => {
  if(e.target.name == i.choices) { // Will always return false.
  }
}

You have to join(',') choices array to make the comparison happen.

*Another issue is that for each component, arr: [0,0,0,0,0] will be separate as we initialized it in each Question component which render dynamically. Hence, It is updating separate arr for each Question component.
One workaround for this problem is to emit the val object to parent and then handle that updation logic in parent and then do splice in parent.
Here is the live Demo :

Vue.component('question', {
  data: function() {
    return {
      mChoice: null
    }
  },
  props: ['choices', 'questionsarray'],
  template: `

<input type="radio" :id="choice" @change="onChange($event)" v-model="mChoice" :name="choices" :value="choice">
{{ choice }}

`,
  methods: {
    onChange(e) {
      const data = e.target.value;
      const val = {
        idx: 0,
        correctAns: ""
      };

      this.questionsarray.forEach((i, index) => {
        if(e.target.name == i.choices.join(',')) {
          val.idx = index;
          val.correctAns = i.correctAnswer;
          this.$emit('radioselection', { val: val, index: index })
        }
      });
    }
  }
});

var app = new Vue({
  el: '#app',
  data: {
    arr: [0, 0, 0, 0, 0],
    questions: [
      {
        "id": 1,
        "question": "1. What is Chris's favorite shadow puppet?",
        "choices": [
          "Dog",
          "Rabbit",
          "Bird"
        ],
        "correctAnswer": "Bird"
      },
      {
        "id": 2,
        "question": "2. What is Chris's favorite pokemon?",
        "choices": [
          "Poliwhirl",
          "Pikachu",
          "Suicune",
          "Buzz Lightyear"
        ],
        "correctAnswer": "Poliwhirl"
      },
      {
        "id": 3,
        "question": "3. What is Chris's least favorite dance?",
        "choices": [
          "Chicken Dance",
          "All"
        ],
        "correctAnswer": "All"
      },
      {
        "id": 3,
        "question": "4. What is Chris's favorite color?",
        "choices": [
          "Rainbow",
          "Black",
          "Rock",
          "MegaMan",
          "Sprite"
        ],
        "correctAnswer": "Black"
      }
    ]
  },
  methods: {
    getVal({val, index}) {
      this.arr.splice(index, 1, val);
      console.log(this.arr);
    }
  }
});

{{ question.question }}

    <Question :choices="question.choices" :questionsArray="questions" @radioselection="getVal"/>


text:
Q: End a while loop that continue ask for string input until I enter -1 I have to create a menu that holds item names, I can do it with a for loop that ends until the max has been reach, but how do I do it with a while loop that will continue ask until the max is reached or I enter -1
I tried with a for loop and it worked, but I have to use a while loop that can stop when I tell it to stop.
#include <iostream>

using namespace std;

void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
                  int MAX_MENU_ITEMS);

int main()
{
    const int MAX_MENU_ITEMS = 5;
    char menu_list[MAX_MENU_ITEMS][50];
    float price_list[MAX_MENU_ITEMS];
    int num_menu_items;

    read_in_menu(menu_list, price_list, num_menu_item, MAX_MENU_ITEMS);
}

void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
                  int MAX_MENU_ITEMS)
{
    for (int i = 0; i < MAX_MENU_ITEMS; i++)
    {
        cout << "Enter Names: ";
        cin.getline(menu_list[i], 20);
    }
}

I want to use a while loop that will continue going until I input -1 or reach the maximum. I want to stop the while loop whenever I want instead of the for loop where I have to reach the max.

A: Whenever you want to exit a loop you can use the break keyword.
for(int i = 0; i < MAX; i++){
    if(i > 10){
        break;
    }
    doWork();
}

A: You can transform for loop to other loops. For example:
For
for(int i = 0; i < 10; i++)
    DoSomething();

While
int i = 0;
while(i < 10){
    DoSomething();
    i++;
}

do-while
int i = 0;
do{
    DoSomething();
    i++;
}
while(i < 10);

To control the loops use continue and break keywords. Keyword continue will skip the current iteration of the loop and break will exit the loop. These are usually conditioned by if statement.

A: If I understand correctly, something like this should work:
int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS || input == "-1") {
    cout << "Enter Names: ";
    cin.getline(input, 20);
    if(input != "-1") { //to avoid setting menu_list[i] = "-1"
        menu_list[i] = input;
    }
    MAX_MENU_ITEMS++;
}

or using break:
int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS) {
    cout << "Enter Names: ";
    cin.getline(input, 20);
    if(input == "-1") {
        break;
    }
    menu_list[i] = input;
    MAX_MENU_ITEMS++;
}

A: I was able to get it with a pointer lol.
void read_in_menu(char menu_list[5][20], float price_list[], int &num_menu_items, int MAX_MENU_ITEMS){
int i = 0;
char *p = "-1";
while(i<MAX_MENU_ITEMS){
cout << "Enter Name" << endl;
cin.getline(menu_list[i],20);
if(strcmp(menu_list[i], p)){
i++;
}else{
break;
}
}
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: what EXACTLY is the difference between const thisFunction = () => {} and const thisFunction = ({}) => {} Check this function below, what would I call the thread thats coming in on this function below, is it a parameter? or is it a destructured part of an object? does the curly brace mean this is still a parameter? im just a little confused
const ChatThread = ({thread}) => {

return (

)
}

if I do the same function like below i get an error with the thread, why is it required to use the curly braces to get the data?
const ChatThread = (thread) => {

return (

)
}


text:
Q: Efficient approach of selecting large amount of rows in an Excel file I have an Excel file which have large amount of rows.
Is there an efficient way to select say 100,000 rows other than dragging my mouse?

A: I simply use the End key. Start with A1 selected. Hold down Shift, then press End and then →. Then (while still holding Shift) press End again and then ↓.
This should select everything in a very small number of key strokes. However if there are gaps in your data you may have to press End then ↓ until you have everything.

A: One thing I do is press F5 (on Windows - brings up the "Go To" menu) and in the Reference section type the address of the range I want to select. For instance, to select the first 100,000 rows, type 1:100000 (or A1:D100000, etc.).
You can also do various things like hitting Shift+Space and Ctrl+Shift+Down assuming 100000 is the end and your range is contiguous, Ctrl+A to select the entire used range, etc.

A: For Excel (Windows 10, Office 365 at least) this is very easy.

*

*Click to select a cell within your table of data

*Press the "End" key to tell Excel that you want to select all cells until the end of the table of data

*Now press and hold the "Shift" key and then press one of the four arrow keys

All the cells from the cell you first selected to the last cell in the arrow's direction should now be selected.
You can also begin at step 1. and select a group of cells.

A: I have a Mac, using Version "16" and do not know where the "GoTo" menu is, so here's an alternative if you need to delete a large number (but not all) of the rows. Click on the first row to select it, scroll down to the row that is the bottom of the range you want to delete. Do a shift click on that row - this will highlight all the rows you want to delete. Click on the Delete menu item in the Edit menu.


text:
Q: Setting coordinate display axis order for new projects with PyQGIS Using QGIS 3.28.1 (Windows), I wanted to automatically change the default coordinate display axis order of a new QGIS project to "XY". Unfortunately there is no global setting for this, so I created a startup.py file with the following code:
from qgis.core import QgsProject,QgsMessageLog,Qgis

QgsProject.instance().displaySettings().setCoordinateAxisOrder(Qgis.CoordinateOrder.XY)
QgsMessageLog.logMessage('CoordinateAxisOrder: %s' % QgsProject.instance().displaySettings().coordinateAxisOrder(),'Custom',Qgis.Info)

Although the message log shows me that the axis order has been changed, QGIS shows no change at all.
Do I need to use any signal to change the default coordinate display axis order?
And if possible, can I change the value via Python plugin?

A: With the help of @bugmenot123 and north-road (Nyall?) I found a solution using the newProjectCreated signal of QGIS iface:
from qgis.core import QgsProject,QgsMessageLog,Qgis
from qgis.utils import iface

iface.newProjectCreated.connect(lambda: QgsProject.instance().displaySettings().setCoordinateAxisOrder(Qgis.CoordinateOrder.XY))


text:
Q: Stored Procedure in datediff Couldn't execute stored proc. in date diff
    SELECT DATEDIFF(DAY,'2012-11-23',(exec AddValorDate 3,'2012-11-26'))
    Msg 156, Level 15, State 1, Line 1
    Incorrect syntax near the keyword 'exec'.
    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near ')'.

A: You should make AddValorDate a function rather than a stored procedure. Then you can call it in your query.

A: The following will solve your problem if you cannot convert the stored procedure to a function.
declare @date table
(
    theDate datetime
)
insert into @date
exec AddValorDate 3,'2012-11-26'
SELECT DATEDIFF(DAY,'2012-11-23',theDate) from @date


text:
Q: Lookup and replace column values using dplyr in r Although I found few discussions but couldn't find a proper solution within dplyr.
My main table consists of more than 50 columns and have 15 lookup tables. Each lookup tables has around 8-15 columns. I have multiple lookups to perform and since it becomes really messy with select statements (either by selecting or removing with a minus), I would like to be able to replace column values on the fly.
Is this possible using dplyr? I have provided below just a sample data for better understanding.
I would like to do VLOOKUP (like excel) with city in table with lcity in lookup and replace values of city with newcity.
> table <- data.frame(name = c("a","b","c","d","e","f"), city = c("hyd","sbad","hyd","sbad","others","unknown"), rno = c(101,102,103,104,105,106),stringsAsFactors=FALSE)
>lookup <- data.frame(lcity = c("hyd","sbad","others","test"),newcity = c("nhyd","nsbad","nothers","ntest"),rating = c(10,20,40,55),newrating = c(100,200,400,550), stringsAsFactors = FALSE)
> table
  name    city rno
1    a     hyd 101
2    b    sbad 102
3    c     hyd 103
4    d    sbad 104
5    e  others 105
6    f unknown 106
> lookup
   lcity newcity rating newrating
1    hyd    nhyd     10       100
2   sbad   nsbad     20       200
3 others nothers     40       400
4   test   ntest     55       550

My output table should be
  name    city rno
1    a    nhyd 101
2    b   nsbad 102
3    c    nhyd 103
4    d   nsbad 104
5    e nothers 105
6    f    <NA> 106

I have tried below code for updating values on the fly, but this creates another dataframe/table instead of a character vector
table$city <- select(left_join(table,lookup,by=c("city"="lcity")),"newcity")

A: One solution could be:
Note: The data shown by OP and created with commands are different for lookup. I have used the data shown for lookup in tabular format by OP.
library(dplyr)
# Data from OP
table <- data.frame(name = c("a","b","c","d","e","f"),
    city = c("hyd","sbad","hyd","sbad","others","unknown"),
 rno = c(101,102,103,104,105,106),stringsAsFactors=FALSE)
lookup <- data.frame(lcity = c("hyd","sbad","others","test"),
newcity = c("nhyd","nsbad","nothers","ntest"),
rating = c(10,20,40,55),newrating = c(100,200,400,550),
 stringsAsFactors = FALSE)

table %>%
  inner_join(lookup, by = c("city" = "lcity")) %>%
  mutate(city = newcity) %>%
  select(name,   city, rno)

  name    city rno
1    a    nhyd 101
2    b   nsbad 102
3    c    nhyd 103
4    d   nsbad 104
5    e nothers 105


text:
Q: A prettier way to handle spaces with enters in YAML This is more of a styling question. I have this ugly piece of code:
- name: download something
  shell: "wget https://www.{{ my_var }}\
    a_string\
    {{ a_very_long_string_to_show_what_i_mean }}"

In my opinion, this looks very ugly. Since the URL must be a 'whole', without spaces and quoting and whatnot, I need to escape each newline with a \. Yuck.
However, I can't use breaks, e.g. > or | since that will include spaces in the end result, and the code will error.
Following the ansible-lint guidelines, I do not want the string size on a single line to be larger than something about 84 characters. In this example, when I have to download a file, I can't simply put the string on a single line.
Expected output:
- name: pretty download something
  shell:
    wget https://www.{{ my_var }}
    a_string
    {{ a_very_long_string_to_show_what_i_mean }}

A:
However, I can't use breaks, e.g. > or | since that will include spaces in the end result, and the code will error.

That is actually only an half true statement.
You can combine it with the whitespace control mechanism of Jinja to remove those unneeded whitespaces.
Basically, adding a dash to the opening or the closing of an expression blocks do trim the extraneous whitespace or carriage return before or after it.

Given:
- hosts: localhost
  gather_facts: no

  tasks:
    - debug:
        msg: >-
          wget https://www.{{ my_var -}}
          a_string
          {{- a_very_long_string_to_show_what_I_mean -}}
      vars:
        my_var: example.org/
        a_very_long_string_to_show_what_I_mean: _foo

This yields:
ok: [localhost] =>
  msg: wget https://www.example.org/a_string_foo

Note that in:
wget https://www.{{ my_var -}}

The dash on the opening moustache is not needed, because there is no extra space before that variable.


text:
Q: Ionic tabbing through password and text I have a ionic project in which i'm  supposed to tab through  a password fields. Its a usual change password scenario i just can't tab through like i would in PC ,in android the GO button just right away submits the form i want a functionality like  number does in ionic you know the next button please help.
And thanks a bunch in advance.


text:
Q: Why are read/write speeds on my Time Machine drive so low? So I have an external SSD connected with a SATA to USB 3.0 adapter to my retina MacBook Pro. The wire supports speeds up to 6 Gbps. I could write to the SSD itself at such a high speed.
I created two partitions on the SSD – one for the TM backups, and one for storing files. However, whenever I try to transfer files to it now, the maximum speed it will reach is 20 MBps.
Is there a reason that it has become so much slower? Is this an inevitable consequence of having a TM drive, or is this an unusual circumstance which should not be occurring?


text:
Q: Xclip realtime clipboard backup? As is known to all of us, clipboard is managed by the program itself in most Linux distribution, which means that the content in clipboard will disappear when the hosting program halts.
However, clipboard managers like xclip seems to be exceptions. Even we got return value from these programs, we still can paste contents from the clipboard. So, I wonder if it possible to make xclip a daemon service which realtime backups content in clipboard. In this way, we can still available to paste contents from clipboard even if the original program halts for every process.
If so, I believe it will save a lot efforts, especially you don't need to re-open your closed libreoffice to re-copy in order to paste some sentences.

A: If you are planning to write your own clipboard manager, you might look at this python example which uses the gtk library to do most of the work. You might want to change SELECTION_CLIPBOARD to SELECTION_PRIMARY. The class is documented here.
Selections can be rich text, or images, but if you only want to handle text it can be simpler.
This much shorter example just prints the selection every time it changes, and might be enough for you to keep a history of text selections.
parcellite claims to do what you want, keeping a history of selections, but I cannot test it as I don't use a suitable desktop environment.
If you use gnome, you can try gpaste, which should be available as a package. It is a clipboard manager, but seems to use dbus rather than the X11 selection mechanism, so it may not work with pure X11 clients, but only gnome applications.
autocutsel could also be a starting point if you program in C. It copies the PRIMARY selection to cutbuffer 0 whenever it changes, to provide compatibility with some other systems when using VNC.

A: Have a look at xclipboard. Unfortunately, it only stores CLIPBOARD selections, while most modern X applications only use PRIMARY selections ...
But the source is available, you can change it as you like.


text:
Q: Why is immutability set on types (rather than variables) in Julia? In Julia, why is immutability a "property" of overall types (in the Julia sense of the word, so more akin to a struct or class in other languages) rather than variables?
e.g. In Rust (and I think most languages with support for immutability), whether something is immutable is set on specific variables rather than overall types - i.e. there are no separate Vector vs ImmutableVector structs. To create an immutable vector, I do let v = Vec::new(). To create a mutable one, I do let mut v = Vec::new(). mut is thus a keyword that can apply to any struct.
This seems more convenient, because you can make anything immutable, and variables are immutable by default (which the Julia folks want people to do as much as possible [1]). Are there pragmatic or performance gains with the Julia approach instead?
1: https://github.com/JuliaLang/julia/issues/13#issuecomment-11007166

A:
whether something is immutable is set on specific variables rather than overall types

I think there's some confusion here about what meaning we give to types and values.
In your example you give a mutable and immutable vector:
let v = Vec::new().
let mut v = Vec::new()

So these appear to have the same type, "Vec", yet somehow the second one is immutable. You've tagged it with an extra property of immutability via a new keyword, "mut".
You could imagine this property as part of the type as well, e.g.:
let v = Vec<Pure>::new().
let v = Vec<Mutable>::new().

Using a type parameter to pass in the mutable/immutable tag. One benefit is no need for an extra keyword, but it requires a type system that supports higher-order types.
The "mut" keyword is really just another way to tell the compiler about a particular property -- it adds "type" information. That information could also be passed directly in type syntax, if the type system was expressive enough. Either way, the compiler knows the property and can make optimizations regarding it.
So, in summary, even if mutability/effects are not part of the concrete type syntax, they are still logically part of the "type" as the compiler sees it. Tricks like 'mut' keywords are ways to annotate the type with this information, in the same way parameters to types behave in other languages.

A: I think this is largely a semantic distinction. While somewhat less convenient than the Rust syntax, if you really want you can do the same thing in Julia with abstract types:
abstract MyType
type MyTypeMut <: MyType
    a::Int
end
immutable MyTypeImmut <: MyType
    a::Int
end

Now declare your variables using the appropriate Mut/Immut type, but for any function arguments that need type declarations, use MyType.


text:
Q: Nginx gzip compression not working despite following official Nginx documentation / online research The Issue
I'm at wits end so decided to post a query, I am attempting to set up gzip compression on an nginx docker container after I noticed lighthouse was complaining a number of my clients sites don't have it enabled. All offending sites have gzip compression settings in their config with the right settings and types added but no matter what I change it comes through as uncompressed. I've tested this through both browser and using a CURL request and no change.
I've looked through numerous tickets both on here and elsewhere and none of the solutions have worked despite lots of config fiddling.
What I've tried
For the purposes of this ticket and testing I have created a completely 'virgin' docker project with a default.conf file containing the site config and a public/ folder containing an index.html and test-css.css file.
You can find this example project here: https://github.com/MajorFailz/so-issue-nginx-docker-example
The config file simply serves the folder and contains the gzip settings recommended by nginx's own article here: https://docs.nginx.com/nginx/admin-guide/web-server/compression/
Dockerfile
FROM nginx:1.21

RUN mkdir /app

WORKDIR /app

COPY ./public /app/public

COPY ./conf/default.conf /etc/nginx/conf.d/default.conf

default.conf
server {
    gzip on;
    gzip_types      text/plain application/xml text/css;
    gzip_proxied    no-cache no-store private expired auth;
    gzip_min_length 1000;

    location / {
        root /app/public;
    }
}

Testing with browser
When this project is booted up and viewed in chrome, opening the development tab and viewing the index.html shows that it is being served with gzip compression:

Now if take a look at the test-css.css file, we can see it is not being compressed:

Testing via console
So, after doing some research there appears to be instances were Chrome or various windows antiviruses and decompress things before reaching the browser. So I go and test from a linux VM using curl to attempt to fetch the file with gzip and see what it says.
master@apex:~$ curl -H "Accept-Encoding: gzip" -I http://www.apex.local/test-css.css
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Date: Tue, 11 Jan 2022 15:38:00 GMT
Content-Type: text/css
Content-Length: 53790
Connection: keep-alive
Last-Modified: Tue, 11 Jan 2022 14:55:59 GMT
ETag: "61dd9a7f-d21e"
Accept-Ranges: bytes

So still no compression! So it doesn't appear to be the browser, additionally I used a site performance report website to test it and encountered the same issue.
From further research the issue can be if nginx doesn't have the gzip module installed so after digging I run this command from within the container which tests to see if it was compiled with gzip:
root@127b59858b48:/app# 2>&1 nginx -V | tr -- - '\n' | grep _module | grep gzip
http_gzip_static_module

So it has the module! So what the hey?
Additional information
I've tried numerous combinations of config settings and also tried different OS setups for the nginx docker image (my projects run on alpine so thought it may be a factor) but the results are consistent.
Client nginx config example
An example of the current configuration copy/pasted from one my clients websites:
    gzip on;
    gzip_min_length 10240;
    gzip_comp_level 1;
    gzip_vary on;
    gzip_disable msie6;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types
        # text/html is always compressed by HttpGzipModule
        text/css
        text/javascript
        text/xml
        text/plain
        text/x-component
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/rss+xml
        application/atom+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        image/svg+xml;

Tickets for reference
I've looked at numerous tickets but these are three recent ones I've still got open in my browser:

*

*https://serverfault.com/questions/915928/gzip-not-working-on-nginx/923396

*nginx gzip compression doesn't seem to work

*nginx gzip compression not working

A: It all works on my Debian 11 Host
$:/so-issue-nginx-docker-example# curl -Iv -H "Accept-Encoding: gzip" 127.1:49153/test-css.css
*   Trying 127.0.0.1:49153...
* Connected to 127.1 (127.0.0.1) port 49153 (#0)
> HEAD /test-css.css HTTP/1.1
> Host: 127.1:49153
> User-Agent: curl/7.74.0
> Accept: */*
> Accept-Encoding: gzip
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Server: nginx/1.21.5
Server: nginx/1.21.5
< Date: Wed, 12 Jan 2022 09:12:35 GMT
Date: Wed, 12 Jan 2022 09:12:35 GMT
< Content-Type: text/css
Content-Type: text/css
< Last-Modified: Wed, 12 Jan 2022 09:04:47 GMT
Last-Modified: Wed, 12 Jan 2022 09:04:47 GMT
< Connection: keep-alive
Connection: keep-alive
< ETag: W/"61de99af-d21e"
ETag: W/"61de99af-d21e"
< Content-Encoding: gzip
Content-Encoding: gzip

I have noticed in your Browser as well as curl the NGINX Version is 1.18.0. The Dockerfile you have shared uses NGINX Version 1.21. Given that, are you sure you are sending the curl to the correct instance or is there any other NGINX server proxying the traffic before it reaches the "Dockerized" NGINX?
Can you please double check? I will test the setup with 1.18 to make sure it is not the version.
Update: It works with 1.18.0 as well
HTTP/1.1 200 OK
< Server: nginx/1.18.0
Server: nginx/1.18.0
< Date: Wed, 12 Jan 2022 09:52:00 GMT
Date: Wed, 12 Jan 2022 09:52:00 GMT
< Content-Type: text/css
Content-Type: text/css
< Last-Modified: Wed, 12 Jan 2022 09:04:47 GMT
Last-Modified: Wed, 12 Jan 2022 09:04:47 GMT
< Connection: keep-alive
Connection: keep-alive
< ETag: W/"61de99af-d21e"
ETag: W/"61de99af-d21e"
< Content-Encoding: gzip
Content-Encoding: gzip


text:
Q: Witcher 2 Gargoyles: How to get in the last district? The question is all in the title. I'm talking about the district on the left of gate when you arrive.

A: Not exactly sure where you are but I guess this:
Amphitheater area is accessible from the hallways leading out the far side of the town square. Along the amphitheater, head to the right and you'll find a room where gargoyles attack
Here is full quest guide
Map

Video guide


text:
Q: How to visual/text toolbar button in ckeditor5     ClassicEditor.create( document.querySelector( '.editor' ), {
            // extraPlugins: [ AnnotationsUIs ],
    // plugins: [ Mention,],

    removePlugins:['Title'],

            toolbar: {
                items: [

        "alignment:left", "alignment:right", "alignment:center", "alignment:justify", "alignment", "undo", "redo", "blockQuote", "bold",  "link", "ckfinder", "selectAll", "heading", "horizontalLine", "htmlEmbed",  "indent", "outdent", "italic",  "numberedList", "bulletedList", "mediaEmbed", "pageBreak", "specialCharacters", "restrictedEditingException", "strikethrough", "subscript", "superscript", "insertTable", "tableColumn", "tableRow", "mergeTableCells", "tableCellProperties", "tableProperties", "textPartLanguage", "todoList", "underline"

      ],
      shouldNotGroupWhenFull: true,
    },

            mention: {
        feeds: [
            {
                marker: '@',
                feed: [ '@test' ],
                // itemRenderer: customItemRenderer
            },
        ],
            },
            language: 'en',

        } )
        .then( editor => {
    window.editor = editor;

        } )
        .catch( error => {

            console.error( error );
  } );
});

Which toolbar or plugin is missing?
I have added almost plugging and toolbar items.
CKEditor 5 doesn't have any documentation about the text/visual button. I want to add a toggle button which show me HTML view and text in editor.

A: It looks like this feature was added in May 2021, a couple of weeks after your question!
There is a SourceEditing feature which adds a 'Source' toggle button - https://ckeditor.com/docs/ckeditor5/latest/features/source-editing.html (scroll down for a demo and how to install it).
But it is considered experimental currently, has some limitations of which editors it works with, and note that some HTML will be ignored (e.g. for HTML features you don't have a plugin loaded for).


text:
Q: Custom DSL runs in groovy 3.0.x but fails at runtime in 2.5.x I have a strange runtime bug where custom DSL based on AbstractFactory compiles and runs fine with groovy 3.0.x but fails at runtime under 2.5.x.
Here's the code:
  @Test
  void sayTest() {
    PerCLScript script = percl.script {
      say language: 'en-US', loop: 1, conferenceId: 'confId', text: 'some text', enforcePCI: false
    }

    compare('[{"Say":{"language":"en-US","conferenceId":"confId","text":"some text","enforcePCI":false,"loop":1}}]', script.serializeToPerCL())
  }

Runtime error:
groovy.lang.MissingMethodException: No signature of method: com.freeclimb.groovy.PerCLBuilderTest.say() is applicable for argument types: (LinkedHashMap) values: [[language:en-US, loop:1, conferenceId:confId, text:some text, ...]]
Possible solutions: sms(), any(), any(groovy.lang.Closure), tap(groovy.lang.Closure), wait(), wait(long)

I'm building with GmavenPlus 1.8.1, but I tried the eclipse-groovy-compiler with the same results.
      <plugin>
        <groupId>org.codehaus.gmavenplus</groupId>
        <artifactId>gmavenplus-plugin</artifactId>
        <version>1.8.1</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>compileTests</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <invokeDynamic>true</invokeDynamic>
        </configuration>
      </plugin>

PerCLBuilder
class PerCLBuilder extends FactoryBuilderSupport {

  private PerCLScript percl

  public PerCLBuilder(boolean init = true) {
    super(init)
  }

  def registerObjectFactories() {
    registerFactory('script', new ScriptFactory())
    registerFactory('say', new PerCLCommandFactory(Say.class))
...

  }

  class PerCLCommandFactory extends AbstractFactory {
    Class clazz;

    PerCLCommandFactory(Class clazz) {
      this.clazz = clazz;
    }

    @SuppressWarnings("GrDeprecatedAPIUsage")
    Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes)
        throws InstantiationException, IllegalAccessException {
      clazz.newInstance()
    }
...


text:
Q: How do I get my Facebook app to show something on the top right corner? Here is what the top right corner of my Facebook page looks like:

What is the area under "Create Event" called? I see that some apps can put messages there like the one you see with "4 requests". How can I make my app put something there.
Also I see Birthday notifications there. When I click on the notification a box pops up where I can post to a friend's wall. Is it possible to make my app do that too?
Thanks!

A: This is where application requests shows.
When an application/user sends you an application request, this is where Facebook put it
Please provide more info like the programming language you use and if this is your first application - that can help direct you in the right direction


text:
Q: Vertical scrollbar for customizing table in google chart I am customizing table in google chart. All i need is fixing the header and footer of table and enabling an vertical scrollbar in the remaining rows of table.
Following is the code i have tried to use..
Please help me..Thanks in advance


text:
Q: How to input two numbers and output their sum in SML-NJ I want to write a sample program that input's two numbers from the user and print their sum as output in SML-NJ. The two numbers should be integers and each integer will be given in a new line. It is guaranteed that the input will be of integer type and there is no need to check it. I have installed the SML-NJ compiler and I am compiling using the ml-build command.

A: Since you don't specify what kind of numbers you would like as input, how to extract the numbers from the input, or what should happen in case any errors occur, I will assume integers, one integer per line, and that nothing should happen in case any errors occur.
fun getInt () =
    (case TextIO.inputLine TextIO.stdIn of
          NONE => NONE
        | SOME s => (case Int.fromString s of
                          NONE => NONE
                        | SOME n => SOME n))

fun getTwoInts () =
    (case getInt () of
          NONE => NONE
        | SOME i => (case getInt () of
                          NONE => NONE
                        | SOME j => SOME (i,j)))

fun sumAndPrintTwoInts () =
    (case getTwoInts () of
          NONE => ()
        | SOME (i,j) => print (Int.toString (i+j)))

But there are many ways that those functions could be structured. For example,
infix 3 >>=
fun NONE >>= _ = NONE
  | (SOME a) >>= f = f a

fun getInt () =
    TextIO.inputLine TextIO.stdIn >>= Int.fromString

fun getTwoInts () =
    getInt () >>= (fn i =>
    getInt () >>= (fn j => SOME (i,j)))

fun sumAndPrintTwoInts () =
    getTwoInts () >>= (fn (i,j) => (print (Int.toString (i+j)); NONE))


text:
Q: How to disconnect user from radius? I want to disconnect user from radius but it is not working. i am using this command
echo User-Name=$loginId,Framed-IP-Address=$framedipaddress | /usr/local/bin/radclient -x $nasIp:$nasPort disconnect $naspass"

it showing a error like:
radclient: no response from server for ID 91 socket 3.I am using linux centos.

A: echo Command string should be in double quotes. You may not need the framed IP address rather you'd need the client's mac address and User-Name. The password specified should the Radius password that has been set in the clients.conf file.
echo "User-Name=radusertester,Calling-Station-ID=80-CE-B9-70-42-BD" | /usr/local/bin/radclient 127.0.0.1:3799 disconnect radpass


text:
Q: Get result of a mysql query I have a pretty basic website connected to a database and I want to access the result of an SQL query:
$connection = mysql_connect("localhost", "username", "password")
    or die(mysql_error());
mysql_select_db("Database")
    or die(mysql_error());

$query = mysql_query("SELECT path FROM db1 WHERE id > 4");
while($row = mysql_fetch_object($query))
{
    echo $row->path;
}

On the website nothing shows, not even an error
(The SQL code works for sure)

A: Since you stated in comments that there were no id greater than 4,
you could have just done WHERE id >= 4 which means greater than or equal to 4 and you would have had results.
References:

*

*http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html

*http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_greater-than-or-equal


text:
Q: Async call of a FeignClient Springboot with CompletableFuture I want to call async rest endpoints with Feign client and have done the below changes.
When calling it the CompletableFuture.get() doesn't complete.
The while keeps looping...
while(!combinedFuture.isDone()) { log.info("useraccount - waiting for combinedFuture 2: " + request.toString()); }

Interface to call the API:
@FeignClient(value = "clientUser", url = "http://localhost:8898/springboot", fallback = UserFallback.class)
public interface User {

@RequestMapping(method = RequestMethod.GET, value = "/user/", produces = "application/json")
@Async
CompletableFuture<UserInfo> findUserInfo(@RequestHeader(value = "Authorization", required = true) String authorizationHeader);
}

Controller method:
@PostMapping(value = "/springboot/useraccount/", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> userAccount(@requestbody @Valid AuthRequest request) {
log.info("useraccount - request received with request body: " + request.toString());
try {

   if (Strings.isBlank(request.getUsername()) || Strings.isBlank(request.getPassword())) {
       throw new BadRequestException("invalid username or password");
   }

   String token = authorisationService.obtainAuthToken(request.getUsername(), request.getPassword());

   CompletableFuture<UserInfo> userInfo = clientUser.findUserInfo(token);

   CompletableFuture<UserAccountInfo> userAccountInfo = clientAccount.findAccountInfo(token);

   CompletableFuture<Void> combinedFuture
           = CompletableFuture.allOf(userInfo, userAccountInfo);

   while(!combinedFuture.isDone()) {
       log.info("useraccount - waiting for combinedFuture 2: " + request.toString());
   }
   Optional<UserAccountResponse> userAccountResponse = userAccountService.getAccountInfo(
           userAccountInfo.get(), userInfo.get()
   );

   if (userAccountResponse.isEmpty()) {
       throw new BadCredentialsException("Bad Credentials");
   }

   return ResponseEntity.ok().body(userAccountResponse);
   } catch (BadCredentialsException | UnAuthorizedException ex) {
   return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
   } catch (BadRequestException ex) {
   return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
   } catch (ExecutionException e) {
   return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
   } catch (InterruptedException e) {
   return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
   }
}

(update) Have changed a bit to use CompletableFuture.supplyAsync
but now the object is always null...

@Service
public class AccountService {

@Autowired
Account accountClient;

@Async
public Optional<UserAccountInfo> getAccountInfo(String token) {
    return Optional.of(accountClient.findAccountInfo(token));
}

}

A: Managed to solve it like this:
 @Async
public CompletableFuture<UserAccountInfo> getAccountInfo(String token)   {
    try {
        System.out.println(
                "Current Thread account Name: "
                        + Thread.currentThread().getName());
        Thread.currentThread().sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return    CompletableFuture.completedFuture(accountClient.findAccountInfo(token).getBody());
}

The same for the userInfo service. Then on the controller:
CompletableFuture<UserAccountInfo> userAccountInfo = accountService.getAccountInfo(token);
       CompletableFuture<UserInfo> userInfo = userService.getUserInfo(token);

       Optional<UserAccountResponse> userAccountResponse = userAccountService.getAccountInfo(
               userAccountInfo.get(),userInfo.get()
       );

So that means both services will start running each in a new thread while the main thread continues ran until find the first .get().
By doing it like that the maximum waiting time to finish is the time of the thread that takes more time and not the sum of both as it happens if it is a synchronous.
Thanks!


text:
Q: shell script "tar" error while running in jinja2 While running shell script in jinja2, I'm getting some errors.
Commond is:
resultFilesPath=/var/data/output
cd $resultFilesPath;
tar czvf {% for tar_file in outputs.output %}{{ tar_file.path }} ./* {% endfor %};

error is:

tar: Old option 'f' requires an argument.
  Try 'tar --help' or 'tar --usage' for more information.

I don't know the reason, please help me.

A: As stated in the error. Look at the man page for tar. The option f requires you to specify the target archive file name:
tar czvf archive.tar.gz {% for tar_file in outputs.output %}{{ tar_file.path }} ./* {% endfor %};


text:
Q: Rearranging iBooks on bookshelf manually I'm unable to manually rearrange my iBooks bookshelf manually and would like to put individual books as well as a 'series' of books in their right order.It lets me 'edit' and move to the position I want but then re-sets itself back to the order the books started with when I press 'done'. I have tried rearranging and not pressing the 'done' but that doesn't work either.either way, once you re-open the bookshelf it's reset itself again. What can I do to rearrange my books in the order I want and save the changes without my iPad re- setting them? Thank- you for your help.

A: Are you doing it through the categories of purchased books or PDFs or collection? Try doing it through the collection.
Another thing you could try is go to your iPad's Settings, click on the Settings icon and scroll past the General settings and other apps until you see iBooks then click on where it says "Show All Purchases" and slide it to No. Then try rearranging again from your bookshelf collections.
I have no idea why it worked for me. I had your same problem with rearranging with the edit on and then when I clicked done it would revert back to the original unwanted order. But the steps I just described fixed it for me. I will now try and reselect show all purchases and see if it undoes what I just "fixed". I do not even know what made me take those steps - maybe intuition. But it worked like a charm.


text:
Q: how to attach local folder into qtquick I need to load images in my qml window. Usually I load it from a resource file which will be deployed along with my .pro file. But since the image folder size is too big the loading time is more. Is there any way by which a local folder can deploy with the qtquick application?. And how can I refer images in qml file.(The path of image). I am using Qt 5.5 version.

A: Using qmake to copy files
You can use qmake to copy the image files to the build directory so that the application can find them. I'm currently using this solution in my project because I don't want to use make install. You should read that answer to understand it, but to give it some context here:
# using shell_path() to correct path depending on platform
# escaping quotes and backslashes for file paths
copydata.commands = $(COPY_FILE) \"$$shell_path($$PWD\\archive.png)\" \"$$shell_path($$OUT_PWD)\"
first.depends = $(first) copydata
export(first.depends)
export(copydata.commands)
QMAKE_EXTRA_TARGETS += first copydata

As the answer says, this is just for one file, so you'll need to use $(COPY_DIR) if you want to copy a whole directory of images over. This is probably not the best approach, but qmake is difficult to use, so when it works for me, I'm happy. :)
Once you've got that working, you can use this answer to refer to the images on the file system:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

int main(int argc, char *argv[]) {
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec(); }

QML:
Image {
    source: "file:///" + applicationDirPath + "/images/image.png"
}

This sets a QML context property that points to the directory that the executable is running in, and then uses that directory to form the path to the image.
rcc's Compression Options
Note that if most or all of your images are PNGs, you could see if rcc's compression options help with the size of the executable:

Resources are compressed by default (in the ZIP format). It is
  possible to turn off compression. This can be useful if your resources
  already contain a compressed format, such as .png files. You do this
  by giving the -no-compress command line argument.

rcc -no-compress myresources.qrc

rcc also gives you some control over the compression. You can specify
  the compression level and the threshold level to consider while
  compressing files, for example:

rcc -compress 2 -threshold 3 myresources.qrc


text:
Q: Typing Urdu/Arabic in TextEdit/TextView in Android I want to create a database in which i can add and retrieve  the Urdu words. for this purpose i installed Inpage 2009 professional and copied its fonts (.ttf)  into assets folder but it gave an error i.e
I also installed UrduFonts.exe and copied its font JameelNooriNastaleeq.ttf but it also gave the same error. i need the Urdu font that is compatible to the android , the font that can add and retrieve Urdu to and from the database using android.
this is how i coded foa a Lcd2Mono.ttf and i am having the true experience of that font but i am unsuccessful. here is my piece of code..
private EditText txt,start,urdu;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 urdu=(EditText) findViewById(R.id.urdu);
 try
 {
 urdu.setTypeface(Typeface.createFromAsset(this.getAssets(),"urdu.ttf"));
 urdu.setText("ur text");
 }
 catch(Exception ex)
 {
 start.setText(ex.toString());
 }

i did some with Inpage Fonts and got Exception that Native Font.....

A: i think JameelNooriNastaleeq.ttf font is very huge, more than 10M (maybe somehow connected to your problem), i recommend to try something much more smaller like: http://www.quran.or.kr/urdu/font/asunaskh.ttf
but still issue with connecting the urdu characters, like in this question:
how to add language support to android
what exception you got?


text:
Q: discord.py Pillow train meme command text overlapping So whenever I try to do this command, It works successfully but the text overlays instead of pasting the empty train meme template over it
@client.command()
async def trainmeme(ctx, *, text):
  text = text.split(",")
  text2 = text[0]
  text3 = text[1]
  img = Image.open("train.jpg")
  draw = ImageDraw.Draw(img)
  drawer = ImageDraw.Draw(img)
  font = ImageFont.truetype("Arimo.ttf", 50)
  drawer.text((197, 165), text=text2, font=font)
  draw.text((87, 531), text=text3, font=font)
  img.save("train.jpg")
  img.paste(img, (7, 5))
  await ctx.send(file = discord.File("train.jpg"))

Here is a picture of what happens when I try to do the command multiple times

A: It's because you're using img.save("train.jpg") which overwrites the original image file.


text:
Q: Rotating a String with StringBuilder instead of a character array Aiming to check whether a String is a rotation of another String by rotating it until it matches.
Tried to use a StringBuilder to rotate said String instead of a char[ ] because it is more efficient, but I can't determine why the String is only rotating once, instead of a.length()-1 times.
public static void main(String[] args) {

    String a = "erbottlewat";
    String b = "waterbottle";

    System.out.println(isSubstring(a,b));

}

    public static boolean isSubstring(String a, String b) {

    StringBuilder strbdr = new StringBuilder(a); // can pick either string. if one ends up matching the other one, we know it is a rotation

    for(int i = 0; i < a.length()-1; i++) { // this is the number of times the program will run

        char temp = a.charAt(0);

        for(int j = 0; j < a.length()-1; j++) {
            strbdr.setCharAt(j, a.charAt(j+1)); // tried to use a stringbuilder because i read it was the most efficient way.
        }

        strbdr.setCharAt(a.length()-1, temp);

        System.out.println(strbdr.toString());

        if(strbdr.toString().equals(b)) {
            return true;
        }
    }
    return false;

}

}

A: My mistake was indexing String a (which never changed) to replace elements with the StringBuilder. By replacing strbdr.setCharAt(j, a.charAt(j+1)); with strbdr.setCharAt(j, strbdr.charAt(j+1));, I was able to save my changes and rotate the string properly.
Solution:
public static void main(String[] args) {

    String a = "erbottlewat";
    String b = "waterbottle";

    System.out.println(isSubstring(a,b));

}

public static boolean isSubstring(String a, String b) {

    StringBuilder strbdr = new StringBuilder(a);

    for(int i = 0; i < a.length()-1; i++) {

        char temp = strbdr.charAt(0);

        for(int j = 0; j < a.length()-1; j++) {
            strbdr.setCharAt(j, strbdr.charAt(j+1));
        }

        strbdr.setCharAt(a.length()-1, temp);

        System.out.println(strbdr.toString());

        if(strbdr.toString().equals(b)) {
            return true;
        }
    }
    return false;

}


text:
Q: Ruby on Rails: just upgraded to rails 3. some of my links don't work the link:

<%= link_to "Map", :controller => :info, :action => :map  %>

routes:
  resources :link_pages
  resources :services
  resource :user_session
  resource :account, :controller => "users"
  resources :password_resets
  resources :users
  resources :addresses
  resources :info

  match "/home", :to => 'info#home'
  match "/register", :to => 'users#new'

  root :to => 'info#home'

but when I click "Map", it thinks I want to go to info#show =\
   match ':controller(/:action(/:id(.:format)))'

A: Try <%= link_to "Map", {:controller => :info, :action => :map}  %> (notice the Hash)


text:
Q: Receiving NaN value in Fortran app I'm developing an Fortran application for numerically solving Boundary Value Problem for second order ODE of the type: -y''+q(x)*y=r(x). In this application I use Gauss-ellimination algorithm to solve the linear system of equations and write the solution in file. But for the solution vector I receive NaN. Why is that happen? Here is some code.
      subroutine gaussian_solve(s, c, error)

    double precision, dimension(:,:), intent(in out) :: s
    double precision, dimension(:),   intent(in out) :: c
         integer        :: error

    if(error == 0) then
        call back_substitution(s, c)
    end if

     end subroutine gaussian_solve
!=========================================================================================

!================= Subroutine gaussian_ellimination ===============================
      subroutine gaussion_ellimination(s, c, error)

    double precision, dimension(:,:), intent(in out) :: s
    double precision, dimension(:),   intent(in out) :: c
    integer,            intent(out)  :: error

    real, dimension(size(s, 1)) :: temp_array
    integer, dimension(1)       :: ksave
    integer                     :: i, j, k, n
    real                        :: temp, m

    n = size(s, 1)

    if(n == 0) then
        error = -1
        return
    end if

    if(n /= size(s, 2)) then
        error = -2
        return
    end if

    if(n /= size(s, 2)) then
        error = -3
        return
    end if

    error = 0
    do i = 1, n-1
        ksave = maxloc(abs(s(i:n, i)))
        k = ksave(1) + i - 1
        if(s(k, i) == 0) then
            error = -4
            return
        end if

        if(k /= i) then
            temp_array = s(i, :)
            s(i, :) = s(k, :)
            s(k, :) = temp_array
            temp = c(i)
            c(i) = c(k)
            c(k) = temp
        end if

        do j = i + 1, n
            m = s(j, i)/s(i, i)
            s(j, :) = s(j, :) - m*s(i, :)
            c(j) = c(j) - m*c(i)
        end do
    end do

     end subroutine gaussion_ellimination
     !==========================================================================================

   !================= Subroutine back_substitution ========================================
     subroutine back_substitution(s, c)

    double precision, dimension(:,:), intent(in) :: s
    double precision, dimension(:),   intent(in out) :: c

    real    :: w
    integer :: i, j, n

    n = size(c)

    do i = n, 1, -1
        w = c(i)
        do j = i + 1, n
            w = w - s(i, j)*c(j)
        end do
        c(i) = w/s(i, i)
    end do

      end subroutine back_substitution

Where s(i, j) is the matrix of coefficients of the system and c(i) is the solution vector.

A: You should never write your own routines for gaussian elimination or similar matrix operations.   Ubiquitous packages like LAPACK will have faster, more accurate versions than anything you're likely to code yourself; in LAPACK you'd use a combination of _getrf and _getrs for general matricies, but if you have banded or symettric matricies there are special routines for those, too.   You should find it quite easy to find and install an optimized linear algebra package for your system.   (Look for package names like atlas or flame or gotoblas).
In the code above, there should presumably be a call gaussion_ellimination(s, c, error) near the start of your gaussian_solve routine, your temp_array (and temp and m and w)  should also be double precision to avoid losing precision from your double precision matrix, checking for exact equality to floating point zero is a risky strategy, and I'd check your input matrix - if there are any linear degeneracies you will get all NaNs (particularly if it's the last row vector which is linearly degenerate with any of the earlier ones).
If that doesn't fix the problem, you can use signaling NaNs to find out where the  problem first arises - Force gfortran to stop program at first NaN - but you're really better off just using existing packages for stuff like this, which have been written by people who have studied the numerical solution of sets of linear equations for years.


text:
Q: How can you conditionally set services in the docker-compose.yml file? I'm new to using Docker and Cake. At the moment we have a simple Cake task that runs the DockerComposeUp() method that takes a DockerComposeUpSettings object. The docker-compose.yaml file holds some info on a service that I want to conditionally run (serviceA):
version: "1.0"
services:
    serviceA:
        image: someImage
        ports:
          -"000000"
          -"000001"
    serviceB:
        image: someOtherImage
        anotherProperty: somethingElse
        ports:
          -"111111"

I've tried splitting out serviceA into a separate docker-compose file called 'docker-compose.serviceA.yaml' and calling it by adding to the DockerComposeUpSettings.ArgumentCustomization the following:
if(some setting)
{
    dockerComposeUpSettings.ArgumentCustomization = builder => builder.Append("-f docker-compose.yaml -f docker-compose.serviceA.yaml");
}

However, Cake throws the following error:

"unknown shorthand flag: 'f' in -f"

How can I merge to docker-compose files as part of the DockerComposeUp method using Cake?
Update
I've found there is a 'Files' property on the DockerComposeUpSettings object (inherited from DockerComposeSettings object), where you can declare the configuration files. So I've added:
if(some flag)
{
    dockerComposeSettings.Files = new[]{ "docker-compose.yaml", "docker-compose.serviceA.yaml" };
}

A: I don't know much about docker, but looking at the docs here and here it seems it would be important to have the -f option set before the command specified on the commandline. Your customization (builder.Append()) puts them at the end of the commandline.
Have you tried setting the Files property of the DockerComposeUpSettings? That looks like what you are looking for.


text:
Q: Does Copying of const shared memory objects make sense in Multithreading This question is not about thread savety.
The objects I am talking about are const vectors (of point clouds) used as input in a multithreaded routine. As they are const, I can share them without worrying about thread savety.
It is about getting better runtime performance. My multithreaded routine is by far not as fast as I expect it to be. I run 11 parallel threads (maximum number is 12 on my six core), but I only get something like half the runtime of the non multithreaded approach.
The counter argument to make copies (inefficient in memory usage) can also be ignored. Memory is in my case not an issue.
My routine relies on a lot of spatial queries on the input vector. As the vector is shared, I expect the loss of efficiency here.
My question, before I modify my complex code is: If I generate 11 copies of the vector for my 11 parallel threads, will this be only a minor improvement, because all 11 objects still share the same physical memory? My knowledge of the hardware of a computer is too limited to answer this question.


text:
Q: Kdevelop and CMake cooperation I wonder what are the restrictions on using CMake files (I guess, especially using subdirectories and/or libraries, as well as the location of the executables)
(When I use the trivial Hello example, KDevelop works fine, I can even debug my project. When I attempt to approach it to my real target project, and I edit the CMakeList.txt file to create library in a subdirectory, and move the executables in a separate subdirectory, KDevelop gets partially working: it builds the executables, the executables work in stand-alone mode, but not under KDevelop, and of course I cannot debug.)
I guess that some kind of visibility problem is happening: i.e. although CMake thinks my arrangement is OK (i.e. produces correct Makefile and even the executables), somehow KDevelop gets lost, and since it does not see some file at the place it expects, it stops working. Is there any rule set, what NOT to use in CMake?
For any case I attach my cmake files (the main one and the one for the library). Do I make something wrong?
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
set(CMAKE_LEGACY_CYGWIN_WIN32 0)

project(kmanycore CXX C)

include_directories(../lib)

add_subdirectory(lib)

add_executable(../bin/kmanycore ../src/main.cpp)
add_executable(../bin/kmanycore_test ../src/main_test.cpp)

target_link_libraries(../bin/kmanycore manycore)
target_link_libraries(../bin/kmanycore_test manycore)

and
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
set(CMAKE_LEGACY_CYGWIN_WIN32 0)

add_library(manycore src/ToDo.cc)

A: Your CMake file looks weird, and I am not an IDE.
The first argument of add_executable is the name of the executable, no path. It works by change with plain Makefiles. Same with target_link_libraries. And it is unclear who the two projects are related to each other. Usually IDEs keep track of single project; interweaved ones are not supported.


text:
Q: Duplicating a table with partitions in SQL the current database at my work runs on SQL script to generate data as outputs to use, one of the data I often use might be updated so I'm trying to create a back up copy or a duplicate, unfortunately,  I'm a novice in SQL. The system is called Waterdrop and it's not widely used but it runs on Hive SQL.
My understanding of SQL is that this should work:
CREATE TABLE acc_backup LIKE acct;
INSERT INTO acc_backup SELECT * FROM acct;

However, I get an error

Need to specify partition columns because the destination table is partitioned

Not realizing this table had partitions, I then checked:
SHOW PARTITIONS acct;

And in the column dat_dt (which is date not string or decimal) there are 198 partitions that looks like
dat_dt= 2017-09-25
dat_dt= 2017-09-30
dat_dt= 2017-10-05
dat_dt= 2017-10-08
... 198 rows

So how would I copy the data from acc to acc_backup? The table is very big so it takes a long time to run these codes, should I try
CREATE TABLE acc_backup AS SELECT * FROM acct;

or perhaps :
DROP TABLE IF EXISTS acc_backup
SELECT * INTO acc_backup FROM acct;

Or would I need to create an empty table with the exact same 198 partitions to copy the data and how would I attempt that? My ultimate goal is to keep this original chart the same and a backup, so structure/partition of the new table isn't my main concern as long as the data is the same!
Thank you very much! Any notes or suggestion is appreciated. And again sorry I tagged SQL Server before as you can tell I'm very novice to the SQL databases, thanks everyone for correcting me!


text:
Q: Hive code stuck in reduce=99% I run a paragraph of hive code. But it stuck in 99%.
here is my code below:
    insert overwrite table novaya.brand_info
select goods.brandid, goods.brandnm, cate1.cate1_price, cate2.cate2_price, cate3.cate3_price
  from novaya.goods_info goods
    left join
    (select brandid, brandnm, mng_catecode1, avg(sales_price) as cate1_price
    from novaya.goods_info  where brandid is not null
    group by brandid, brandnm, mng_catecode1) cate1
    on goods.brandid=cate1.brandid
    left join
    (select brandid, brandnm, mng_catecode2, avg(sales_price) as cate2_price
    from novaya.goods_info  where brandid is not null
    group by brandid, brandnm, mng_catecode2) cate2
    on  goods.brandid=cate2.brandid
    left join
    (select brandid, brandnm, mng_catecode3, avg(sales_price) as cate3_price
    from novaya.goods_info  where brandid is not null
    group by brandid, brandnm, mng_catecode3) cate3
    on goods.brandid=cate3.brandid
  where goods.brandid is not null ;

The logic is not complex that the cate1, cate2 and cate3 will be appdendix their columns after brandid and brandnm which belong to the goods table. Goods table may be more larger than the three tables.
It may caused by skew. And how can I fix this problem without changing hive settings.
Mant thanks.


text:
Q: Format input currency jquery I'm having some problems creating the mask for the currency field.
1- I need to limit UP TO 18 characters (counting the '.' and the ',') Ex: 999.999.999.999,99
2 - I need you to put more than one '.' (currently only one)
3 - I need this not to happen:

Because when I type it adds the '.' right then before I type in one more number.
My code:

function onlyNumberAmount(input) {
    var v = input.value;
    v = v + '';
    v = parseInt(v.replace(/[\D]+/g, ''));
    v = v + '';
    v = v.replace(/([0-9]{2})$/g, ",$1");
    v = v.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
    input.value = v;
    if(v == 'NaN') input.value = '';
}
<input type="text" class="form-control" id="mP0"  onkeyup="onlyNumberAmount(this)">

A: The following seems to meet your requirements.

function onlyNumberAmount(input) {
  let v = input.value.replace(/\D+/g, '');
  if (v.length > 14) v = v.slice(0, 14);
  input.value =
    v.replace(/(\d)(\d\d)$/, "$1,$2")
     .replace(/(^\d{1,3}|\d{3})(?=(?:\d{3})+(?:,|$))/g, '$1.');
}
<input type="text" class="form-control" id="mP0" onkeyup="onlyNumberAmount(this)">

\d is short for [0-9] as I'm sure you know.
A positive lookahead (?=(?:\d{3})+(?:,|$)) is used to ensure the correct placement of the .
14 is the maximum number of digits that can appear in the string.
Further explanation on request.

A: If, test if the field is already valid
const moneyTest = /(\d{1,3}\.)?(\d{1,3}\.)?(\d{1,3})?(.\d{1,2})?/

if (!moneyTest.test(field)) {

Then, if it's not, separate into the number fields
var digits = /d/g.match(field); // might be field.match(/d/g)

Now you have to see if there was a decimal place in the original number
var dot = field.lastIndexOf(".");

And then you should be good to reconstruct the number.
Question: What happens if there are two dots?


text:
Q: Unordered list in HTML5 with a list/group name How would you create an unordered list of items in HTML5 with a group name at the top? The items should look indented.
Ex:
GroupName1
    Item1
    Item2
    Item3
GroupName2
    Item4
    Item5

A: Why not just do a list within a list?

    Group 1

Item 1

Item 2

Item 3

    Group 2

Item 4

Item 5

A: I reckon scurker's answer is the way to go, but if your groups were really separate from each other, and thus didn't really make sense in one big list, you could do this:

GroupName1

Item1

Item2

Item3

GroupName2

Item4

Item5


text:
Q: ios5 - turning pages in page view controller when in landscape I'm using UIPageViewController and story board in my application.
When in portrait, i'm using following code to jump from one page to another page and its working fine.
int direction = UIPageViewControllerNavigationDirectionForward;
if ([self.modelController currentPage] < pagenum)
{
    direction = UIPageViewControllerNavigationDirectionForward;
}
else if ([self.modelController currentPage] > pagenum)
{
    direction = UIPageViewControllerNavigationDirectionReverse;
}

[self.pageViewController setViewControllers:[NSArray arrayWithObject:[self.modelController viewControllerAtIndex:pagenum storyboard:self.storyboard]] direction:direction animated:YES completion:NULL];

But the same code is not working when we are in landscape mode. How to turn the pages when in landscape?

A: If you look at the Page-Based Application Template in Xcode you find the following UIPageViewControllerDelegate method:
- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        // In portrait orientation: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
        UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
        NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

        self.pageViewController.doubleSided = NO;
        return UIPageViewControllerSpineLocationMin;
    }

    // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
    DataViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
    NSArray *viewControllers = nil;

    NSUInteger indexOfCurrentViewController = [self.modelController indexOfViewController:currentViewController];
    if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) {
        UIViewController *nextViewController = [self.modelController pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
        viewControllers = [NSArray arrayWithObjects:currentViewController, nextViewController, nil];
    } else {
        UIViewController *previousViewController = [self.modelController pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
        viewControllers = [NSArray arrayWithObjects:previousViewController, currentViewController, nil];
    }
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    return UIPageViewControllerSpineLocationMid;
}

When returning UIPageViewControllerSpineLocationMid from the above method, you are telling the UIPageViewController that it should expect to display two UIViewControllers side by side (i.e. two pages).
The key here is that you must pass the correct number of UIViewControllers when calling the UIPageViewController's setViewControllers:direction:animated:completion: method.

*

*Showing two pages? Pass two UIViewControllers.

*Showing one page? Pass one UIViewController.

The code you presented will never pass more than one UIViewController to the UIPageViewController.
If the UIPageViewControllerSpineLocation does not correspond with the amount of UIViewControllers you are passing it will crash or just do nothing.
Let me know if you need further help.


text:
Q: Send Distinguished Name ADFS 2.0 Can you guys help me out on how to send DN in a claim from ADFS 2.0?
Thanks!

A: There doesn't seem to be a standard URI for DN but you can always roll your own.
The ADFS claims rules box is actually configurable - refer ADFS : Selecting claim that's not in the default drop down
So in the "LDAP Attribute" enter "DN" and in the "Outgoing Claim Type" enter something like "http://company.com/identity/claims/DistinguishedName".
Edited:
LDAP attributes see here : Selected LDAP Attributes

A: c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"]
 => issue(store = "Active Directory", types = ("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"), query = "; distinguishedName;{0}", param = c.Value);


text:
Q: MacBook Pro 2012, HDD speed 80MB read/write normal? I have a MacBook Pro 13" (non-retina) from 2012 with a 512GB HDD. I've run some speed test with BlackMagic and those are around 75-80MB/sec for read/write. This seems slow, but maybe this is normal for this configuration.
Are these normal values?

A: Those kinds of speeds are to be expected from a MacBook HDD. For much higher speeds, consider upgrading the HDD to an SSD. (See Macbook Pro Hard drive speed)


text:
Q: Maintain a stock sheet in google sheets with seperate Inventory and Issuance sheets I have 2 sheets which are inventory count and issuance count, both of them have sample numbers and their count. I want to maintain a 3rd stock sheet which will show sample number, its inventory count, the issuance count and the stock count. Stock count is just inventory count - issuance count.
The inventory and issuance count sheets will get updated automatically.
The sample numbers might not be arranged in same manner in inventory count and issuance count sheets, moreover some of the samples which might be there in inventory count might not be there in issuance count, so its issuance count in the stock sheet must be 0.
I have pasted the link to a reference sheet similar to my use-case. Any help will be appreciated. Thanks in advance!

https://docs.google.com/spreadsheets/d/1UDlCzA1WDkIWDNoEffihSH2rKegKHciSP1kqp_QJ-kY/edit?usp=sharing

A: You can place array formulas in the headers that will do what you ask.
All the unique sample numbers:
={
  "Sample Number";
  SORT(UNIQUE(
    {
      UNIQUE(FILTER(Issuance!A2:A, Issuance!A2:A <> ""));
      UNIQUE(FILTER(Inventory!A2:A, Inventory!A2:A <> ""))
    }
  ))
}

Inventory Count:
={
  "Inventory Count";
  ARRAYFORMULA(IF(B2:B = "", "", COUNTIF(Inventory!A2:A, B2:B)))
}

Issuance Count:
={
  "Issuance Count";
  ARRAYFORMULA(IF(B2:B = "", "", COUNTIF(Issuance!A2:A, B2:B)))
}

Stock:
={
  "Stock";
  ARRAYFORMULA(IF(B2:B = "", "", C2:C - D2:D))
}

Look at you sample sheet, all this is there.


text:
Q: Laravel Vue SPA using Sanctum response Unauthorized The Sanctum Auth system on my local machine works well and I have no errors. But my deployed app is having trouble with authorizing a user. When I login it sends a request to get the user data then redirects. After auth completes you are redirected and the app make a GET request for more data. This GET route is guarded using laravel sanctum. But the backend is not registering that the user has made a successful login attempt so it sends a 401 Unauthorized error. Here is some code...
loadUser action from store.js
actions: {
    async loadUser({ commit, dispatch }) {
        if (isLoggedIn()) {
            try {
                const user = (await Axios.get('/user')).data;
                commit('setUser', user);
                commit('setLoggedIn', true);
            } catch (error) {
                dispatch('logout');
            }
        }
    },
}

Route Guard on the routs.js checking to see isLoggedIn (which is just a boolean store locally)
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
    // if (to.meta.requiresAuth) {
        if (isLoggedIn()) {
            next();
        } else {
            next({
                name: 'home'
            });
        }
    } else {
        next();
    }
})

It was pointed out that I had forgotten the withCredetials setting for axios in bootstrap.js. I made this addition but my issue still remains.
window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;

Route middleware guard on the server side (this is where the request is getting turned away)
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('trucks', 'Api\TruckController');
});

In the laravel cors.php config file I changed the "supports_credentials" from false to true
'supports_credentials' => true,

It seems to me that the cookie information is not being over the api call (but I'm really not sure). This setup is working on my local machine but not on the server that I have deployed to.

A: Needed to add an environment variable to the .env file for SANCTUM_STATEFUL_DOMAINS and made that equal the domain name.
In the laravel sanctum.php config file...
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),


text:
Q: Uploading JSON Object to server I have to "POST" JSON Objects to server via ajax calls.
I'm using :
data : { fieldName : JSONObject }
for the data part in the ajax call.
The data is uploaded fine, as a JSON. But it takes the following form :
{ "0" : {key,value} , "1" : {key,value} ... };
How to get rid of the "0","1",etc. that are being added automatically? Is it something that I can handle at the client side, or is it the server side code that is responsible for this? As far as I understand, it's the server side code.

EDIT :
Response Received :
[
    {
        "students": {
            "0": {
                "id": "101",
                "name": "A"
            },
            "1": {
                "id": "102",
                "name": "B"
            },
            "2": {
                "id": "103",
                "name": "C"
            },
            "3": {
                "id": "104",
                "name": "D"
            }
        }
    }
]
JSONObject :
[
    {
        "id": 101,
        "name": "A"
    },
    {
        "id": 102,
        "name": "B"
    },
    {
        "id": 103,
        "name": "C"
    },
    {
        "id": 104,
        "name": "D"
    }
]
Just a guess, is it because the JSONObject is an array , ie [] are causing the probs? Meanwhile I'll just test the same without the [].

A: Use JSON.stringify(object); to convert your JavaScript object into a JSON String.


text:
Q: Changing the environment variables in ubuntu I want to compile a code, and there is a instruction for that. The instruction says that the environment variables of libraries and compilers should be changed as below:
Make sure the compilers and libraries paths are set in the appropriate environment variables (PATH and LD_LIBRARY_PATH). Here are some examples which will need to be adapted for your setup:
On Ubuntu:

  export PATH=/usr/lib/openmpi/bin:${PATH}
  export LD_LIBRARY_PATH=/usr/lib/openmpi/lib:$LD_LIBRARY_PATH
or
  export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/openmpi/lib:$LD_LIBRARY_PATH

I do not know how to change the environmental variables for gfortran and other compilers.
Thanks in advance
Saeed
I reviewed all options in the websites but the issue has not been solved.


text:
Q: Login Logout Scripts issue with Php On Mysqli I entered username='admin' pw='admin'on my login.php that's values true on mysqladmin
and it stops in check_login.php, after I can't see anything .
Here is the codes
check_login.php
      <?php
define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
$username = $_POST['username']; //Set UserName
$password = $_POST['password']; //Set Password
$msg ='';
if(isset($username, $password)) {
    ob_start();
    include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($username);
    $mypassword = stripslashes($password);
    $myusername = mysqli_real_escape_string($dbC, $myusername);
    $mypassword = mysqli_real_escape_string($dbC, $mypassword);
    $sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA('$mypassword')";
    $result=mysqli_query($dbC, $sql);
    // Mysql_num_row is counting table row
    $count=mysqli_num_rows($result);
    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count==1){
        // Register $myusername, $mypassword and redirect to file "admin.php"
        session_register("admin");
        session_register("password");
        $_SESSION['name']= $myusername;
        header("location:admin.php");
    }
    else {
        $msg = "Wrong Username or Password. Please retry";
        header("location:login.php?msg=$msg");
    }
    ob_end_flush();
}
else {
    header("location:login.php?msg=Please enter some username and password");
}
?>

and
admin.php
<?php
session_start(); //Start the session
define(ADMIN,$_SESSION['name']); //Get the user name from the previously registered super global variable
if(!session_is_registered("admin")){ //If session not registered
header("location:login.php"); // Redirect to login.php page
}
else //Continue to current page
header( 'Content-Type: text/html; charset=utf-8' );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Welcome To Admin Page Demonstration</title>

Welcome To Admin Page <?php echo ADMIN /*Echo the username */ ?>

Logout

Put Admin Contents

I tried something for find the error I wrote echo"asdasd" on my check_login.php and I saw "asdasd" untill 21. Line that's line starting with session_register(...). I think here is my problem. But I don't know how to use it.

A: One of two problems...
You're defining $username and then doing session_register("admin").
Or ... you're running on PHP 5.4 which no longer implements session_register().
instead of
session_register("password")

use
$_SESSION['password'] = $password;

A: I have still problems, i cant check to login admin page.I can open admin.php without username and pw.
Here is my changed check_login.php
<?php

error_reporting(E_ALL);
        ini_set('display_errors', 1);
define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
$username = $_POST['username']; //Set UserName
$password = $_POST['password']; //Set Password
$msg ='';
if(isset($username, $password)) {
    ob_start();
    include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($username);
    $mypassword = stripslashes($password);
    $myusername = mysqli_real_escape_string($dbC, $myusername);
    $mypassword = mysqli_real_escape_string($dbC, $mypassword);
    $sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA('$mypassword')";
    $result=mysqli_query($dbC, $sql);
    // Mysql_num_row is counting table row
    $count=mysqli_num_rows($result);
    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count==1){
        // Register $myusername, $mypassword and redirect to file "admin.php"
        $_SESSION['admin'] = $admin;
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        $_SESSION['password'] = $password;
        $_SESSION['name']= $myusername;
        header("location:admin.php");
    }
    else {
        $msg = "Wrong Username or Password. Please retry";
        header("location:login.php?msg=$msg");
    }
    ob_end_flush();
}
else {
    header("location:login.php?msg=Please enter some username and password");
}
?>

here is the admin.php
   <?php
error_reporting(E_ALL);
session_start(); //Start the session
define(ADMIN,$_SESSION['name']); //Get the user name from the previously registered super global variable
// if(!isset($_SESSION['admin']));{ //If session not registered
if( isset($_SESSION['admin']) && $_SESSION['admin'] == '0' ){

header('location:login.php'); // Redirect to login.php page
}
else //Continue to current page

header( 'Content-Type: text/html; charset=utf-8' );

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Welcome To Admin Page Demonstration</title>

Welcome To Admin Page <?php echo ADMIN /*Echo the username */ ?>

Logout

Put Admin Contents

Thanks.


text:
Q: Date picker does not open first click on textfield in swift 2.2 I have datePicker view that does not open at first time click on textField. If I click it second time then the date picker view is opened. I'm confused in this case. Why it did not open at first click? How to show date picker view in first click on UITextField?
Code I have try:
@IBAction func datePick(sender: UITextField)
{
    let datePickerView = UIDatePicker()
    datePickerView.datePickerMode = UIDatePickerMode.Date
    sender.inputView = datePickerView
    datePickerView.addTarget(self, action: #selector(SendSMS.showDatePicker), forControlEvents: UIControlEvents.ValueChanged)
}

func showDatePicker(sender: UIDatePicker) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"

    let timeFormatter = NSDateFormatter()
    timeFormatter.dateFormat = "HH:mm:SS"
    timeField.text = timeFormatter.stringFromDate(sender.date)
    dateField.text = dateFormatter.stringFromDate(sender.date)
}

Output:

A: Instead of setting action with textField try to use delegate method of UITextFieldDelegate.
func textFieldDidBeginEditing(textField: UITextField!) {    //delegate method
    if textField == dateField {
        let datePickerView = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.Date
        textField.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(SendSMS.showDatePicker), forControlEvents: UIControlEvents.ValueChanged)
    }
}

A: It'll also work by setting TextField action event Editing Did Begin. It won't work first time if you set the action Editing Did End.


text:
Q: Journey Builder Open rate 200% How is this possible?  Looks like one of the sends wasn't tracked?

A: This is a result of data lag on the marketing Cloud side.  Depending on the complexity of your journey/email send, you should wait at least an hour for results to normalize.


text:
Q: Como eu printo dados por dados em sql?(seleciona todos os dados, porem só printa um por um em formato de array)!

    $sql = "SELECT * FROM perguntas ORDER BY id_pergunta";
    $execsql = mysqli_query($conn, $sql) or die("Erro");
    while($row = mysqli_fetch_array($execsql)){
        # code...
        $IdPergunta = $row['id_pergunta'];
        $p = $row['pergunta'];
        $ra = $row['respostaa'];
        $rb = $row['respostab'];
        $rc = $row['respostac'];
        $rd = $row['respostad'];
        $vp = $row['valor_pergunta'];

    }
    echo '<?xml version="1.0" encoding="UTF-8" ?>';
    echo '<root>';
    echo '<Pergunta id="IdPergunta">' . $IdPergunta . '</Pergunta>';
    echo '<Pergunta id="ValorPergunta">' . $vp . '</Pergunta>';
    echo '<Pergunta id="Pergunta">' . $p . '</Pergunta>';
    echo '<Pergunta id="RespostaA">' . $ra . '</Pergunta>';
    echo '<Pergunta id="RespostaB">' . $rb . '</Pergunta>';
    echo '<Pergunta id="RespostaC">' . $rc . '</Pergunta>';
    echo '<Pergunta id="RespostaD">' . $rd . '</Pergunta>';
    echo '</root>';

?>```

A: Faça isso:
$sql = "SELECT * FROM perguntas ORDER BY id_pergunta";
    $execsql = mysqli_query($conn, $sql) or die("Erro");
    while($row = mysqli_fetch_array($execsql)){
        # code...
        $IdPergunta = $row['id_pergunta'];
        $p = $row['pergunta'];
        $ra = $row['respostaa'];
        $rb = $row['respostab'];
        $rc = $row['respostac'];
        $rd = $row['respostad'];
        $vp = $row['valor_pergunta'];

    echo '<?xml version="1.0" encoding="UTF-8" ?>';
    echo '<root>';
    echo '<Pergunta id="IdPergunta">' . $IdPergunta . '</Pergunta>';
    echo '<Pergunta id="ValorPergunta">' . $vp . '</Pergunta>';
    echo '<Pergunta id="Pergunta">' . $p . '</Pergunta>';
    echo '<Pergunta id="RespostaA">' . $ra . '</Pergunta>';
    echo '<Pergunta id="RespostaB">' . $rb . '</Pergunta>';
    echo '<Pergunta id="RespostaC">' . $rc . '</Pergunta>';
    echo '<Pergunta id="RespostaD">' . $rd . '</Pergunta>';
    echo '</root>';

    }

?>


text:
Q: Octave: Smoothing a value-series (not a classical Moving average) I'd need a function where o=f(v) returns a vector holding o(i)=(v(i)+v(i+1))/2 , so in other words:
(v(1)+v(2))/2
(v(2)+v(3))/2
(v(3)+v(4))/2
(v(4)+v(5))/2
...

So e.g. for the input vector

v = [1;3;5;3;9;9]

the result would be

[2;4;4;6;9]

What's that? A moving average? A smoothing function?
In Matlab there seems to be "smooth" which could be what I'm looking for, but I don't see that in Octave.
Thanks in advance for a hint.

A: There are various ways to do this. A straighforward implementation would be
(v(1:end-1)+v(2:end))/2

This gets a little bit cumbersome for more complex moving averages, in which case you could use a convolution
conv(v, [0.5, 0.5], 'valid')

here the second array [0.5, 0.5] - called the "kernel" - defines how consecutive values are weighted.
Finally in the newer versions of octave there is also movmean.

A: To me, it looks like interpolation. See interp1:
v = [1;3;5;3;9;9];
n = numel(v);
iv = interp1(1:n, v, 1.5:n);   % or any other equally-spaced x values

Result:
iv =
   2   4   4   6   9


text:
Q: Minimal installation of Oracle Java 8 on Debian - headless, with no GUI In another question here (Minimal Java installation for Linux with no GUI) I found some information about headless installation of OpenJDK, but I would need this with Oracle Java 8.

*

*I need Oracle Java, because I use an ARM architecture (Raspberry Pi 2) to run a Minecraft Spigot server, and red many times that ARM version of OpenJDK lacks critical optimalisation to provide suitable performance

*I want version 8, because Spigot also recommands to use this version for any Minecraft-related purpouses; OpenJDK does not have version 8 yet anyway

*I want it headless, since I run my Raspberry server in console mode, with all GUI/desktop environment components uninstalled, to save storage place and performance.
My current system is the strongly Debian-based Raspbian Wheezy (Kernel ver. 3.18.; released 2015-05-05). This comes with a pre-installed Oracle Java 8, but it was deleted when I wiped out the GUI and desktop components (along with various other useless softwares) to make a minimal platfrom.
Then I tried to re-install it using the following command:
# apt-get install oracle-java8-jdk

it provided me a huge list of packages to install, which, as I was able to recognize them, contained mostly fonts, icons, language files, and x11 (x-server-realted) libraries, all nice damned GUI staff, what I absolutely do not need - and cried for >200 MB storage space.
Finally to my question: is there any way to install an Oracle Java Runtime Environment without these GUI conponents?
Maybe I should manually sort out unwanted packages - but how could I know which ones are really need for Java to run on console, or may it cause instability if I miss packages which are in the dependancy list, but functionally would not need to Java?
The list of required packages (maybe they will help):
fontconfig
fontconfig-config
hicolor-icon-theme
libatk1.0-0
libatk1.0-data
libcairo2
libdatrie1
libfontconfig1
libgdk-pixbuf2.0-0
libgdk-pixbuf2.0-common
libgraphite2-2.0.0
libgtk2.0-0
libgtk2.0-bin
libgtk2.0-common
libharfbuzz0a
libjasper1
libjpeg8
libpango-1.0-0
libpango1.0-0
libpangocairo-1.0-0
libpangoft2-1.0-0
libpangox-1.0-0
libpangoxft-1.0-0
libpixman-1-0
libthai-data
libthai0
libtiff4
libx11-6
libx11-data
libxau6
libxcb-render0
libxcb-shm0
libxcb1
libxcomposite1
libxcursor1
libxdamage1
libxdmcp6
libxext6
libxfixes3
libxft2
libxi6
libxinerama1
libxrandr2
libxrender1
libxtst6
oracle-java8-jdk
ttf-dejavu-core
x11-common

A: Full JDK (no matter if oracle-java8-jdk package, or JDK straight from Oracle) contains VisualVM profiler. It runs in graphical mode, which explains these dependiences.
You wrote about storage space, that >200MB is too big for you. And you also don't indicate, why you need full JDK, instead of just JRE, which is perfectly enough to run software written in Java.
So, I suggest to use this:
https://github.com/serverfarmer/sf-java8
setup.sh file installs plain JRE from Oracle, in /opt directory. And it:

*

*makes a symbolic link /opt/java, which will always lead to current Java installation

*adds proper JAVA_HOME and JAVA_OPTS environment variables to /etc/environment file, so many Java-based software (eg. Tomcat, JBoss EAP) will be able to find it automatically, without any manual configuration


text:
Q: Reduce code duplication without weakening types when processing a discriminated union I'm trying to figure out how to eliminate some duplicate code when handling a discriminated union in a way that does not weaken the type checking:
const handlers = {
  foo: (input: string): void => console.log(`foo ${input}`),
  bar: (input: number): void => console.log(`bar ${input}`),
};

type Handlers = typeof handlers;
type Values<T> = T[keyof T];
type DiscriminatedInput = Values<{
  [Id in keyof Handlers]: {type: Id; value: Parameters<Handlers[Id]>[0]};
}>;

const inputs: DiscriminatedInput[] = [
  JSON.parse('{"type": "foo", "value": "hello world"}'),
  JSON.parse('{"type": "bar", "value": 42}'),
];
for (const input of inputs) {
  // This doesn't work:
  //
  //     handlers[input.type](input.value);
  //                          ^^^^^^^^^^^
  //         error: Argument of type 'string | number' is not assignable to
  //         parameter of type 'never'.
  //
  // So I do this instead, which has a lot of duplication and must be kept in
  // sync with `handlers` above:
  switch (input.type) {
    case 'foo': handlers[input.type](input.value); break;
    case 'bar': handlers[input.type](input.value); break;
    default: ((exhaustiveCheck: never) => {})(input);
  }
}

Inside the for loop above, handlers[input.type] is guaranteed to be a function whose first parameter always matches the type of input.value, regardless of input.type. It seems to me that TypeScript should be able to see that, but it doesn't.
Am I doing something wrong, or is this is a limitation of TypeScript?
If it's a limitation of TypeScript, is there an existing bug report? Is there something I can do to help TypeScript narrow input to a foo- or bar-specific type so that I can eliminate that switch statement? Or refactor DisciminatedInput?
I could use a type assertion to weaken the type checking, but that adds complexity and reduces readability just to work around a language limitation. I'd rather work with the language instead of against it.

A: This answer is in response to your latest question revision and your comment:

You can view an assertion as widening (weakening) types, but what's really happening is that you are artificially narrowing (strengthening) the types by asserting what gets parsed from the JSON strings (which is actually any), and then having to fight against what you asserted to the compiler.

If you:

*

*don't want to use a type assertion, and

*must parse JSON inputs according to the schema provided in your question

then you can refactor your handlers to include the typeof runtime value of each handler's input parameter. This will enable you to then validate that there is a correlation between it and the typeof the input value parsed from each JSON object: using a type predicate function to satisfy the compiler.
In summary: this replaces the discussed assertion with a predicate, which uses a runtime check to enforce simple validation of the parsed JSON input before invoking its associated handler.
Here's an example of such a refactor:
TS Playground
type Values<T> = T[keyof T];
type Handler<Param> = (input: Param) => void;

type HandlerData<Param> = {
  inputType: string;
  fn: Handler<Param>;
};

/**
 * This identity function preservees the type details of the provided
 * argument object, while enforcing that it extends the constraint (which
 * is used later in a predicate to ensure a level of type-safety of the parsed JSON)
 */
function createHandlers <T extends Record<string, HandlerData<any>>>(handlers: T): T {
  return handlers;
}

const handlers = createHandlers({
  foo: {
    inputType: 'string',
    fn: (input: string): void => console.log(`foo ${input}`),
  },
  bar: {
    inputType: 'number',
    fn: (input: number): void => console.log(`bar ${input}`),
  },
});

type Handlers = typeof handlers;

type DiscriminatedInput = Values<{
  [Key in keyof Handlers]: {
    type: Key;
    value: Parameters<Handlers[Key]['fn']>[0];
  };
}>;

// This type is required for the usage in the following predicate
type HandlerDataWithInput<Param, Value> = HandlerData<Param> & { value: Value };

function dataIsTypeSafe <T = DiscriminatedInput['value']>(data: HandlerDataWithInput<any, any>): data is HandlerDataWithInput<T, T> {
  return typeof data.value === data.inputType;
}

const inputs: DiscriminatedInput[] = [
  JSON.parse('{"type": "foo", "value": "hello world"}'),
  JSON.parse('{"type": "bar", "value": 42}'),
];

for (const input of inputs) {
  const data = {...handlers[input.type], value: input.value};
  if (dataIsTypeSafe(data)) data.fn(data.value);
}


text:
Q: Specify Time series in R I'm new in R and i'm trying to do some prognosis using GA connection using forecast library.
I have an input data like this:
 day month year visits
1  01    01 2013  21821
2  02    01 2013  17865
3  03    01 2013  25300
4  04    01 2013  41184
5  05    01 2013  48953
6  06    01 2013  64135

It grabs the visits for the days of each month and year.
When i try to use ts function i go like this:
visits.ts=ts(ga.data$visits, start=c(2013,1), end=c(2014,1), frequency=12)
Given the output like this:
     Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
2013
2014

Here is my question- how can i split the month to days and create an output like this:
      01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
January 2013
February 2013

A: First create some test data, DF.  (In the future please provide test data.)
# create data set for testing
tt0 <- seq(as.Date("2013-01-01"), as.Date("2014-12-31"), by = "day")
lt <- as.POSIXlt(tt0)
DF <- data.frame(year = lt$year + 1900, month = lt$mon + 1, day = lt$mday, visits = 1:730)

The following depends crucially on every year containing the exact same number of days (i.e. no leap years).  Fortunately, that is the case in the data shown in the question.  Using DF convert it to "ts" class:
# convert to ts
tser <- ts(DF$visits, start = 2013, freq = 365)

If we did have leap years we might want to use "zoo" class from the zoo package or "xts" class from the xts package.
For the second question, first append a year_month column and then use dcast to create a 2d display:
library(reshape2)
DF2 <- transform(DF, year_month = I(sprintf("%d-%02d", year, month)))
dcast(DF2, year_month ~ day, value.var = "visits")

or using as.yearmon from the zoo package:
library(reshape2)
library(zoo)
DF2 <- transform(DF, year_month = as.yearmon(paste(year, month, sep = "-")))
dcast(DF2, year_month ~ day, value.var = "visits")

and here is a third alternative.  This one does not use any external packages although it's a bit slow:
 DF2 <- transform(DF, day = factor(day), year_month = sprintf("%d-%02d", year, month))
 xtabs(visits ~ year_month + day, DF2, sparse = TRUE)

Omitting sparse=TRUE it will be faster but will fill the unused spots with 0.


text:
Q: ASP.Net: RegisterOnSubmitStatement not calling the specified javascript function Upon failing validation the BackgroundSize of these TextBoxes sets from 0px to 20px. I got this technique from here.
Problem: The code in click event of the button doesn't run the specified javascript.
code-behind:
public static _Default d = new _Default();
public static ValidatorCollection signupValidators = d.GetValidators("signupGroup");
protected void btnSignup_Click(object sender, EventArgs e)
{  /***** i put a breakpoint here ******/
   Page.ClientScript.RegisterOnSubmitStatement(GetType(), "currentValidator", "onUpdateValidators();");
}

Javascript:
function onUpdateValidators() {
    alert("Alert! In Javascript");
    for (var i = 0; i < signupValidators.length; i++) {
        var currentValidator = signupValidators[i];
        var control = document.getElementById(currentValidator.ControlToValidate);
        if (control != null && control.style != null) {
            if (!currentValidator.isvalid) {
                control.style.backgroundSize = "20px";
                alert("in onUpdateValidators()");
            }
        }
    }
}

First time ever doing this so no idea what's wrong =(
[EDIT:]
Could there be something wrong with my Button?
<asp:Button ID="btnSignup" runat="server"
                Style="width: 150px; height: 40px; border-radius: 2px; font-weight: bold; background-color: #499234; margin-left: 70px; margin-top: 10px"
                Text="Create New Account"
                CausesValidation="true"
                ValidationGroup="signupGroup"
                PostBackUrl="~/Page2.aspx" <%-- removing this doesn't work either --%>
                OnClick="btnSignup_Click" />

Because i put a breakpoint on its click event and the execution doesn't break there

A: For Page.ClientScript.RegisterOnSubmitStatement check this link
Else try this:
First Add AjaxControlToolKit reference and than from AJAX Extenions in Toolbox add ScriptManager in your page after <form runat="server">
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        //your other logic

    </form>
 </body>

And than in code behind use this:
  ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "onUpdateValidators", "onUpdateValidators();", true);