text:
Q: Upgrade App Engine app to Python 3: How to provision Flask to run multiple, distinct apps I'm trying to upgrade my App Engine app from Python 2 to Python 3, replacing webapp2 with Flask. What is the best way to provision routing for my existing app structure which resembles the following:
/ - routes to main.py
/myapp1 - routes to myapp1.py
/myapp2 - routes to myapp2.py

main.py, myapp1.py, myapp2.py live in the same directory
The ability to use "handlers:" within app.yaml appears to no longer be available with Flask(?). I've been tinkering with Blueprints and Application Dispatching but that appears to expect that everything run through main.py (a "driver" module if you will).
I'm new to Flask so perhaps I'm missing something simple. I'd prefer not to restructure my application into subdirectories at this stage, as there's plenty of other changes to deal with for this upgrade.
Thank you

A: *

*GAE Standard for Python 3 uses an entrypoint in your app.yaml file. If you don't specify one, dev_appserver.py will use a default of gunicorn -b :$PORT main:app (see documentation).

*From the above, it means you'll have to 'tell main.py to route to different files if certain conditions (url paths) are met'. This is achieved via Blueprint
myapp1.py
from flask import Blueprint
myapp1_handlers = Blueprint('myapp1_handlers', __name__,
template_folder='templates')

@myapp1_handlers.route("/myapp1/")
def home():
    return "myapp1 - This is home page"

@admin_handlers.route("/admin/1/")
def home_1():
    return "myapp1 - This is page 1"

main.py
from flask import Flask

# Import the handlers defined in the Blueprint for myapp1_handlers
from myapp1 import myapp1_handlers

app = Flask(__name__)

# Register your blueprint so that any route matching
# what you've defined in the blueprint will get routed to it
app.register_blueprint(myapp1_handlers)

@app.route("/")
def home():
    return "Main App - This is home page"

@app.route("/1/")
def home_1():
    return "Main App - This is page 1"

a. Start your app by running dev_appserver.py app.yaml. It will display 'Main App - This is home page'
b. Change the url to /myapp1 and it should now display 'myapp1 - This is home page'

Another Solution:
Instead of using Blueprint, another option is to make each of myapp1, myapp2 a service (we have a blog article with an example and explanation here).
Each of them will need to have its own 'app.yaml' e.g. myapp1.yaml, myapp2.yaml. You'll then create a dispatch.yaml file which says route anything with a path of myapp1 to myapp1 service and anything with a path of myapp2 to myapp2 service and everything else to your default service. This means you'll end up with something like this
dispatch.yaml
dispatch:

# Send all traffic for paths that include /myapp1/ to the myapp1 service
- url: "*/myapp1/*"
  service: myapp1

# Send all other traffic to the default service.
- url: "*/*"
  service: default

myapp1.yaml
service: myapp1
runtime: python39

# Tell GAE to check myapp1.py for the 'app' object
# This means you need to have it in myapp.py too
entrypoint: gunicorn -b :$PORT myapp1:app

Notice that there's an entrypoint in myapp1.yaml. If you don't include it, GAE will assume the default entrypoint (as earlier stated) and will go look for your main.py file.
I have not included code for your default service i.e. your app.yaml file


text:
Q: Size of prefab when spawning in panel is too small I'm spawning prefab in a panel but it's size is too small like a dot but when I spawn it outside the panel there's no problem . Please check below image and code

public class RedKeyShapeSpawn : MonoBehaviour
{
    public GameObject redshapes;

    void Start()
    {
        GameObject redkeychild1 = Instantiate(redshapes, transform.position,
transform.rotation) as GameObject;
        redkeychild1.transform.SetParent(GameObject.FindGameObjectWithTag
("ShapePanel").transform, false);

    }

    void Update()
    {

    }
}

RedKeyShapeSpawn script is attached to RedKey1spawn object

A: Problem is that when you spawn you object inside the panel it will inherit the parent position and use that as a reference (x,y and z are relative).
You should be able to solve this problem if, for example, your panel in in the origin (0,0,0) or if you set an absolute position in your code.
PS. Same thing with rotation and scale

A: The culprit of this issue is likely the transform of the ShapePanel. If the transform of that object is not 1x1x1 then any objects added as a child of the panel will be affected by it.
Consider making the prefab a child of the panel, and rescale it accordingly. Then when you spawn the prefab and add it as a child of the panel, the scale of the RedKey should be as you expect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deriving ¬R from {R↔(R∨(P∧¬P)),R↔¬P,¬P→(P↔(Q→Q)),P→Q}
Give a derivation of $\neg R$ from the following premises:
$$\{R\leftrightarrow(R\lor(P\land \neg P)), R\leftrightarrow\neg P, \neg P\to(P\leftrightarrow(Q\to Q)), P\to Q\}$$
using the rules found here.

My assignment is due today, if someone can help me out. ty
Is this correct? I know some dependence columns are wrong.

1 1) R↔(R/lor(P∧¬P)) P
2 2) R↔¬P P
3 3) ¬P→(P↔(Q→Q))  P
4 4)P→Q P
5 5)R P
2 6)R→¬P  2,BE
2,5 7)¬P 5,6,MP
2,3 8)P↔(Q→Q) 3,7,MP
2,3 9)(Q→Q)→P 8,BE
2,3,5 10)¬(Q→Q) 7,9,MT
2,3,5 11)Q∧¬Q 10,NC
2,3,5 12)Q 11,simp
2,3,5 12)¬Q 11,simp
2,3 14)¬R 12,13,RAA
2,15)¬R 5,14,RAA


text:
Q: Keep initial input signal of enabled subsystem constant during pulse Imagine I have a continous signal (e.g. a sine) and a periodic rectangular pulse (50%) (blue lines):

While the pulse is switching its state - and a little before and after (yellow line, 2nd plot) - I'd like the continious signal to remain constant. So when the second pulse = 1, there should be a little stair step in the original signal.
How can I implement this behaviour in Simulink?

I thought a simple Zero Order Hold within an enabled subsystem should be enough, but it returns the output from the previous enabled state, which is a little weird (yellow line, 1st plot).
Here you can find a minimal example to play with.:

A: Replace your enabled subsysten with a triggerd subsystem / raising edge. Don't put any block in it, just leave the input connected to the output.


text:
Q: Spring Security Authorization Server with custom AuthenticationProvder I'm having a problem configuring an Oauth2 Auth Server in Spring, I have my custom AuthenticationProvider and I'm defining my own AuthenticationManager, but everytime that I do a request for a token to "/oauth/token", I see that Spring keeps injecting and calling the default DaoAuthenticationProvider in the ProviderManager defined by Spring.
This are my configuration classes:
@Configuration
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private AuthenticationManager authenticationManager;

    public AuthorizationServerConfiguration(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        return converter;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

}

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private AuthenticationProvider authenticationProvider;

    public WebSecurityConfig(AuthenticationProvider authenticationProvider) {
        this.authenticationProvider = authenticationProvider;
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return new ProviderManager(authenticationProvider);
    }
}

Thanks in advance
EDIT
@Service
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    private ADCustomerService adCustomerService;

    public CustomAuthenticationProvider(ADCustomerService adCustomerService) {
        this.adCustomerService = adCustomerService;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        return adCustomerService.retrieveUser(username, authentication);
    }
}

A: You need to override configure(AuthenticationManagerBuilder auth) from WebSecurityConfigurerAdapter class
The final class should look something like this
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }

}

A: Edit your WebSecurityConfig  as follows:
FROM
  @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        private AuthenticationProvider authenticationProvider;

        public WebSecurityConfig(AuthenticationProvider authenticationProvider) {
            this.authenticationProvider = authenticationProvider;
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return new ProviderManager(authenticationProvider);
        }
    }

TO
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private CustomAuthenticationProvider customAuthenticationProvider;

    public WebSecurityConfig(AuthenticationProvider authenticationProvider) {
        this.authenticationProvider = authenticationProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return new ProviderManager(authenticationProvider);
    }
}


text:
Q: OpenGL Object Rendering Order Problem: Objects aren't rendering correctly.
What I tried to do: Searched Stack Overflow. Read that I needed to enable Depth_Test and did so. Still doesn't work. Read that I possibly needed glDepthFunc(GL_LEQUAL);, did not work. Is there something in the way I wrote reshape/initscene/myDisplay that causes these common approaches not to work?
Code below.
void reshape (int w, int h)
{
    viewport.w = w;
    viewport.h = h;
    glViewport(0,0,viewport.w,viewport.h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (w <= h) {
        glOrtho (-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w, 1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0);
    }
    else {
        glOrtho (-1.5*(GLfloat)w/(GLfloat)h,1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0);
    }
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void myDisplay() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the color buffer
    glMatrixMode(GL_MODELVIEW);   // indicate we are specifying camera transformations
    glLoadIdentity();             // make sure transformation is "zero'd"
    glScalef(zoom, zoom, zoom);
    gluLookAt(0.0, -9.0, 0.0,
      0.0, 0.0, 0.0,
      0.0, 0.0, 1.0);
    glRotatef(y_rotation, 0.0, 1.0, 0.0);
    glRotatef(x_rotation, 1.0, 0.0, 0.0);
    renderObjects();
    glFlush();
    glutSwapBuffers();                  // swap buffers (we earlier set double buffer)
}

void initScene(){

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    reshape(viewport.w, viewport.h);

    glShadeModel(GL_FLAT);
    glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);

    GLfloat red[] = {1.0f, 0.2f, 0.2f, 1.0f};
    GLfloat white[] = {1.0f, 1.0f, 1.0f, 1.0f};
    GLfloat gray[] = {0.5f, 0.5f, 0.5f, 1.0f};
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, gray);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, gray);

    GLfloat lightPos[] = {0.0f, 0.0f, -10.0f, 1.0f};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_NORMALIZE);
}


text:
Q: How to get column list with comma separate values on data-table load in some function I want to pass the column list with comma separated values(string) on some customize function.
For ex.
function newExportAction() {
    var table = $('#tblfiles').DataTable();
    var SearchData = table.search();
    var OrderData = table.order();
}

*

*these are used for getting search and order values. but I also need the columns list as string value.

A: Use code below, it works fine:

$(function(){
  var table =  $('#tblfiles').DataTable();

  var names = col_names_string($('#tblfiles'));

  $('#nam').text(names);
  console.log(names);
})

function col_names_string(tbl) {
        var len = tbl.find('th').length;
        var str = tbl.find('th').eq(0).text();
        for (var i = 1; i<len; i++) {
            str += ',' + tbl.find('th').eq(i).text();
        };
  return str;
}

      EEE
      WWW
      QQQ
      RRRR

      1
      2
      2
      2

      3
      5
      6
      1

Implementation to your function is next:
function newExportAction() {
    var table = $('#tblfiles').DataTable();
    var SearchData   = table.search();
    var OrderData    = table.order();
    var ColumnNames  = col_names_string($('#tblfiles'));
}
    function col_names_string(tbl) {
            var len = tbl.find('th').length;
            var str = tbl.find('th').eq(0).text();
            for (var i = 1; i<len; i++) {
                str += ',' + tbl.find('th').eq(i).text();
            };
      return str;
    }


text:
Q: Missing AdMobDelegateProtocol.h when building with AdWhirl on iOS I downloaded the latest AdWhirl and AdMob SDKs a few days ago, followed the iPhone installation instructions for both and ran into this error while trying to build:
AdMobDelegateProtocol.h: No such file or directory in AdWhirl/adapters/AdWhirlAdapterAdmob.h

I can't find that file anywhere and the AdMob SDK website makes no mention of it. Where can I get this file? Is the latest version of AdMob no longer compatible with AdWhirl?

A: Having similar problem.
Upgrading an old app. Working with older sdk's of adwhirl and admob.
Downloaded latet adwhirl sdk
Downloaded admob sdk.
Same issue as you are having.
Has admob been updated and lost compatibility with adwhirl sdk suddenly?
AdMobDelegateProtocol.h No such file or directory.
Seems to me that this header file used by adwhirl is no longer part of admob sdk download.
Found the answer here. Admob has been updated, adwhirl has not yet.
http://groups.google.com/group/adwhirl-users/browse_thread/thread/e0baf3c472a3420f
Need to find those older admob sdk's.


text:
Q: $lookup in multiple array object both collection   {
    $lookup: {
      from: "site",
      "let": {
        "pid": "$data"
      },
      "pipeline": [
        {
          "$match": {
            "$expr": {
              "$in": [
                "$doc_id",
                "$$pid"
              ]
            }
          }
        }
      ],
      "as": "subComment"
    }
  },

https://mongoplayground.net/p/6t2uVwLzW0A
How to make a $lookup inside array using mongodb I did try but didn't get success countRecord should be inside data whose object_id does match.
output should be
[
  {
    "_id": ObjectId("5ebb74ef92033b3dc79aca13"),
    "content": "Here is new content",

    "data": [
      {
        "_id": ObjectId("5e7cd2019b1c522b15cca6fe"),
        "height": 1000,
        "url": "xyz.jpg",
        "width": 1000,
        "countRecord": 2,
      },
      {
        "_id": ObjectId("5e7cd2019b1c522b15cca6fd"),
        "height": 1000,
        "url": "verr.jpg",
        "width": 601
      }
    ],
    "subComment": [],
    "timestamp": 1.58934347177e+12,
    "type": "post"
  }
]

A: What I would suggest to make it easier to lookup, is to unwind the array first.
db.setting.aggregate([
  { $unwind: '$data' },                                                        // unwind the data array so that we can process it 1 by one
  {
    $lookup: {                                                                // will lookup for each to the unwinded elements
      from: 'site',
      localField: 'data._id',
      foreignField: 'doc_id',
      as: 'subComment'
    }
  },
  { $addFields: { 'data.countRecord': { $size: '$subComment' } } },           // add the count of records
  {
    $group: {                                                                 // We will use $group to revert unwinded data back to an array
      _id: {
        _id: '$_id',
        content: '$content',
        type: '$type',
        timestamp: '$timestamp'
      },
      data: { $push: '$data' }
    }
  },
  { $replaceRoot: { newRoot: { $mergeObjects: ['$_id', { data: '$data' }] } } } // restructures the objects to what you need it to look like
]);

A: There are many ways you can do this, here is an easy example by changing input structure using $map
db.setting.aggregate([
    {
        $lookup: {
            from: "site",
            "let": {
                "pid": {
                    "$map": {
                        "input": "$data",
                        "as": "datum",
                        "in": "$$datum._id"
                    }
                }
            },
            "pipeline": [
                {
                    "$match": {
                        "$expr": {
                            "$in": [
                                "$doc_id",
                                "$$pid"
                            ]
                        }
                    }
                }
            ],
            "as": "subComment"
        }
    },
    {
        $addFields: {
            "data": {
                "$map": {
                    "input": "$data",
                    "as": "datum",
                    "in": {
                        "$mergeObjects": [
                            "$$datum",
                            {
                                "countRecord": {
                                    "$size": {
                                        "$filter": {
                                            "input": "$subComment",
                                            "as": "comment",
                                            "cond": {
                                                "$eq": [
                                                    "$$comment.doc_id",
                                                    "$$datum._id"
                                                ]
                                            }
                                        }
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
])


text:
Q: Convert ARGB data(.tiff image) to 2D texture using D3D11 I have a sample ARGB image (.tiff file).
I want to pass it as a 2D texture. I am not sure how to do that or is it even possible ?

A: I think you can utilize WIC texture loader which is a part of official DirectX Tool Kit.


text:
Q: Selenium code in PyCharm(Python) running slow, how to improve speed? I wrote this automated bot in PyCharm and I do not know why my code executes so slow? Any help for improvement is sincerely appreciated.
from selenium import webdriver
from InfoApp import keys
import time
def order(k):
    driver = webdriver.Chrome(executable_path='driver/chromedriver')
    driver.get(k['product_url'])
    driver.maximize_window()
    driver.find_element_by_xpath('//*[@id="RightRail"]/div/div[4]/fieldset/div/div[7]/label').click()
    driver.execute_script("window.scrollTo(0, 1000)")
    driver.find_element_by_xpath('//*[@id="floating-atc-wrapper"]/div/button').click()
    driver.find_element_by_xpath('//*[@id="PDP"]/div/div[4]/div/div/div/div/div/div/div/div/div/div[3]/div/button[2]').click()
    time.sleep(5)
    driver.find_element_by_xpath('//*[@id="nav-cart"]/a/div/span').click()
    driver.find_element_by_xpath('//*[@id="react-root"]/div/div[4]/button').click()
    driver.find_element_by_xpath('//*[@id="qa-guest-checkout"]').click()
    driver.find_element_by_xpath('//*[@id="firstName"]').send_keys(k["First_Name"])

if __name__ == '__main__':
    order(keys)

A: remove time.sleep and add explicit or implicit wait:
you can add implicit wait as
driver = webdriver.Chrome(executable_path='driver/chromedriver')
driver.implicitly_wait(10)

this will automatically make all commands to wait maximum of 10 seconds . If element not found in 10 sec then element not found is thrown.
but this will not check clicability , visibility etc , this checks only for presence of element. For other condition you can use explicit wait.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(browser, 10)

elem= wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'somelocator')))

Note:
There is good video link jeff added but to add to that :
implicit waits are not bad practices, mixing implicit wait and explicit wait is bad practice. As implict wait waits for only the presence of the elment so in most cases you cannot avoid explicit wait as you need to wait for visibility,clicability etc . so its better to avoid it completely as it cause long waits in your code when you mix both implicit and explicit wait together
So if you are using explicit wait DONT use implict wait


text:
Q: how can i prevent the footer from changing its position when resizing the browser window? This is my website with the dimention of 6443-4840 :
image
but in smaller sizes the footer is no longer a footer.
website with the dimention of 2920-2386:
image
in every window sizes i want the postition of the footer to be at the same position in dimention of 6443-4840, then i can say i have a footer but currently in bigger window sizes the footer is in a correct position and as long as i change the window size the footer overlaps the other content.

body{

  position: relative;
  min-height: 100vh;
  padding-bottom: 500px; /* Height of the footer */
}
footer{
  position: absolute;
  width: 100%;
  height: 500px;
  bottom: 0;
  background: grey;
}

.card {

  max-width: 400px;
    margin: 0auto;
  text-align: center;
  font-family: arial;
  border-style: solid;
  border-width: 6px;
  position:  relative;
  top: 611px;
  margin-bottom: 33px;
  margin-right: 33px;
  float: left;

}

.card img{

  height: 400px;
    width: 400px;
  vertical-align: middle;

}

.price {background-color: #f44336;
    font-size:22px;
    border-radius: 3px;
    position: absolute;
    bottom: 0px;
  right: 0px;
  padding: 3px;

}

.card button {
  border: none;
  color: white;
  background-color: #000;
  position: relative ;
  cursor: pointer;
  width: 100%;
  height: 100px;
  font-size: 44px;
  align-items: center;

}

.card button:hover {
  opacity: .5;
  background-color: #330;

}

#id{
    background-color: palevioletred;
    color: white;
    margin: 0;
    font-size: 17px;
}

.number{
    width: 50px;
    height: 50px;
    background-color: #330;
    color: yellow;
    border-radius: 50%;
    position: absolute;
    top: -22px;
    right: -22px;
    justify-content: center;
    align-items: center;
    display: flex;
    font-size: 22px;

}

@media  (max-width: 1864px){
    .card{
        max-width: 300px;
    }

    .price{

        font-size:20px;

    }

    .card img{
        height: 300px;
        width: 300px;

    }

}
{% load static %}
<!DOCTYPE html>

    <link rel="stylesheet"   href="{% static 'main.css' %}">

header

    {% for i in p%}

{{i.Number}}

{{i.description}}

                        <button> ${{i.price}} buy</button>

    {%endfor%}

hello

how can i solve this problem?(i do not want a fixed footer)

A:

.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: red;
   color: white;
   text-align: center;
}

Fixed Footer

Footer


text:
Q: Cropping an image as a 3d array I have a tensor of dimension (224, 224, 3) representing an image. I would like to firstly "crop" this image using bounding box dimensions in the format bndbox = [x1, y1, x2, y2] and then resize this cropped image back to a dimension of (224, 224, 3).
Is there a simple way of doing this with numpy/cv2(OpenCV)?

A: Supposing that your tensor supports slicing, simply select the bounding box, then you can resize with cv2.resize:
cv2.resize(img[y1:y2,x1:x2], (224, 224))

Just note that img is probably selected in height then in width, while the shape argument for cv2.resize takes (width, height).


text:
Q: cvc-elt.1.a: Cannot find the declaration of element 'familia' I'm trying to validate a really simple xml using xsd, but for some reason I get this error.

cvc-elt.1.a: Cannot find the declaration of element 'familia'

Also, exists a problem in the element "nome":

src-resolve: Cannot resolve the name 'nome' to a(n) 'element declaration' component.

I'll really appreciate if someone can explain me why.
XML File
<?xml version="1.0" encoding="UTF-8"?>

<familia xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://www.painatal.pt/familia"
         xsi:schemaLocation="http://www.painatal.pt/familia familia.xsd">

    <detalhesFamilia>
        <nome>Familia</nome>
        <pais>Portugal</pais>
        <cidade>Porto</cidade>
        <dataNascimento>2000-02-01</dataNascimento>
        <numeroMembros>5</numeroMembros>
    </detalhesFamilia>

    <prefDias>
        <numeroDias>5</numeroDias>
    </prefDias>
</familia>

XSD File
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="familia"
           elementFormDefault="qualified">

<xs:element name="nome" type="xs:string"/>
<xs:element name="pais" type="xs:string"/>
<xs:element name="cidade" type="xs:string"/>
<xs:element name="dataNascimento" type="xs:date"/>
<xs:element name="numeroMembros" type="xs:integer"/>
<xs:element name="numeroDias" type="xs:integer"/>

<xs:element name="familia">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="nome"/>
            <xs:element ref="pais"/>
            <xs:element ref="cidade"/>
            <xs:element ref="dataNascimento"/>
            <xs:element ref="numeroMembros" minOccurs="1" maxOccurs="7"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="prefDias">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="numeroDias" minOccurs="1" maxOccurs="5"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

</xs:schema>

A: The target namespace defined in the schema ("familia") doesn't match the actual namespace used in the instance ("http://www.painatal.pt/familia").
Furthermore, within the schema, <xs:element ref="nome"/> is a reference to a no-namespace element with local name nome; you want <xs:element ref="p:nome"/> where the namespace prefix p is bound to the (corrected) target namespace of the schema.


text:
Q: How to efficiently show user's online status in Laravel, Redis, SocketIO Lately I've been working on a realtime web app built using React. I want to display which users are online currently. I've thought of many different ways to implement it, and chose the following implementation.
In my Laravel login controller, after the user has successfully logged in I've stored the user email as the key and user id as a value in a Redis Hash Structure.
In the get users controller, I am checking for each user if their email is present as a key in the Redis hash, shown as below
$users = User::all();
$users->map(function($user){
    $user->setAttribute('online', 0);
    if(Redis::hget('ActiveUsers',$user->email)) {
        $user->setAttribute('online', 1);
    }
});
return $users;

And as for the realtime displaying of the status I am using SocketIO and Redis pub/sub feature
redis.on('message', (channel, message) => {
    io.emit('someone-logged-in', msg.data.id);
});

io.on('connection', (socket) => {

redis.subscribe('logged-in');
socket.on('loggedOut', data => {
    ActiveUsersRedis.hdel("ActiveUsers", data.email);
    io.emit('someone-logged-out', data.id);
});

In my React Application I'm handling the event as follows
this.state.socket.on('someone-logged-out',data => {
    let i = this.state.activeUsersId.indexOf(parseInt(data, 10));
    if(i !== -1)
    {
        this.state.activeUsersId.splice(i, 1);
        this.setState({activeUsersId: this.state.activeUsersId});
    }
});
this.state.socket.on('someone-logged-in',data => {
    let e = true;
    if(this.props.users.data)
        e = this.props.users.data.some(user => user.id === data);
    if(e) this.setState({activeUsersId: [...this.state.activeUsersId,data]});
});

I don't know if it is the best way or an optimal solution or if it's scalable upto 100k users. So, does anyone has a better approach or any suggestions on how can I improve this implementation?


text:
Q: SEO - moving subdomain to folder I am moving my blog from a sub-domain - blog.example.com to a sub-folder example.com/blog/
The URLs and the content are staying exactly the same.
What would be the best SEO-wise action to take, I was thinking the following:

*

*Add rel="canonical" to sub-domain URLs and let the spiders crawl my pages to become aware of the new links.

*Add a 301 redirect from sub-domain to sub-folder.

I understand that there's no point in having canonical if there's a 301 redirect.
Any help would be highly appreciated, thank You in advance!

A: The URLs are not staying the same. They are changing so you need to tell search engines and users where to find the content. 301 redirects are exactly what you want. They tell search engines where to find the new content and to update their indexes (plus Google will transfer PageRank) plus when users go to the old URL they are automatically redirected to the new URL which canonical URLs do not do.


text:
Q: Elasticsearch universal search query I have a string "Jhon Abraham 18". I want to create search query that will search by divided by spaces words from the string in an index. This search have to be set to all fields of the index and you don't know what meaning have to be mapped(set) to a field.
So, I have a document:
{
  "_index": "recipient",
  "_type": "recipient",
  "_id": "37a15258d9",
  "_version": 1,
  "_score": 1,
  "_source": {
    "name": "Jhon ",
    "surname": "Abraham",
    "age": "18 ",
}

and I don't know to what fields of index meanings Jhon, Abraham and 18 correspond. I just have a string and by this string I want to search in all fields of the index documents. I can divide it by separete words by spaces but I don't know exact mapping fields for search. Also, I want to do it at Java.
I'll be appreciate for help.

A: I think you should use query_string in elasticsearch.
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
This will solve your problem.

A: You can use multi match query, writing all fields or wildcards.
Multi Match Query


text:
Q: Relation between hypergeometric and gamma functions Show that, for a positive integer $n$, $$F\left(-\frac{n}{2},-\frac{n}{2}+\frac{1}{2};n+\frac{3}{2};-\frac{1}{3}\right)=\left(\frac{8}{9}\right)^n\frac{\Gamma\left(\frac{4}{3}\right)\Gamma\left(n+\frac{3}{2}\right)}{\Gamma\left(\frac{3}{2}\right)\Gamma\left(n+\frac{4}{3}\right)}.$$
I can identify the right hand side (using the definition of the Pochhammer symbol) with: $$\left(\frac{8}{9}\right)^n\frac{\Gamma\left(\frac{4}{3}\right)\Gamma\left(n+\frac{3}{2}\right)}{\Gamma\left(\frac{3}{2}\right)\Gamma\left(n+\frac{4}{3}\right)}=\left(\frac{8}{9}\right)^n\frac{\left(\frac{3}{2}\right)_n}{\left(\frac{4}{3}\right)_n},$$ and get an expression for this in terms of factorials, but I'm not sure how to simplify the left hand side - it gets quite messy!

A: Your formula still holds if $n\notin \mathbb{Z}$. From $F(a,b;c;z)=(1-z)^{c-a-b}F(c-a,c-b;c;z)$, it suffices to calculate
$$F(\frac{3n+3}{2},\frac{3n+2}{2};n+\frac{3}{2};-\frac{1}{3})$$
its value follows directly from a cubic transformation of $_2F_1$ due to Goursat:
$$\tag{1}_2F_1(\frac{3a}{2}, \frac{3a-1}{2}; a+\frac{1}{2};-\frac{z^2}{3}) = {(1+z)^{1-3a}} {_2F_1}(a-\frac{1}{3}, a;2a;\frac{2z(3+z^2)}{(1+z)^3})$$
and the formula of $F(a,b;c;1)$.

Once an identity like $(1)$ has been conjectured, there is a mechanical way to prove it. One constructs a 2nd order ODE satisfied by RHS, then show LHS is also a solution. The calculation tends to be lengthy and not quite do-able by hand.
The Mathematica commands
DifferentialRootReduce[(1+z)^(1-3a)*Hypergeometric2F1[a-1/3,a,2a,2z(3+z^2)/(1+z)^3],z]

and
DifferentialRootReduce[Hypergeometric2F1[3a/2,(3a-1)/2,a+1/2,-z^2/3],z]

shows both sides of $(1)$ are satisfied by
$$3a(3a-1)zy+6a(1+z^2)\frac{dy}{dz}+z(z^2+3)\frac{d^2y}{dz^2}=0$$
Therefore it suffices to show both sides have equal $0$th and $1$st derivative at $z=0$, this is even easier.


text:
Q: how to get result of group by with join I am using query in controller:
$data = DB::table('circulate_files')
           ->join('regionmasters','circulate_files.region_id','=','regionmasters.id')
           ->select('circulate_files.unique_id_for_group,circulate_files.title','regionmasters.region', DB::raw('group_concat(region) as new_region'))
           ->groupBy('unique_id_for_group')
           ->get();

But I am getting error:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'circulate_files.unique_id_for_group,circulate_files.title' in 'field list' (SQL: select circulate_files.unique_id_for_group,circulate_files.title, regionmasters.region, group_concat(region) as new_region from circulate_files inner join regionmasters on circulate_files.region_id = regionmasters.id group by unique_id_for_group)

A: I think the problem in your select, it should be:
select(['circulate_files.unique_id_for_group','circulate_files.title','regionmasters.region', DB::raw('group_concat(region) as new_region')])

the problem was in this code:
->select('circulate_files.unique_id_for_group,circulate_files.title', ...)

it should be:
->select('circulate_files.unique_id_for_group','circulate_files.title',...)

A: you can rewrite your query as follow and use selectRaw instead of select:
$data = DB::table('circulate_files')
           ->selectRaw('
               circulate_files.unique_id_for_group, circulate_files.title,
               regionmasters.region, group_concat(region) as new_region
            ')
           ->join('regionmasters', 'circulate_files.region_id', 'regionmasters.id')
           ->groupBy('unique_id_for_group')
           ->get();


text:
Q: How to publish message from server to flet app client? reference: https://flet.dev/docs/guides/python/pubsub/
quote from reference:

*

*Flet provides a simple built-in PubSub mechanism for asynchronous communication between page sessions.

*Flet PubSub allows broadcasting messages to all app sessions or sending only to specific "topic" (or "channel") subscribers.
Question:
Broadcasting or sending message is triggered from client side. How to do it from server side? Like broadcasting messages to subscribers of specific "topic"
I have no idea how to do it. But I expect something like:
Server side command:
publish <topic> <message>

Flet client app subscriber will receive the message on_message(msg):
import flet as ft

def main(page: ft.Page):
    page.title = "Flet Chat"

    # subscribe to broadcast messages
    def on_message(msg):
        messages.controls.append(ft.Text(msg))
        page.update()


text:
Q: Extrapolating learned model with time series in R library(astsa)
library(forecast)
globtemp
trend <- tslm(globtemp~I(trend^2)+trend)
autoplot(cbind(globtemp,trend$fitted), lwd=1)

How do I extrapolate here? I'd like to draw the "trend line" line further, up to let's say 2031.

I tried using solution from this question:
predict(trend, data.frame(date=seq(as.Date("2021-01-01"), by="1 year", length.out=10)), interval = "prediction")

but it only warned me that Warning message: 'newdata' had 10 rows but variables found have 136 rows and gave some gibberish results.

A: Answer
Use forecast::forecast:
forecast(trend)

This returns an object with predicted values for subsequent years as well as confidence intervals that you can then use to create a plot.
If you want to forecast further into the future, say, 50 years:
forecast(trend, h = 50)

By default, it allows you to plot the forecast with plot:
plot(forecast(trend, h = 50))


text:
Q: Сохранение состояния приложения при сворачивании Разметка MainActivity следующая:
LinearLayout
-AppBarLayout
-DrawerLayout
   -FrameLayoutContent
   -FrameLayoutNavigation

Допустим мой FrameLayoutNavigation содержит две категории (Категория1 и Категория2). FrameLayoutContent отображает содержимое каждой категории, это хорошо. Но если в процессе работы я перейду в Категория2 и сверну приложение, то при развороте на экране отображается содержимое Категория1.
Как сохранить состояние приложения при сворачивании, чтобы при развороте отображалось содержимое Категория2?
Пытаюсь сделать следующим образом, но это не работает (код из MainActivity):
 @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            toolbarname = getSupportActionBar().getTitle().toString();
           outState.putString("toolbarname", toolbarname);
        }

        @Override
        protected void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
            toolbarname = savedInstanceState.getString("toolbarname");
            if (toolbarname.equals("Категория1")){
getSupportFragmentManager().beginTransaction.replace(R.id.content_frame, new Fragment1().commit();
            } else if (toolbarname.equals("Категория2")){
getSupportFragmentManager().beginTransaction.replace(R.id.content_frame, new Fragment2().commit();
        }
}

A: Используйте какую-нибудь переменную для обозначения типа/номера категории и SharedPreferences для ее сохранения. При изменении категории, меняйте значение в переменной.
В методе onPause, сохраняйте эту переменную.
mSharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mSharedPref.edit();
editor.putInt(getString(R.string.number), mNumber);
editor.apply();

В методе onCreate или где нужно, восстанавливайте ее значение.
mSharedPref = getPreferences(Context.MODE_PRIVATE);
mNumber = mSharedPref.getInt(getString(R.string.number), 1);

Перед тем как загружать/отображать категорию, проверяйте значение переменной.


text:
Q: Extract all values from Json Array in SQL I have SQL-data, with one column of JSON-data. Unfortunately, my database only compatibility level 100. So I can't use OPENJSON().
My JSON-data are structured as follows, it contains results from testing. I also have the columns id, model and type.
[
{ "name": "rtc", "value": "pass" },
{ "name": "battery", "value": "pass" },
{ "name": "connection", "value": "pass" },
{ "name": "timer", "value": "pass" },
{ "name": "provide", "value": "pass" },
{ "name": "request", "value": "fail" }
]

How do I get columns for rtc, battery, connection, timer, provide and request with cells that are pass/fail?
Some products have all tests, while some only have a few.
I have tried JSON_Value(details, '$.name'), but that gives me null.
EDIT
Expected output table, Either of the works:

A: If your SQL Server version supports JSON, you may try to parse the stored JSON data and pivot the rows:
Sample data:
DECLARE @json nvarchar(max) = N'[
{ "name": "rtc", "value": "pass" },
{ "name": "battery", "value": "pass" },
{ "name": "connection", "value": "pass" },
{ "name": "timer", "value": "pass" },
{ "name": "provide", "value": "pass" },
{ "name": "request", "value": "fail" }
]'
SELECT *
INTO Data
FROM (VALUES (1, @json)) v (id, details)

Statement:
SELECT *
FROM (
   SELECT d.id, j.[name], j.[value]
   FROM Data d
   CROSS APPLY OPENJSON(d.details) WITH (
      [name] nvarchar(50) '$.name',
      [value] nvarchar(4) '$.value'
   ) j
) t
PIVOT (
   MAX([value]) FOR [name] IN ([rtc], [battery], [connection], [timer], [provide], [request])
) p

Result:

id
rtc
battery
connection
timer
provide
request

1
pass
pass
pass
pass
pass
fail

Note, that you may get the unpivoted values with the following statement:
SELECT d.id, j.[name], j.[value]
FROM Data d
CROSS APPLY OPENJSON(d.details) WITH (
   [name] nvarchar(50) '$.name',
   [value] nvarchar(4) '$.value'
) j


text:
Q: Is it possible to show the content of a googlle drive document on a drupal site? I have a drupal 7 site and i want my google drive content to show up in a page on my site.  I have tried droogle but that only adds links to the files not the files themselves.  Has anyone tried to add google drive content to drupal?

A: There is a module for embedding Google docs in your node via iframes. You can find it here. I haven't tested it personally, but it is definitely an interesting idea.


text:
Q: How to return value from function in protractor?   this.httpXsrf = function() {
    var token;
    var http = require("https");

    var options = {
        "method" : "GET",
        "hostname" : "infomatrix-ci.cmxdev.com",
        "port" : null,
        "path" : "/",
        "headers" : {
            "cache-control" : "no-cache",
        }
    };
     http.request(options, function(res) {
        var chunks = [];
        var setcookie = res.headers["set-cookie"];
        if (setcookie) {
            setcookie.forEach(
            function(cookiestr) {
                if (cookiestr.indexOf('XSRF-TOKEN') > -1) {
                    var a = cookiestr.split(';');
                    token = a[1].splice;
                }
            });
        }
        res.on("data", function(chunk) {
            chunks.push(chunk);
        });

        res.on("end", function() {
            var body = Buffer.concat(chunks);
            console.log(body.toString());
        });
    }).end();
};

In above code i would like to return token variable from function and store it in antoher variable on test page,
like,
var token = apiPage.httpxsrf();

or
apiPage.httpxsrf().then(function(token){
  // call another function like apiPage.httplogin(token);
});

How can i return token and store in variable and call another function using token variable?


text:
Q: InStr to return ENTIRE criteria not partials My code below does not return the EXACT value from a list of names.  For example if in a list I have:
Ann
Anna
Hannah
...and I am looking for "Hannah Fawler" the code will return the following:
"Ann, Anna, Hannah"
I need to update the code to look for the ENTIRE name (Hannah) in a cell (which will have comments and will mention the persons full name) and return the ENTIRE name with no partials (Hannah > Hannah).  Anyone know how to do this?
Public Function NameLister(r1 As Range, r2 As Range) As String
    Dim Sentence As String
    NameLister = ""
    Sentence = LCase(r2.Text)
    For Each r In r1
        v = LCase(r.Text)
        If v <> "" Then
            If InStr(1, Sentence, v) > 0 Then
                If NameLister = "" Then
                    v = StrConv(v, vbProperCase)
                    NameLister = v
                Else
                    v = StrConv(v, vbProperCase)
                    NameLister = NameLister & ", " & v
                End If
            End If
        End If
    Next r
End Function

A: Here is a solution that uses a VBScript regular expression object. It matches the entire name (no partials) by requiring the name to appear within word boundaries (\b in regular expressions).
Public Function NameLister(r1 As Range, r2 As Range) As String
    Dim Sentence As String, rgx As Object
    NameLister = ""
    Sentence = LCase(r2.Text)
    'Initialize regular expression object
    Set rgx = CreateObject("vbscript.regexp")
    For Each r In r1
        v = LCase(r.Text)
        If v <> "" Then
            'Set search pattern to match only entire word.
            rgx.Pattern = "\b" & v & "\b"
            'Test Sentence for matches
            If rgx.Test(Sentence) Then
                If NameLister = "" Then
                    v = StrConv(v, vbProperCase)
                    NameLister = v
                Else
                    v = StrConv(v, vbProperCase)
                    NameLister = NameLister & ", " & v
                End If
            End If
        End If
    Next r
End Function


text:
Q: How to get all the elements an unknown length python list? I have a list:
>>> my_list = ['a', 'b', 'c', 'd']

And I have a string which contains {} markers for the format method:
>>> my_string = 'First element = "{}" and the Second element = "{}"'

I want to interpolate the first elements from my_list into my_string like this:
>>> print my_string.format(my_list[0], my_list[1])
First element = "a" and the Second element = "b"

However, When I write the code:

*

*I don't know how many {}s there will be in my_string

*I don't know how many elements there will be in my_list

*I do know that the number of elements in #2 will be greater than or equal to #1.

What python expression can I use to do the interpolation given facts number 1, 2 and 3?

A: You can use the splat operator: ("unpacking argument lists" officially)
print(my_string.format(*my_list))

It converts each element into another positional argument.


text:
Q: Finding the elements in a list that are less than their successor along with their indices Please suggest how to write following MALTAB code in Mathematica
k=1;
for j=1:bb-1
if (aa(j)-aa(j+1))<0
cc(k)=aa(j);
dd(k)=j;
k=k+1;
end
end

Here aa is some array and bb is the length of aa.

A: SeedRandom[1];
aa = RandomInteger[{-10, 10}, 20]
(*{-5, -10, -3, -10, -8, -7, -10, -10, 6, 4, -7, -2, 9, -5, 8, 6, 2, -10, 9, -6}*)

To get the positions, you can use Position and subsequently, to get the elements you can use Extract.
ddc = Position[Differences@aa, _?Positive];
dd = ddc[[All,1]];
cc = Extract[aa, ddc]
(*{-10, -10, -8, -10, -7, -2, -5, -10}*)

A: This seems to be quite fast:
f1 = Transpose@Pick[Most @ Transpose[{#, Range @ Length @ #}], Sign @ Differences @ #, 1]&;

f1 @ {-5, -10, -3, -10, -8, -7, -10, -10, 6, 4, -7, -2, 9, -5, 8, 6, 2, -10, 9, -6}

{{-10, -10, -8, -10, -7, -2, -5, -10}, {2, 4, 5, 8, 11, 12, 14, 18}}

Update: Timings:
ClearAll[f0, f1, aardvark2012F1, aardvark2012F2, anjanKumarF, eldoF, ubpdqnF]
funcs = {f0, f1, aardvark2012F1, aardvark2012F2, anjanKumarF, eldoF, ubpdqnF};
labels = {"f0", "f1", "aardvark2012F1", "aardvark2012F2", "anjanKumarF", "eldoF", "ubpdqnF"};
results = {res0, res1, res2, res3, res4, res5, res6};

f0[a_] := Pick[#, Sign@Differences@a, 1] & /@ {Most@a, Most@Range@Length@a}
f1[a_] := Transpose@Pick[Most@Transpose[{a, Range@Length@a}], Sign@Differences@a, 1]
aardvark2012F1[a_] := Module[{cc = {}, dd = {}}, Do[If[a[[j]] < a[[j + 1]],
   AppendTo[cc, a[[j]]]; AppendTo[dd, j];], {j, Length@a - 1}]; {cc, dd}]
aardvark2012F2[a_] := Transpose@
  Table[If[a[[j]] < a[[j + 1]], {a[[j]], j}, ## &[]], {j, Length@a - 1}]
anjanKumarF[a_] := Module[{ddc = Position[Differences@a, _?Positive]},
  {Extract[a, ddc], ddc[[All, 1]]}]
eldoF[a_] := Transpose[Flatten[#, 1] &@
   Split[MapIndexed[{#, #2[[1]]} &, a], #2[[1]] - #1[[1]] > 0 &][[All, 1 ;; -2]]]
ubpdqnF[a_] := Module[{p = Partition[a, 2, 1]},
  Transpose[Thread[Reap[MapIndexed[Sow[#2[[1]], #1[[2]] > #1[[1]]] &, p],
      True, {a[[#2]], #2} &][[2, 1]]]]]

Equal @@ (#@{-5, -10, -3, -10, -8, -7, -10, -10, 6, 4, -7, -2, 9, -5,
      8, 6, 2, -10, 9, -6} & /@ funcs)

True

SeedRandom[1];
bb = RandomInteger[{-10, 10}, 100000];
timings = Table[First[AbsoluteTiming[results[[j]] = funcs[[j]][bb];]], {j, 7}];
Equal @@ results

True

Transpose[{labels, timings}] //
 TableForm[#, TableHeadings -> {None, {"function", "timing"}}] &

Removing the function aardvark2012F1 from the list for a test with a larger input size:
SeedRandom[1];
bb = RandomInteger[{-10, 10}, 1000000];
timings = Table[First[AbsoluteTiming[results[[j]] = funcs[[j]][bb];]],
 {j, {1, 2, 4, 5, 6, 7}}];
Equal @@ results[[{1, 2, 4, 5, 6, 7}]]

True

Transpose[{labels[[{1, 2, 4, 5, 6, 7}]], timings}] //
 TableForm[#, TableHeadings -> {None, {"function", "timing"}}] &

A: EDIT
To dea with clumping from same difference from original code
Just for something different using Reap and Sow and producing list {index,value}:
list = {-5, -10, -3, -10, -8, -7, -10, -10, 6, 4, -7, -2, 9, -5, 8, 6,
    2, -10, 9, -6};
p = Partition[list, 2, 1];
Thread[Reap[
MapIndexed[Sow[#2[[1]], #1[[2]] > #1[[1]]] &, p],True,{#2,list[[#2]]} &][[2,1]]]

yielding:
(*{{2, -10}, {4, -10}, {5, -8}, {8, -10}, {11, -7}, {12, -2}, {14, -5},{18, -10}}*)

A: list = {-5, -10, -3, -10, -8, -7, -10, -10, 6, 4, -7, -2, 9, -5, 8, 6, 2, -10, 9, -6};

Flatten @ Split[list, Less][[All, 1 ;; -2]]

{-10, -10, -8, -10, -7, -2, -5, -10}

To also get the indices:
Flatten[#, 1]&@
   Split[
      MapIndexed[{#2[[1]], #1} &, list],
   #2[[2]] - #1[[2]] > 0 &][[All, 1 ;; -2]]

{{2, -10}, {4, -10}, {5, -8}, {8, -10}, {11, -7}, {12, -2}, {14, -5},
   {18, -10}}

A: Taking
bb = 20;
SeedRandom[1];
aa = RandomInteger[{-10, 10}, bb];

Here are two possibilities:
cc = {}; dd = {};
Do[
 If[aa[[j]] < aa[[j + 1]],
  AppendTo[cc, aa[[j]]];
  AppendTo[dd, j];
  ],
 {j, bb - 1}
 ]
cc
dd

(* cc = {-10, -10, -8, -10, -7, -2, -5, -10}
   dd = {2, 4, 5, 8, 11, 12, 14, 18} *)

Or alternatively,
{cc, dd} =
 Transpose@
  Table[If[aa[[j]] < aa[[j + 1]], {aa[[j]], j}, Nothing], {j, bb - 1}]

(* {{-10, -10, -8, -10, -7, -2, -5, -10}, {2, 4, 5, 8, 11, 12, 14, 18}} *)


text:
Q: Angularjs ng-repeat pass data to rating controller So I'm trying to use angularjs ui.boostrap rating component with my app, however i have no idea how to pass from ng-repeat rating value to ratingCtrl. I have tried using ng-init, but it just returns undefined error... Any ideas? (Data should be passed by r.rating)
My template:

{{r.recipe.name}}

{{ingredient.name}}

        <rating class="rating" ng-style="success" ng-model="rate" max="max" readonly="isReadonly" on-hover="hoveringOver(value)" on-leave="overStar = null" ng-click="setRating(r.recipe.id)"></rating>

My controller:
recipeApp.controller('RatingCtrl', function ($scope, $http) {

    $scope.max = 5;
    $scope.isReadonly = false;

    $scope.ratingStates = [
        {stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle'},
        {stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty'},
        {stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle'},
        {stateOn: 'glyphicon-heart'},
        {stateOff: 'glyphicon-off'}
    ];

    $scope.setRating = function(id) {

        var data = {
            rating: $scope.rate,
            id: id
        };

        $http.post('api/rate/recipe', angular.toJson(data), {cache: false})
            .success(function(data){

            })
            .error(function(data){
                alert(data.message);
            });
    };
});


text:
Q: Apache 2.4 Directory access control for mod_auth_form I need some help with this simple directory access rules - sorry I  just started playing with Apache 2.4 and not done this before.
I have configured Apache 2.4 to a stage where I can see a login for for protected resources and once I enter the user/pass I get access to the protected resourced.
Now I want to do the following which I am not sure how I can get this done.

*

*Web root is set to /var/www

*/var/www/login - anyone can access, no auth required as this folder contains login.html and logout.html. ( I got this working)

*/var/www - all other contents in the root of my app can only be accessed after authentication. This is the part I don't know how to setup.

My vhost conf looks like this.
    NameVirtualHost *:80
<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host2.example.com
    DocumentRoot "/var/www"
    ServerName auth-test.ml.com
    ErrorLog "logs/test-error_log"
    CustomLog "logs/test-access_log" common

<Directory "/var/www">
    AuthFormProvider file
    AuthType form
    AuthName "Reserved Area"
    Session On
    SessionCookieName session path=/
    require valid-user

        # This is the login page
    ErrorDocument 401 /login/index.html

    # This is the file containing users login data
    AuthUserFile /usr/local/apache2/auth/.htpasswd

</Directory>
 <Directory /var/www/login>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
   </Directory>

</VirtualHost>

AT the moment when I access the app like http://example.com  I expect to see the login.html page returned but I get the following error message:
Unauthorized

This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.

Additionally, a 401 Unauthorized error was encountered while trying to use an ErrorDocument to handle the request.

How can I make this work?

A: Figured it out. It was as simple as using Directory to first deny access to all to the root document and only allow valid users.
Using another Directory to open access to all to the auth folder.


text:
Q: Specify function parameter in jest mocking I am currently writing unit tests to improve my coverage and I am stuck on a function where I want to set the input parameter of a function.
The function I want to test is:
this.map.forEachFeatureAtPixel(e.pixel, (event: any) => {
    if (
      event.values_.name === 'name'
    ) {
      this.openWeatherData(event.values_.name);
    } //more logic ...
  });

I want to test the code inside the callback function to test if the correct calls are made.
But how do I set the event parameter to something like
{ values_ : { name: 'name' } }

and execute the actual callback implementation to improve my coverage.

A: Use jest.spyOn(object, methodName) to create a mock version for this.map.forEachFeatureAtPixel() method and its mocked implementation. The mocked implementation accept two paramters: pixel and callback. Invoke the callback function manually with your mocked event object.
E.g.
index.ts:
export const obj = {
  map: {
    // simulate real implementation
    forEachFeatureAtPixel(pixel, callback) {
      callback();
    },
  },
  method(e) {
    this.map.forEachFeatureAtPixel(e.pixel, (event: any) => {
      if (event.values_.name === 'name') {
        console.log('openWeatherData');
      }
    });
  },
};

index.test.ts:
import { obj } from './';

describe('67818053', () => {
  it('should pass', () => {
    const mEvent = { values_: { name: 'name' } };
    const forEachFeatureAtPixelSpy = jest
      .spyOn(obj.map, 'forEachFeatureAtPixel')
      .mockImplementationOnce((pixel, callback) => {
        callback(mEvent);
      });
    obj.method({ pixel: '12' });
    expect(forEachFeatureAtPixelSpy).toBeCalledWith('12', expect.any(Function));
    forEachFeatureAtPixelSpy.mockRestore();
  });
});

test result:
 PASS  examples/67818053/index.test.ts (8.297 s)
  67818053
    ✓ should pass (14 ms)

  console.log
    openWeatherData

      at examples/67818053/index.ts:11:17

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.055 s


text:
Q: Need suggestions on what tool to use for manipulating a file We have a need to create a daily process that will manipulate a file that is now being manually generating before FTPing it to a vendor. The issues with the current file are as follows:
1) It is currently comma delimited and it needs to be pipe delimited.
2) The vendor only want specific columns to be sent. They have a limit of 26 columns.
We need to develop an automated process that can be scheduled to run once a day and pick up a file with a specific extension, do the file manipulation and FTP the file.
Ideally, we would like to have some error handling in the process. We would want an email to get sent out if there was no file to process or if there was an error during the manipulation or FTP process.
My first thought was to use SQL Server Import/Export. I've done this before but that was only for packages that could be run manually. This process needs to be fully automated (after the existing file is manually generated.) I don't see a way to pick up any file with a specific extension. It looks like I have to select a specific file.
Is there a way to use Import/Export or some similar tool?
Or, do I need to write a program to do this sort of task? It seems to me like it would be more work to write a program. So, I am trying to avoid that.
Thank you for your help!

A: You should write a program.  Seriously.


text:
Q: How to destroy one radix tree in linux kernel I'm trying to use radix tree to maintain one internal data for the driver. So what's the proper way to destroy the whole tree?
One thought is to traverse the tree with the method mentioned at: 1
For each node, free the item and delete its key from the tree.
The other question is, is radix_tree_for_each_slot() safe with delete item inside the loop? Will delete trigger internal shrink and cause iteration failure?

A: Check out cgwb_bdi_unregister.
It seems to be doing pretty much what you need - it iterates over the radix tree with radix_tree_for_each_slot() and while doing so it does also radix_tree_delete (from cgwb_kill).
So I guess nothing should blow up if you're keeping things properly synchronized.


text:
Q: Is it possible in C++ to type multiple lines of string outputs without have to continually add the prefix "cout"? I just started learning C++. I have seen examples of coders typing code like this...
int main() {

    cout << "hello";
         << "world";
    return 0;
}

but when I tried that it seemed to me that I have to write it like this...
int main() {
    cout << "hello";
    cout << "world";
    return 0;
}

How can I do this like the original example shows?

A: You might mean:
int main() {

    cout << "hello"  // <- no trailing `;`
         << "world";
    return 0;
}

That will print:
helloworld

If you wanted then on separated rows, you can write:
int main() {

    cout << "hello\n"
         << "world\n";
    return 0;
}

That will produce:
hello
world

But, there is another, less known, feature of the compiler - concatenation
of raw strings:
int main() {
    cout << "hello"
            "world";
    return 0;
}

That will also work. This too gives helloworld as output.


text:
Q: PHP Redirects work in every browser but Edge This PHP redirect works with every browser but Edge:
http://localhost/index.php/de/tag-suche?agdetagsearchs_checkbox[0]=2&Agdetagsearch=1&language=de-DE&Itemid=111&option=com_agdetagsearchs&lang=de-DE&view=category&id=11&limit=20&agtagscolumnlimit=3&agtagscolumnlimit_fields=1&agde_language=all#agdetagsearch-resultlist

The problem does not exist in any other browsers.
When I manually type the URL into the address bar, it also renders properly.
I tried to use Post instead of GET, but the form did not submit as well.
I tried it with different web servers and different clients.
I found this question: Microsoft Edge does not redirect page with Chinese characters properly
This could be a similar problem. Also I do not use Chinese characters.


text:
Q: field is not created or edited Field is not created or edited in views Create and Edit (C# MVC4 CodeFirst).
The rest of the field with the data types string or integer created and edited properly and correctly.
In Model Requirement:
...

    public int RequirementId { get; set; }

    //[StringLength(500, MinimumLength = 500)]
    public string Definition { get; set; }
    public string Rationale { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime CreatedOn { get; set; }

    public virtual Users CreatedBy { get; set; }
    public virtual Users Responsible { get; set; }
    public virtual ICollection<Users> InterestedPersons { get; set; }

    public string CurentVersion { get; set; }
    public StateEnum State { get; set; }
    public PriorityEnum Priority { get; set; }
    public StabilityEnum Stability { get; set; }
    public TypeEnum Type { get; set; }

    public virtual BusinessRule Source { get; set; }
    public virtual ICollection<TestCase> TestCase { get; set; }

    public string UserPart { get; set; }

...

Controller RequirementController (in method Create):
 public ActionResult Create()
    {
        RequirementViewModel reqVM = new RequirementViewModel();
        AutoMapper.Mapper.CreateMap<RequirementViewModel, Requirement>();
        reqVM.UserList = new SelectList(db.Users, "UsersId", "Surname");
        reqVM.BusinessRuleList = new SelectList(db.BusinessRule, "BusinessRuleId", "Definition");
        reqVM.TestCaseList = new SelectList(db.TestCase, "TestCaseId", "Title");
        Requirement requirement = AutoMapper.Mapper.Map<RequirementViewModel, Requirement>(reqVM);

        return View();
    }

        //
        // POST: /Requirement/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Requirement requirement)
        {
             try
            {
                AutoMapper.Mapper.CreateMap<RequirementViewModel, Requirement>();
                reqVM.UserList = new SelectList(db.Users, "UsersId", "Surname");
                reqVM.BusinessRuleList = new SelectList(db.BusinessRule, "BusinessRuleId", "Definition");
                reqVM.TestCaseList = new SelectList(db.TestCase, "TestCaseId", "Title");

                Requirement requirement = AutoMapper.Mapper.Map<RequirementViewModel, Requirement>(reqVM);

                if (ModelState.IsValid)
                {
                    db.Requirement.Add(requirement);
                    db.SaveChanges();
                    return RedirectToAction("Index"); //, new { id = requirement.InterestedPersons }
                }
            }
            catch (DataException /* dex */)
            {
                //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            return View();
}

View Create:
    ...

  @model OpenSoft.AgileAnalytics.EF.Models.Requirement
  @{
    ViewBag.Title = "Create";
   }

Create

    @using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Requirement</legend>
        @*@Html.EditorForModel()*@

        @Html.LabelFor(model => model.Definition)

        @Html.EditorFor(model => model.Definition)
        @Html.ValidationMessageFor(model => model.Definition)

        @Html.LabelFor(model => model.Rationale)

        @Html.EditorFor(model => model.Rationale)
        @Html.ValidationMessageFor(model => model.Rationale)

        @Html.LabelFor(model => model.CreatedOn)

        @Html.EditorFor(model => model.CreatedOn)
        @Html.ValidationMessageFor(model => model.CreatedOn)

        @Html.LabelFor(model => model.CreatedBy)

        @Html.DropDownListFor(model => model.CreatedBy, Model.UserList, "-Select-") //error
        @Html.ValidationMessageFor(model => model.CreatedBy)

        @Html.LabelFor(model => model.Responsible)

        @Html.DropDownListFor(model=>model.Responsible, Model.UserList, "-Select-") //error
        @Html.ValidationMessageFor(model => model.Responsible)

            @Html.LabelFor(model => model.InterestedPersons)

            @Html.ListBoxFor(model=>model.InterestedPersons, Model.UserList) //error
            @Html.ValidationMessageFor(model => model.InterestedPersons)

        @Html.LabelFor(model => model.CurentVersion)

        @Html.EditorFor(model => model.CurentVersion)
        @Html.ValidationMessageFor(model => model.CurentVersion)

        @Html.LabelFor(model => model.UserPart)

        @Html.EditorFor(model => model.UserPart)
        @Html.ValidationMessageFor(model => model.UserPart)

        @Html.LabelFor(model => model.State)

        @*@Html.EnumDropDownList(model => model.StateEnum)*@
            @Html.DropDownListFor(m => m.State, new SelectList(Enum.GetValues(typeof(OpenSoft.AgileAnalytics.EF.Models.StateEnum))))
            @Html.ValidationMessageFor(model => model.State)

            @Html.LabelFor(model => model.Priority)

            @Html.DropDownListFor(m => m.Priority, new SelectList(Enum.GetValues(typeof(OpenSoft.AgileAnalytics.EF.Models.PriorityEnum))))
            @Html.ValidationMessageFor(model => model.Priority)

            @Html.LabelFor(model => model.Stability)

            @Html.DropDownListFor(m => m.Stability, new SelectList(Enum.GetValues(typeof(OpenSoft.AgileAnalytics.EF.Models.StabilityEnum))))
            @Html.ValidationMessageFor(model => model.Stability)

            @Html.LabelFor(model => model.Type)

            @Html.DropDownListFor(m => m.Type, new  SelectList(Enum.GetValues(typeof(OpenSoft.AgileAnalytics.EF.Models.TypeEnum))))
            @Html.ValidationMessageFor(model => model.Type)

            @Html.LabelFor(model => model.Source)

            @Html.DropDownList("BusinessRuleId", "-Select-")
            @Html.ValidationMessageFor(model => model.Source)

            @Html.LabelFor(model => model.TestCase)

            @Html.DropDownList("TestCaseId", "-Select-")
            @Html.ValidationMessageFor(model => model.TestCase)

            <input type="submit" value="Create" />

    </fieldset>
  }

      @Html.ActionLink("Back to List", "Index")

   @section Scripts {
     @Scripts.Render("~/bundles/jqueryval")
 }

    ...

In the drop-down lists the elements of the right.
Help please with the work with these fields model:)

A: Your properties CreatedBy, Responsible and InterestedPersons are complex objects. A <select> only posts back a single value (or array of values in the case of multiple). In addition the name of your dropdowns are all UsersId but your model does not contain a property named UsersId so nothing is bound.
Create a view model to represent the data you want to edit.
public class RequirementVM
{
  public int RequirementId { get; set; }
  public string Definition { get; set; }
  .... // other properties of Requirement that you want to edit

  [Required]
  [Display(Name="Created by")]
  public int? CreatedBy { get; set; }

  [Required]
  public int? Responsible { get; set; }

  public int[] InterestedPersons { get; set; }

  public SelectList UserList { get; set; }

}

Controller
public ActionResult Create()
{
  RequirementVM model = new MyViewModel();
  model.UserList = new SelectList(db.Users, "UsersId", "Surname");
  return View(model);
}

[HttpPost]
public ActionResult Create(RequirementVM model)
{
  ...
}

View
@model RequirementVM
....
@Html.LabelFor(model => model.Definition)
@Html.EditorFor(model => model.Definition)
@Html.ValidationMessageFor(model => model.Definition)

... other properties of RequirementVM to edit

@Html.LabelFor(m => m.CreatedBy)
@Html.DropDownListFor(m => m.CreatedBy, Model.UserList, "-Select-")
@Html.ValidationMessageFor(m => m.CreatedBy)

@Html.LabelFor(m => m.Responsible)
@Html.DropDownListFor(m => m.Responsible, Model.UserList, "-Select-")
@Html.ValidationMessageFor(m => m.Responsible)

@Html.LabelFor(m => m.InterestedPersons)
@Html.ListBoxFor(m => m.InterestedPersons, Model.UserList)
@Html.ValidationMessageFor(m => m.InterestedPersons)


text:
Q: API Koa server in the backend for Nuxt doesn't run on Heroku (production) I'm running Nuxt in Universal Mode with Koa as API / Controller in the backend based on the Koa template. I'm deploying to Heroku. API works fine locally, but returns 404 in production. I think that the app is running as SPA when deployed as everything else works well.
Here's  my server/index.js
const Koa = require('koa')
const consola = require('consola')
const Router = require('koa-router');
const { Nuxt, Builder } = require('nuxt')
const api = require('./api');

console.log('server works'); // ------> This line gets ignored by the Heroku console

const app = new Koa()
const router = new Router();

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'

router.use('/api', api.routes(), api.allowedMethods());
app.use(router.routes());

async function start () {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`, //  ------>  Neither this line appears in Heroku console
    badge: true
  })
}

start()

Procfile
web: nuxt start

Scripts from package.json
"scripts": {
    "dev": "cross-env HOST=192.168.1.65 NODE_ENV=development nodemon server/index.js --watch server ",
    "build": "nuxt build",
    "start": "cross-env NODE_ENV=production node server/index.js",
    "generate": "nuxt generate",
    "test": "ava",
    "test:unit": "cross-env TEST=unit ava --config unit.config.js",
    "test:e2e": "cross-env TEST=e2e ava --config e2e.config.js",
    "heroku-postbuild": "nuxt build"
  }

I think I'm getting nu(x)ts after reading all these deployment docs and not seeing the obvious.
Thanks.

A: I didn't live any problem, attaching my package.json, server/index.js file and Heroku environment settings. You can check herokuapp from here
package.json
{
  "name": "testkoa",
  "version": "1.0.0",
  "description": "My first-class Nuxt.js project",
  "author": "Ahmet Zeybek",
  "private": true,
  "scripts": {
    "dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
    "build": "nuxt build",
    "start": "cross-env NODE_ENV=production node server/index.js",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.3.6",
    "@nuxtjs/dotenv": "^1.4.0",
    "@nuxtjs/pwa": "^3.0.0-0",
    "cross-env": "^5.2.0",
    "koa": "^2.6.2",
    "koa-router": "^7.4.0",
    "nuxt": "^2.0.0"
  },
  "devDependencies": {
    "nodemon": "^1.18.9"
  }
}

server/index.js
const Koa = require("koa");
const Router = require("koa-router");
const consola = require("consola");
const { Nuxt, Builder } = require("nuxt");
const app = new Koa();
// Import and Set Nuxt.js options
const config = require("../nuxt.config.js");
config.dev = app.env !== "production";

async function start() {
  app.use(async function handleError(ctx, next) {
    try {
      await next();
    } catch (err) {
      ctx.status = err.statusCode || err.status || 500;
      ctx.body = err;
    }
  });
  const router = new Router({ prefix: "/api" });
  router.get("/:name", async ctx => {
    ctx.response.body = `Hello ${ctx.params.name}`;
  });
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config);

  const {
    host = process.env.HOST || "127.0.0.1",
    port = process.env.PORT || 3000
  } = nuxt.options.server;

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt);
    await builder.build();
  } else {
    await nuxt.ready();
  }

  app.use(router.routes());
  app.use(router.allowedMethods());
  app.use(ctx => {
    ctx.status = 200;
    ctx.respond = false; // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res);
  });

  app.listen(port, host);
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  });
}

start();

Heroku Config Vars
HOST=0.0.0.0
NODE_ENV=production
NPM_CONFIG_PRODUCTION=false

You don't need Procfile to use your Nuxt app on Heroku with this
  configuration, remove it from your project folder


text:
Q: How to solve HTTP Error 502.5 - Process Failure when I use Topshelf to create windows service under asp.netcore? I create a asp.netcore project with visual studio 2017. And I install TopShelf from Nuget and add code in Program.Main() below:
 public static void Main(string[] args)
 {
     var rc = HostFactory.Run(x =>
     {
         x.Service<MainService>(s =>
         {
             s.ConstructUsing(name => new MainService(args));
             s.WhenStarted(tc => tc.Start());
             s.WhenStopped(tc => tc.Stop());
         });
         x.RunAsLocalSystem();

         x.SetDescription("ASP.NETCoreTest");
         x.SetDisplayName("ASP.NETCoreTest");
         x.SetServiceName("ASP.NETCoreTest");
     });

     var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
     Environment.ExitCode = exitCode;
 }

In MainService.cs:
public void Start()
{
    Task.Factory.StartNew(() => this.StartExecuting(), TaskCreationOptions.LongRunning);
}
public void StartExecuting()
{
    CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

Stratup.cs is default.
Next, I run IIS Express, and it can work, showing as (although it is a little strange)(https://localhost:44345/):

Next, I add RuntimeIdentifiers win7-x64 in PropertyGroup and publish application in CMD:
dotnet publish -c Release -r win7-x64

Finally, I install ASP.NETCoreTest.exe and start ASP.NETCoreTest.exe, But it show as (https://localhost:44345/):

In Event Management, it tell me the error:

What should I do?
Please help me, thanks!
Update: If I exit IIS Express, it show it cannot connect to this site.
Maybe site should be opened with other way (Not https://localhost:44345/)?


text:
Q: Retrieving denormalized data in firebase I'm new to firebase and learned that I should save my data in a denormalized way. I am saving some goals written by users. And I'm allowing other users to add comments. That's working well. Whenever a user submits a comment, the comment gets saved in comments node and the goal also gets updated by adding a key to the related comments ID.
**comments**
    -LmkoRGfB5GX4Q8NKkBz
    -LmkoTE3sdM3_PYuEtco
        comment-text: "another comment"
        time: 87293862
   -LmlUwUdsUVH5ymTXDoj
   -LmlyU2drjD6gI7GGZzp

**goals**
   -user1
       goalID1
          comments
            -LmkoTE3sdM3_PYuEtco: true
          goal: "I struggle to wake up on time"
          plan: "I will definitely wake up when the alarm clock ..."

I can't figure out how to retrieve the comments when I retrieve the information about the goal. Here is how I am retrieving info about the goal. How do I add a loop to get the info about the comments?
firebase.database().ref('/goals/' + req.body.userId).orderByChild(goalId).equalTo("goalID1").on('value', (snapshot) => {
      snapshot.forEach((item) => {
        items.push({
          key: item.key,
          goal: item.val().goal,
          plan: item.val().plan,
          comments:item.val().comments
        });
      });

      res.status(200).json(items)

A: Something like this should do the trick:
firebase.database().ref('/goals/' + req.body.userId).orderByChild(goalId).equalTo("goalID1").on('value', (snapshot) => {
  let promises = [];
  var item;
  snapshot.forEach((item) => {
    item = {
      key: item.key,
      goal: item.val().goal,
      plan: item.val().plan,
      comments: []
    }
    snapshot.child('comments').forEach((commentKey) => {
      let promise = firebase.database().ref('comments').child(commentKey.key).once('value');
    });
  });
  Promise.all(promises).then((snapshots) => {
    snapshots.forEach((snapshot) => {
      item.comments.push(snapshot.val());
    })
    items.push(item);
    res.status(200).json(items);
  })

Some syntax and scope errors are possible, but this should be the rough idea: you load each comment in a loop, and thus have to wait for all comments to be loaded before sending a response to the caller.


text:
Q: How to change settings for Win10 File Explorer's "Frequent Folders" I use the File Explorer's Quick Access "Frequent Folders" section a lot but it seems to take a while before a folder will appear there.  Is there a way to change the setting so folders will appear sooner?  I know how to pin folders but that's not what I want to do.
EDIT:  For example, there's clearly some default setting that tells Explorer to add a folder to the Frequent Folder section after X clicks (or other events).  Is there a way--via a setting, the registry, a freeware utility--to change X to Y?


text:
Q: Sorting by selectbox in XSLT I have this selectbox on a site Im currently building and what I want to do, is sort a list of items displayed on the page by the value that's being selected.
The problem is that I got different kinds of data types, e.g. location and price.
If I want to sort on location, no problem it sorts perfectly on alphabetic order of the location names. But if I sort on the 'Low budget', which is from low to high in price, I have to add additional tags to the sort (data-type="number"). That works fine, but then the location and such aren't working anymore.
How to solve this to make it handle all kinds of different data types?
My XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">

<xsl:param name="url-filter" select="'recommended'" />

<xsl:template name="resort-list" match="data/resorts/entry">
    <form name="sort-form" action="{$root}/resorts/" method="get">
            <select name="filter" onChange="document.getElementById('sort-form').submit();">
                <option value="">Sort By...</option>
                <option value="recommended">Recommended</option>
                <option value="location">Location</option>
                <option value="prices-from">Low budget</option>
                <option value="prices-till">High budget</option>
            </select>
    </form>

      <xsl:for-each select="data/resorts/entry">

         <xsl:sort select="*[name() = $url-filter]" />

<xsl:value-of select="resort-name"/>

                        <xsl:call-template name="truncate">
                            <xsl:with-param name="value" select="resort-description" />
                            <xsl:with-param name="length" select="150" />
                        </xsl:call-template>

     </xsl:for-each>
</xsl:template>

<xsl:include href="../utilities/master.xsl"/>
</xsl:stylesheet>

My XML:
<data>
    <events />
    <resorts>
        <pagination total-entries="11" total-pages="2"
        entries-per-page="10" current-page="1" />

Resorts

        <entry id="114">
            <price-from handle="1200">1200</price-from>
            <price-till handle="1900">1900</price-till>
            <recommended>No</recommended>
            <lipe-green-aware-resort>No</lipe-green-aware-resort>
            <name>Baja Resort</name>
            <location>Sunrise Beach</location>
        </entry>
    </resorts>
</data>

A: This transformation correctly sorts for each possible parameter value: "recommended" or "price-from":
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:param name="url-filter" select="'price-from'" />

 <xsl:variable name="vSortOrder">
  <xsl:choose>
   <xsl:when test="$url-filter = 'price-from'">
    <xsl:text>ascending</xsl:text>
   </xsl:when>
   <xsl:otherwise>descending</xsl:otherwise>
  </xsl:choose>
 </xsl:variable>

 <xsl:variable name="vSortType">
  <xsl:choose>
   <xsl:when test="$url-filter = 'price-from'">
    <xsl:text>number</xsl:text>
   </xsl:when>
   <xsl:otherwise>text</xsl:otherwise>
  </xsl:choose>
 </xsl:variable>

 <xsl:template name="resort-list" match="data/resorts">
    <form name="sort-form" action="/*/resorts/" method="get">
            <select name="filter" onChange="document.getElementById('sort-form').submit();">
                <option value="">Sort By...</option>
                <option value="recommended">Recommended</option>
                <option value="location">Location</option>
                <option value="prices-from">Low budget</option>
                <option value="prices-till">High budget</option>
            </select>
    </form>

      <xsl:for-each select="entry">

         <xsl:sort select="*[name() = $url-filter]"
          data-type="{$vSortType}" order="{$vSortOrder}" />

<xsl:value-of select="name"/>

     </xsl:for-each>
 </xsl:template>

 <xsl:template match="/">

   <xsl:apply-templates/>

 </xsl:template>
</xsl:stylesheet>

With the this XML document (extending the provided with just one more entry):
<data>
    <events />
    <resorts>
        <pagination total-entries="11" total-pages="2"
        entries-per-page="10" current-page="1" />

Resorts

        <entry id="114">
            <price-from handle="1200">1400</price-from>
            <price-till handle="1900">1900</price-till>
            <recommended>No</recommended>
            <lipe-green-aware-resort>No</lipe-green-aware-resort>
            <name>Baja Resort</name>
            <location>Sunrise Beach</location>
        </entry>
        <entry id="115">
            <price-from handle="1500">1500</price-from>
            <price-till handle="1700">1700</price-till>
            <recommended>Yes</recommended>
            <lipe-green-aware-resort>No</lipe-green-aware-resort>
            <name>Blah-Blah Resort</name>
            <location>Blah-Blah Beach</location>
        </entry>
    </resorts>
</data>

and with each of the two possible values of the $url-filter parameter, the correct results are produced sorted with the correct sort-key data type and in the correct sort order (ascending or descending).

A: Good question. Here's a way to do it:

*

*Create a named template for your
inner  element, call it "link"
for example.

*Create two named templates for your sorted for-each: "sort-by-alpha"
and "sort-by-number".

*"sort-by-number" does a for-each, sorts by number, and calls the "link" template.

*"sort-by-alpha" does a for-each, sorts (by alpha), and calls the "link" template.

*In your outer template, outside of where you currently have for-each on data/resorts/entry, put a choose-when-test-otherwise that decides to call "sort-by-number" when the sort criterion is prices-from or prices-till; otherwise, it calls sort-by-alpha.

Does that make sense? Let me know if this doesn't do it for you.


text:
Q: FormatException was unhandled by user code (string format is not in correct format) Converting the Value of SQL Field from numeric type to double.
Input string was not in a correct format.
Can someone help me solve this? Thanks in Advance!
Declaration of new List:
public class OTTotal
{
public double OTPLAN;
public double OTACT;
}

then I have this code to pass the Value of database fields to those public variables.
            mylist.Add(new OTTotal
            {

                OTAct = double.Parse(dr["OT"].ToString()) /*+ double.Parse(dr["SH"].ToString()) + double.Parse(dr["SHtwo"].ToString())*/,
                OTPlan = double.Parse(dr["POT"].ToString())

            });

also this code was highlighted when i run the program and says incorrect format.

Stored Procedure
CREATE PROCEDURE [dbo].[spTotalOverTime]
    @grpID as INT = 0,
    @date as DATE = '2018/3/1'
AS
BEGIN

    SELECT SUM(a.Overtime) as OT, SUM(a.PlanOt) as POT, SUM(a.SunHoliday) as SH, SUM(a.SunHoliday2) as SHtwo FROM tblTimesheet a JOIN userinfo b on a.empID = b.empID   JOIN tblGroup c on b.groupNo = c.groupID
            WHERE YEAR(a.tsDate) =  YEAR(@Date) AND MONTH(a.tsDate) = MONTH(@date) AND c.groupID = CAST(@grpID AS VARCHAR)

END

A: Try Convert.ToDouble(dr["OT"]);

A: I have solve my Problem. I think the main problem is I have a Empty Value in my column that is why it cannot be converted to double.
But Thank you all for giving me a hint to solve it :)
So this is the counter measure to solve my Problem.
  mylist.Add(new OTTotal
                {

                    OTAct = (dr["OT"].ToString() == ""? 0.0 : double.Parse(dr["OT"].ToString())) + (dr["SH"].ToString() == "" ? 0.0 : double.Parse(dr["SH"].ToString())) + (dr["SHtwo"].ToString() == "" ? 0.0 : double.Parse(dr["SHtwo"].ToString())),
                    OTPlan = (dr["POT"].ToString() == "" ? 0.0 : double.Parse(dr["POT"].ToString()))

            });

Thanks Everyone :)


text:
Q: How to find these "breaking" points on an offseted curve? Check the picture:

I noticed that for big offset values the offseted curves often "breaks" like this (one or more times).
So my question is that what is that point marked with ':-(', and how can I find it for a given curve and a given offset value (numerically or analytically).

A: Those breaks occur at "focal points", where the "normal lines" to nearby points on the original curve all intersect. For a circle, with outward pointing normals, there's just one of these --- at the center of the circle (i.e., offset by $-r$, where $r$ is the radius).
In general, assuming your curve is given parametrically as $t \mapsto x(t), y(t)$, you can compute the curvature at each point $t$ via
$$
\kappa(t) = \frac{x'(t) y''(t) - y'(t) x''(t)}{(x'(t)^2 + y'(t)^2)^\frac{3}{2}}
$$
The inverse of this is called the "Radius of curvature",
$$
R(t) = \frac{1}{\kappa(t)}.
$$
In general, if you compute $R(t)$ for every point of the curve, you can offset the curve by any value $s$ that's less than $R(t)$ for all $t$; when you offset by an amount equal to the radius of curvature at some point, you tend to get a "break" at the resulting focal point.


text:
Q: Prevent scrollviewer from going to different horizontal offset when calendar is rescaled I've a calendar view which I'm re-scaling by increasing the width of the day (Code below). On re-scaling, how can I make sure that my calendar retains the same view at different rescale points (ie:- I have 4 rescale points, 25%,50%,75%,100% which means increase the width of the day in the calendar by 25%,50% etc)? If my current rescale point is 100% and my horizontal offset points to Apr 2018, on changing to 50%, Apr 2018 is not getting retained and the current horizontal offset is pointing to a different month. How can I make sure that the same view is retained? Any thoughts?
<ScrollViewer Name="CalendarScroller" HorizontalScrollBarVisibility="Auto"
                      VerticalScrollBarVisibility="Disabled"
                      ViewChanged="ScrollViewer_ViewChangedAsync" >
        <Grid Name="CalendarGrid" Margin="0,0,0,0">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid><ListView  Name="LayoutView"
                           SelectionMode="None" BorderThickness="0"
                           ItemsSource="{x:Bind calendarVM.Calender,Mode=OneWay}"
                           Loaded="LayoutView_Loaded"
                           >
                        <ListView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <ItemsStackPanel Orientation="Horizontal"
                                             />
                            </ItemsPanelTemplate>
                        </ListView.ItemsPanel>
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="entity:Calendar" >
                                <Grid Margin="0,0,0,0" Padding="0" >
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="30"/>
                                        <RowDefinition Height="*"/>
                                    </Grid.RowDefinitions>
                                    <Grid Background="#FAFAFA">
                                        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"
                                                       VerticalAlignment="Center" Margin="10,0,0,0">
                                        <TextBlock Text ="{x:Bind Month}" FontWeight="Bold" FontSize="14" />
                                        <TextBlock Text="{x:Bind Year}" Margin="2,0,0,0" FontWeight="Bold" FontSize="14"/>
                                    </StackPanel>
                                </Grid>
                                <Grid Grid.Row="1">
                                    <ListView  Grid.Row="1"
                                               Name="LayoutDaysView"
                                               SelectionMode="None"
                                               VerticalAlignment="Stretch" VerticalContentAlignment="Stretch"
                                               ScrollViewer.HorizontalScrollBarVisibility="Auto"
                                               ScrollViewer.HorizontalScrollMode="Enabled"
                                               ScrollViewer.IsHorizontalRailEnabled="True"
                                               ScrollViewer.VerticalScrollBarVisibility="Disabled"
                                               ScrollViewer.VerticalScrollMode="Disabled"
                                               ItemsSource="{x:Bind Days}"
                                               >
                                        <ListView.ItemsPanel>
                                            <ItemsPanelTemplate>
                                                <ItemsStackPanel Orientation="Horizontal"/>
                                            </ItemsPanelTemplate>
                                        </ListView.ItemsPanel>
                                        <ListView.ItemTemplate>
                                            <DataTemplate x:DataType="entity:Day">
                                                <Grid Margin="0,0,0,0" Padding="0" Background="Transparent">
                                                    <Grid.RowDefinitions>
                                                        <RowDefinition Height="30"/>
                                                        <RowDefinition Height="*"/>
                                                    </Grid.RowDefinitions>
                                                    <Grid.ColumnDefinitions>
                                                        <ColumnDefinition Width="*"/>
                                                    </Grid.ColumnDefinitions>
                                                    <Grid Background="#FAFAFA"
                                                          Width="{x:Bind Width,Mode=TwoWay}"
                                                          Margin="0,0,0,0">
                                                        <Ellipse Width="28" Height="26" Fill="{x:Bind CurrentDayBg}"
                                                         Margin="0,0,3,5"
                                                         Visibility="{x:Bind IsShowCurrentDay}"/>
                                                        <TextBlock Text="{x:Bind DayOfMonth}" Margin="0,1,3,0" FontSize="14"
                                                                       Opacity="{Binding Opacity}" TextAlignment="Center" Foreground="{x:Bind CurrentDayFg}"  />
                                                    </Grid>
                                                    <Grid Width="{x:Bind Width,Mode=TwoWay}" Margin="0,0,0,0"
                                                          Grid.Row="1"     MinHeight="{x:Bind Height}"
                                                          Background="{x:Bind DayBackground}">
                                                        <Border BorderBrush="#FAFAFA"  BorderThickness="0,0,2,0"
                                                        HorizontalAlignment="Right" Grid.Row="2" />
                                                    </Grid>
                                                </Grid>
                                            </DataTemplate>
                                        </ListView.ItemTemplate>
                                    </ListView>
                                </Grid>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Grid>
        </Grid>
    </ScrollViewer>

Code behind:- (Another header view that has the rescaling slider raises an event which is captured in this view to initiate rescaling)
private void OnRescalingCalendar(int daysWidth)
            {

                foreach (var day in calendarVM.Calender.SelectMany(x => x.Days))
                    day.Width = daysWidth;
            }

[enter image description here][1]

  [1]: https://i.stack.imgur.com/yaPcM.png


text:
Q: Moving from one activity to another activity in android studio I'm writing an application in android studio IDE which shows the models,brands ,prices and etc of the cars and I want to move from one activity to another one.can I use putExtra?if yes i wonder if anyone would like to tell me how can i use it.

A: You can pass data between activities in easiest way like this.
In the first activity use out extra to send the data
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("YOUR_DATA_KEY", data);
startActivity(intent);

Access that intent on next activity like this
String s = getIntent().getStringExtra("YOUR_DATA_KEY");

A: try this
 Intent intent=new Intent(this,YourActivity.class);
 intent.putExtra("key",value);
 startActivity(intent);

A: Try the following
Intent intent =new Intent(FirstActivity.this,SecondeActivity.class);
StartActivity(intent);


text:
Q: C# Data Transformation on Single Object I am trying to wondering if there is a way to transform a method result into a new object in a single line, as is possible when using a List, Linq, and Lambda expressions.
Example using lists:
List<int> ints = GetListOfInts();
List<anotherClass> = ints.Select(x => new anotherClass(){ memberVariable = x }).ToList();

Through this,  I can map a list of type A to a list of type B.
I want to do this on a single object, not a list. Here is what I am intending:
// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = (GetObjectA() x => new ObjectB(){ memberVariable = x });

This is just pseuodocode, and I know it will not compile or work. Is this type of transformation currently possible in C#?
I know I can use mappers, custom methods, etc., but I want to know if it is possible through lamba expressions as it is with lists.

A: // GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = new[]{ GetObjectA() }.Select(x => new ObjectB(){ memberVariable = x }).First();

Not nice, but should work.
However, if it's really that specific code, you could just do
ObjectB objectB = new ObjectB(){ memberVariable = GetObjectA() };

If you want it encapsulated nicely, you could write something like this:
public static class ObjectExtensions
{
    public static TOutput Transform<TInput, TOutput>(this TInput input, Func<TInput, TOutput> transform)
    {
        return transform(input);
    }
}

and use it like that:
// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = GetObjectA().Transform(x => new ObjectB(){ memberVariable = x });


text:
Q: why tan θ > sin θ for range 0 to 90 (i) Prove the identity $$\tan^2 \theta - \sin^2 \theta \equiv \tan^2 \theta\sin^2\theta$$
(ii) Use this result to explain why $\tan θ > \sin θ$ for $0^\circ < \theta < 90^\circ$
I only need the answer for part 2(ii), how tan θ > sin θ ??

A: First of all, if $0^\circ\lt \theta\lt 90^\circ$, then
$$\sin\theta\gt 0\ \ \text{and}\ \ \tan\theta\gt 0.$$
So, since
$$\tan^2\theta\sin^2\theta\gt 0,$$
we have
$$\tan^2\theta-\sin^2\theta=(\tan\theta-\sin\theta)(\tan\theta+\sin\theta)\gt 0.$$
Hence, we have
$$\tan\theta-\sin\theta\gt 0\iff \tan\theta\gt \sin\theta$$
because
$$\tan\theta+\sin\theta\gt 0.$$

A: In the given range $0 \lt \theta \lt 90^\circ, \quad \tan\theta > 0$ and $\sin\theta >0$
From $[i]$, we see that the right-hand side, being the product of two squared values is necessarily positive. So $$\tan^2 \theta - \sin^2 \theta > 0 \implies \tan^2 \theta > \sin^2 \theta\tag{1}$$
And as $\tan \theta$ and $\sin \theta $ are both positive in our range, $(1)$ implies that $$\tan \theta > \sin\theta\quad \text{for }\;0<\theta<90^\circ$$

A: Notice that the left hand side is always positive for $\theta$ in your given range, so what does this say about the difference on the right hand side?


text:
Q: Focus on button instead on input field I have an input field and a close button.
When page loads it focus on the input text field (in ready) but the same focus command $("#param_pattern_value").focus(); in other function (when clicking on tab) focus on the close button instead on the text input field.
HTML:

    <input tabindex="0" class="mdl-textfield__input" type="text" id="param_pattern_value"  value="enter text">

        enter 1

    <button tabindex="0" class="mdl-button mdl-js-button  mdl-button--icon mdl-button--accent margin-left clear_icon_in_input">
        close
    </button>

JS:
$(document).ready(function () {
     $('#param_pattern_value').focus()
});

$("body").keydown(function(e){
        var TAB     = 9;
        var key = e.which;

        if (key == TAB ){
                    $("#param_pattern_value").focus();
        }
    });

LINK TO JSFIDDLE
I have tried many variations but always after clicking on tab it focused on the close button.
Note that on my site, the close button is an "X" icon which placed inside the input field (code looks the same).
Am I doing something wrong?
Thanks!
Mike

A: If you want to set focus on the #param_pattern_value input field whenever a TAB key occurs, you could add a .preventDefault():
$("body").keydown(function(e){
    var TAB = 9;
    var key = e.which;

    if (key == TAB ){
       e.preventDefault();
       $("#param_pattern_value").focus();
    }
});

Please notice, that the $("#param_pattern_value").focus() actually does work in your keydown code, but your handler fires just before the default keydown handler.
You can simply test that using keyup instead, or checking output in console.
JSFiddle Demo

If you simply don't want the X button to be focused, set tabindex="-1" attribute on the button.