text:
Q: SqlAlchemy "too many clients already" error I'm fairly new to python and pyramid framework. Recently I was introduced to SQLSoup to take care of my database (postgres) needs.
dbEngine1 = SqlSoup(settings['sqlalchemy.db1.url'])
users = dbEngine1.users.fetchall()

Everything is working great, however after a short period of using the pyramid app, I'm getting this error message. I have to kill pyramid to release all idling connections in postgres (about 50 idling connection before throwing below exception)
sorry, too many clients already

My question is, how do I close this idling connection, I tried adding a line of code as shown below, but it does not help.
dbEngine1 = SqlSoup(settings['sqlalchemy.db1.url'])
users = dbEngine1.users.fetchall()
dbEngine1.engine.connect().close()

Any pointer from SQLAlchemy gurus?

A: Seems like you create dbEngine1 on each request to yours Pyramid app.
For proper usage SqlSoup in webapp you must use SA Sessions.
See section "Accessing the Session" on this page.

how do I close this idling connection

SqlSoup such as raw SA use the connection pool, each connection in pool at idle status util query executes. This connection pool must be created once.


text:
Q: How to divide the country_map into more than just the country regions in Apache Superset? I am using Apache Superset, specifically country_map to visualize  data.
Is it possible to slice the country maps into more areas than just the regions of the country? How can I achieve that?

A: In order to make changes to country maps, you need to build Superset from sources.
First, fork the Apache Superset repo in your Github. Then clone the repo to your device and enter superset folder:
git clone https://github.com/username/incubator-superset.git
cd incubator-superset

Second:
sudo pip install -r docs/requirements.txt
python3 setup.py build_sphinx

Next, create virtual environment and install superset:
virtualenv -p python3 venv # if virtualenv not found use: `sudo -H pip3 install virtualenv`
source venv/bin/activate
pip install -r requirements.txt
pip install -r requirements-dev.txt # Here I got error "python setup.py egg_info" failed with error code 1. You can skip it or try pip install --upgrade setuptools
pip install -e .
fabmanager create-admin --app superset

pip install python-dotenv # just in case you don't already have it
superset db upgrade # if error pip install pandas==0.23.4 plus pip install sqlalchemy==1.2.18
superset load_examples
superset init

Leave the venv environment to continue building the front-end:
deactivate # exit venv
cd superset/assets
npm ci
npm run dev

Next, go back to superset directory and start the flask local server:
cd superset
FLASK_ENV=development flask run -p 8088 --with-threads --reload --debugger

I got the instructions from Apache Superset GitHub Contributing page
Now, regarding the division of the country maps. What I did was download a new geojson format map and replace the superset map with the new map. Paste the new map in this directory.
cd incubator-superset/superset/assets/src/visualizations/CountryMap/countries

If this a new country and does not already exist in the directory, you also need to add the name at controls.jsx file. File is located here:
cd incubator-superset/superset/assets/src/explore

Open the file and add the new country at the select_country: {...} component. I got the instruction at Superset Visualization Tools Doc
In order for the new country map to show up in the web browser, you need to rerun the command npm run dev at assets directory, and restart the server.
That's what worked for me. Hope it'll be helpful for future users.
PS: Don't forget to upgrade npm in case you have an old version. You'll need it for npm ci command

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does transmission gratings have their max efficiency always at some finite incident angle $\ne0$ Let say we are interested only in transmission gratings. The Bragg condition is $\theta_{incident}=asin(\lambda_L/2\Lambda)$ .
Does the incident angle onto the grating change the maximum diffracted efficiency into some order ?
Can you have optimized grating at normal incidence angle ?

A: For a symmetric grating, at normal incidence you will always have diffraction in to equivalent orders on both sides of normal (e.g. both +1 and -1 orders), and they will be equal by symmetry. A blazed grating will favor one over the other, but as long as one is allowed, the other will be allowed as well.
Off normal, you may be able to make the -1 order disallowed (although that may enable the +2 order). Blazing appropriately will only increase the imbalance further.
So, yes, in general going off-normal will enhance one order.


text:
Q: Two columns linked together when renaming in Pandas dataframe I am having an issue where two columns of my dataframe appear to be linked together. I need to specify the second column to be renamed "Project" by index (in the code below) because it has no column header, but for some files it appears to cause the next column with no header to be renamed "Project" as well. When I try to drop that column by index in the resulting dataset, both columns in the dataset are dropped.

df = df.rename(columns={df.columns[2]: "Project"}

It appears to do this for some data files that I have but not others so it is unclear where the issue is or if it is due to my code below.
The dataset will look something like this:

Classification | Category | Project .... | MTD Budget | Project

dfs=[]

for i in range(12):
    print (i)
    df = pd.read_excel(files[i],sheet_name = sheet,header = None, usecols=range(1,16))

for row in range(df.shape[0]):

    for col in range(df.shape[1]):

        if df.iat[row,col] == 'Classification':
            row_start = row
            break
df = df.loc[row_start:]

new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header

df['Region'] = sheet
df['File'] = files[i].rsplit('/',1)[1]
df['Period'] = files[i].rsplit('Overview - ',1)[1][:-5]

df = df.dropna(axis='columns',how='all')
df = df.dropna(axis='index',how='all')

df = df.rename(columns={df.columns[2]: "Project"})
df = df.loc[:, df.columns.notnull()]

df['Classification'] = df['Classification'].fillna(method='ffill')
df['Category'] = df['Category'].fillna(method='ffill')

dfs.append(df)

A: IIUC, this hack would do:
col_to_change = 2
df.columns = (list(df.columns[:col_to_change]) +
              ['Project'] +
              list(df.columns[col_to_change+1:]
             )

Or:
df.columns = [col if i!=col_to_change else 'Project'
                  for i,col in enumerate(df.columns.to_list()) ]


text:
Q: Sass flex order does nothing on generated elements I have a couple of SVG that get rendered like this
export const MenuHeaderTab = (props: RenderableProps<Props>) =>
{
    const css = props.isActive ? "menu-tab menu-tab-selected" : "menu-tab";

    return (

 props.onClick()} className={css}>
            {props.children}

    )
}

the problem i have is that in desktop mode it works fine cause they render in the order that i want them to. the problem is that in mobile portrait mode i want one of the rendered SVG to be first in the order (row). So i thought i use row and just set the className on the SVG
so here is the sass/css
@media all and (orientation: portrait)
{
    .menu-tab {
        width: 10%;
        height: 20%;
        margin-left: 4vw;
    }
    .menu-close-button {
        order: -1;
    }
    .menu-leaderboard-button {
        order: 2;
    }
    .menu-prize-button {
        order: 3;
    }
    .menu-rules-button {
        order: 4;
    }

so i even provided order to all the SVG and -1 to the one that should be first, but they all stay in the exact same order still. Anyone have any clue why this happens.

A: Order attribute only works if the father element use display: flex
Assuming the .menu-tab is the father's div of this elements .menu-close-button, .menu-leaderboard-button, .menu-prize-button, .menu-rules-button, you just need to set a display: flex to the .menu-tab
Bellow follow an example of the code:
Look athe the close button, its the last element but how its set -1 as order, it become the first element

.menu-tab {
 width: 10%;
 height: 20%;
 margin-left: 4vw;
 display: flex;
}
.menu-tab a{
 margin-right: 10px;
}

.menu-close-button {
 order: -1;
}
.menu-leaderboard-button {
 order: 2;
}
.menu-prize-button {
 order: 3;
}
.menu-rules-button {
 order: 4;
}

  leaderboard
  Prize
  Rules
  Close


text:
Q: Issue with active pointer on mobile, with Phaser 3 I am trying to move my player by clicking on the right or left of the game. While everything is fine on the computer, when I try it on mobile it always moves to the right and after many attempts it starts moving to the left, no matter where press. This is my update function:
if (game.input.activePointer.isDown)
{
    if (game.input.mousePointer.x > 600)
    {
        player.setVelocityX(160);
        player.anims.play('right', true);
    }
    else if (game.input.mousePointer.x < 200)
    {
        player.setVelocityX(-160);
        player.anims.play('left', true);
    }
} else {
    player.setVelocityX(0);
    player.anims.play('turn', true);
}

A: That's because you're using the mousePointer which will only look at the mouse.
From the mousePointer documentation:

The mouse has its own unique Pointer object, which you can reference directly if making a desktop specific game. If you are supporting both desktop and touch devices then do not use this property, instead use activePointer which will always map to the most recently interacted pointer.

Switch to activePointer for all your logic and you should be set.
If you're using physics, which it appears you might be, the reason it's moving slightly may have to do with logic somewhere else in your code; that's the only reason I can think of given your if statements.


text:
Q: Node js Sequential Request with setTimeout not able to get output array to proccess further sequential request with synchronous request with
Using Rest Api get method called sequential request of settimeout on 1 sec.
after each request data massaging and  put in array.
Now I would like  to get this array after all request were done.
       async function sequentialMF(mfIds) {
        var mfData = [];
        try {
            var timeout = 0;
            return await Promise.all(mfIds.map(mfId => {
                console.log(mfId)
                var options = {
                    //https://www.quandl.com/api/v3/datasets/AMFI/103504.json?api_key=WfUR65SA5p1PzpBysgK4
                    method: 'GET',
                    url: 'https://www.quandl.com/api/v3/datasets/AMFI/' + mfId + '.json',
                    qs: { api_key: 'WfUR65SA5p1PzpBysgK4' },
                };
                setTimeout(function () {
                    request(options, function (error, response, body) {
                        var obj = JSON.parse(body);
                        var mfobj = {
                            "code": obj.dataset.dataset_code,
                            "name": obj.dataset.name,
                            "date": obj.dataset.end_date,
                            "nav": obj.dataset.data[0][1]
                        }
                        mfData.push(mfobj);
                        console.log(obj.dataset.dataset_code + '  ' + obj.dataset.data[0][1]);
                        console.log('lngth ' + mfData.length + '  ' + mfIds.length)
                    })
                }, timeout);
                timeout += 1000;
                new Promise(function (resolve, reject) {
                    if (mfData.length === mfIds.length) {
                        console.log('testing')
                        resolve(mfData);
                    } else reject('errrrrrrrrrrrrror')
                })
            }))
        } catch (err) {
            console.log(err)
        }
    }

A: Instead of map and Promise.all it's easier to use reduce and .then to serialize all the request to one result. You can also catch any errors for failed requests so you'll get the result in the end.
//create Fail type instead of rejecting promise
function Fail(details){this.details=details;};
const isFail = item => (item&&item.constructor)===Fail
const sequentialMF = mfIds =>
  mfIds.reduce(//reduce ids to one promise
    (acc,mfId) =>
      acc.then(//acc is the one promise resolving to array of result or Fail items
        results => {
          var options = {
            //https://www.quandl.com/api/v3/datasets/AMFI/103504.json?api_key=WfUR65SA5p1PzpBysgK4
            method: 'GET',
            url: 'https://www.quandl.com/api/v3/datasets/AMFI/' + mfId + '.json',
            qs: { api_key: 'WfUR65SA5p1PzpBysgK4' },
          };
          return new Promise(//make the request as promise
            (resolve,reject)=>
              request(options, function (error, response, body) {
                if(err){
                  reject(err);//reject if there is an error
                }
                var obj = JSON.parse(body);
                resolve({//resolve if there is no error
                  "code": obj.dataset.dataset_code,
                  "name": obj.dataset.name,
                  "date": obj.dataset.end_date,
                  "nav": obj.dataset.data[0][1]
                });
              })
          )
          .then(
            result=>{//add result item to results if successfull
              results.push(result);
              return results;
            }
          )
          .catch(
            err=>{//add Fail item to results if failed
              results.push(new Fail([err,mfId]));
              return results;
            }
          )
          .then(
            results=>
              new Promise(//wait for one second to make the next request
                (resolve,reject)=>
                  setTimeout(
                    _=>resolve(results)
                    ,1000
                  )
              )
          )
        }
      )
    ,Promise.resolve([])
  )
//example of how to ue this function
sequentialMF(ids)
.then(
  results=>{
    const successes = results.filter(result=>!isFail(result));
    const failed = results.filter(isFail);
  }
)


text:
Q: Least value of n that makes the nth derivative of the function non zero at $x=0$ The function f(x) is as follows.
$f(x)=6\tan (x)(e^x-x-1)-3x^3-x^4-x^5$
If the $n^{th}$ derivative at $x=0$ is non zero then what should be the least value of n?
My obvious approach was to differentiate $f(x)$ and see a pattern which would help me estimate the same. Differentiating the tan x part by applying product rule once would give me one $sec^2x$ and one part $e^x-1$. The second part of sec x would make it 0 and $e^x-1$ would also be 0. Differentiation of sec x would give one tan x term, making it 0 in higher differentiation. $ e^x-1$ will always have one tan x part in every differentiation , so going this way inductively would make the first team of f(x) 0. The remaining terms, $-3x^3-x^4-x^5$ would be non zero at least value of n as 3. Therefore my answer is 3.
But I was surprised to see the answer when I plotted the graph in my graphing calculator and differentiated it a couple of times to see the slope go non zero at $x=0$ at $5^{th}$ derivative, making the answer $n=6$.
What is wrong in my reasoning? Why isn't the answer 3?

A: Use Taylor series for $e^x$ and $\tan x$. It becomes
\begin{align*}&6(x+x^3/3+o(x^3))(x^2/2+x^3/6+x^4/24+o(x^4))-3x^3-x^4-x^5\\&=3x^3+x^4+x^5/4+x^5+o(x^5)-3x^3-x^4-x^5=x^5/4+o(x^5)\end{align*}
So the derivatives up to the 4th are $0$ and the 5th is $5!/4=5\cdot3\cdot2=30$.


text:
Q: When opening app via Asset Links the navigation stack becomes wrong I am using flutter_inappwebview 5.7.2+3 to open Chrome custom tabs on Android like this:
class EnrollBrowser extends ChromeSafariBrowser {
  @override
  void onOpened() {
    logDebug("ChromeSafari browser opened");
  }

  @override
  void onCompletedInitialLoad() {
    logDebug("ChromeSafari browser initial load completed");
  }

  @override
  void onClosed() {
    logDebug("ChromeSafari browser closed");
  }
}

Future openELoanBrowser() async {
  final theUrl = await buildUrl();

  try {
    await EnrollBrowser().open(
        url: Uri.parse(theUrl),
        options: ChromeSafariBrowserClassOptions(
            android: AndroidChromeCustomTabsOptions(
                packageName: 'com.android.chrome',
                shareState: CustomTabsShareState.SHARE_STATE_OFF,
                keepAliveEnabled: true),
            ios: IOSSafariOptions(barCollapsingEnabled: true)));
  } catch (e) {
    logError(StackTrace.current, 'Error opening browser: ${e.toString()}');
    return false;
  }
  return true;
}
When ever I navigate, I use (it is a old project):
Navigator.of(context).push()
I have a strange problem.
If I have opened the Chrome custom tab and I then put the app in the background and bring it back to foreground, everything works as I expect, the complete navigation stack is preserved and my Chrome custom tab is on top.
I have a flow where the page opened in the custom tab opens a third party app than then in return opens my app again via Asset Links.

*

*If I have "android:launchMode" set to "singleTop" or "singleTask" or "singleInstance" then my app, when opened with Asset Links, now has a very strange navigation stack. The custom tab that used to be and should be on top, now is on bottom and the rest of the navigation stack from before are now on top of my custom tab and I have to navigate back and back and back... until I get to it.

*If I have "android:launchMode" set to "standard" then I am almost there. When my app is opened with Asset Links, the whole navigation stack is preserved, but one problem remains, my default "/" route is pushed on top of the custom tab.
I have tried calling:
Navigator.of(context, rootNavigator: true).pop();
when I detect that my "/" route has been pushed on top of my custom tab, but then I get a black screen. This is strange, because if acuallt manually navigate back on the device, it works and I get back to the custom tab.
So, with option 1. I do not get any routes added, but my custom tab that was at the top of the navigation stack now is at the bottom. Can I prevent this somehow? Then option 1. would probably be best.
With option 2. the correct navigation stack i preserved, but the "/" route is pushed on top of everything, and from code I can not pop this (even though I can manually).
How can this be? Any ideas to fix this?
Best regards and thank you
Søren


text:
Q: Can I provide the username to use in a SAML request? (AD FS) When initiating a SAML authentication request (from the Service Provider), is there any way to give the Identity Provider a hint as to which username to use?  In my application I know which user it wants to authenticate (based on a unique link the user clicked in an e-mail), and I'd like that username to be prefilled in the IdP's username box.
Using SAML 2.0 with Active Directory Federation Services (AD FS) 2.1.

A: Yes, you can use the optional <saml:Subject> field in the AuthnRequest message sent from the SP to the Idp to request a specific subject from the Idp. See section 3.4.1 in the SAML2 spec.
I have no idea if ADFS respects that field though.


text: Q: Error de compatibilidad con 64 bits al publicar app en Google Play He creado una app en flutter pero subirla a google play me esta dando un error que dice que mi app debe ser compatible con dispositivos de 64 bits. A pesar que dice que debe serlo en un futuro, aun no me permite publicarla. No entiendo por que y necesito ayuda en este proceso.


text:
Q: Open Cart SEO URL for category/manufacturer OC 1.5.6
I've installed a module to filter products in categories based on manufacturer.
I'm able to reach every "search result page" at an url like:
example.com/index.php?route=product/category&path=X&manufacturer=Y

I'd like to create a SEO url like:
example.com/alias-for-category/alias-for-manufacturer

(ex. /bikes/honda or /cars/bmw)
but I can't figure out how to do it.
I've tried for testing and simplifying to convert just a single url:
product/category&path=1&manufacturer=1

so I added to url_alias a record with this query and keyword
cat1-man1

then I modified catalog/common/seo_url.php
function Index
if (isset($this->request->get['product_id'])) {
            $this->request->get['route'] = 'product/product';
        } elseif (isset($this->request->get['path'])) {
            $this->request->get['route'] = 'product/category';
        } elseif (isset($this->request->get['manufacturer_id'])) {
            $this->request->get['route'] = 'product/manufacturer/info';
        } elseif (isset($this->request->get['information_id'])) {
            $this->request->get['route'] = 'information/information';
        }
        //ADDED BELOW CODE TO ROUTE ALL URL
        else {
            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($this->request->get['_route_']) . "'");
            if ($query->num_rows) {
                $this->request->get['route'] = $query->row['query'];
            }
        }

and function rewrite
if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");

                if ($query->num_rows) {
                    $url .= '/' . $query->row['keyword'];

                    unset($data[$key]);
                }
            } elseif ($key == 'path') {
                $categories = explode('_', $value);

                foreach ($categories as $category) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");

                    if ($query->num_rows) {
                        $url .= '/' . $query->row['keyword'];
                    }
                }

                unset($data[$key]);
            }
            //ADDED CODE BELOW TO CONVERT ALL URL
            else {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($data['route']) . "'");

                    if ($query->num_rows) {
                        $url .= '/' . $query->row['keyword'];

                        unset($data[$key]);
                    }
            }

but also this simplified version doesn't work at all, page not found is shown.
What I'm doing wrong? Any tip will be really appreciated

A: First of all the custom module I've installed expects the parameter for manufacturer as "manufacturer" instead of "manufacturer_id" so a converted URL like :
example.com/index.php?route=product/category&path=X&manufacturer_id=Y

isn't handled correctly by the module.
So the answer to my question is : OC does already convert alias-cat/alias-manufacturer to a correct internal URL
On the other hand OC does not convert URL of the type
example.com/index.php?route=product/category&path=X&manufacturer_id=Y

into SEO friendly URL like:
example.com/alias-for-category/alias-for-manufacturer

in the menus or links, to do this, modify catalog/common/seo_url.php like this:
public function rewrite($link) {
    $url_info = parse_url(str_replace('&', '&', $link));

    $url = '';

    $data = array();

    parse_str($url_info['query'], $data);

    foreach ($data as $key => $value) {
        if (isset($data['route'])) {
            if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");

                if ($query->num_rows) {
                    $url .= '/' . $query->row['keyword'];

                    unset($data[$key]);
                }
            } elseif ($key == 'path') {
                $categories = explode('_', $value);

                foreach ($categories as $category) {
                    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");

                    if ($query->num_rows) {
                        $url .= '/' . $query->row['keyword'];
                    }
                }

                unset($data[$key]);
            }
            // ADD THIS CODE
            elseif ($key == 'manufacturer_id') {

                $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'manufacturer_id=" . (int)$value . "'");

                if ($query->num_rows) {
                    $url .= '/' . $query->row['keyword'];
                }

                unset($data[$key]);
            }
            // END ADDED CODE----------------
            else {
                   .....


text:
Q: implementing flask_jwt_extended with templates rendering Again fighting trying to make my first flask application, this time, (after I created every I need and all works smoothly) I'm trying to protect some endpoints with flask_jwt_extended, but I can't find how to work with them in my pages, the documentation is mostly about displaying JSON messages and some tutorials use postman while in my case I'm using HTML templates.
For example, a user sends his credentials from the login page to this endpoint :
@app.route('/login', methods=['POST'])
def UserLogin():
    data = parser.parse_args()
    current_user = UserModel.find_by_username(data['username'])
    if not current_user:
        return {'message': 'User {} doesn\'t exist'.format(data['username'])}

    if UserModel.verify_hash(data['password'], current_user.password):
        access_token = create_access_token(identity = data['username'])
        refresh_token = create_refresh_token(identity = data['username'])
        resp = jsonify({'login': True})         #I just added this line from the documentation
        set_access_cookies(resp, access_token)  # and this one
        set_refresh_cookies(resp, refresh_token) # and this one
        return redirect(url_for('results'))

    else:
        return {'message': 'Wrong credentials'}

and of course, I added the @jwt_required decorator the results endpoint:
@app.route('/result',methods = ['POST','GET'])
@jwt_required
def results():
    temp={}
    if request.method == 'POST':
        # some code to fill temp with values
    return render_template('result.html',data=temp)

So I'm getting a {
  "msg": "Missing cookie \"access_token_cookie\""
}Obviously because I'm not sending the jwt back but if send it in the return statement how can I redirect the user the page I want ?? And indeed I used app.config['JWT_TOKEN_LOCATION'] = ['cookies']

A: You may want to:
resp = make_response(redirect(url_for('results')))
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp

I don't think you need this line! --> resp = jsonify({'login': True})
Took me a while to figure it out, not sure why this part is not clear in the docs, most of the examples there just returns JSON directly

A: Also, you get same error if JWT_ACCESS_COOKIE_PATH is routed wrongly.


text:
Q: Two audio amplifiers in series (IKEA symfonisk into powered speakers) I am hacking an IKEA symfonisk into being a cheap, Sonos connected amp, but the speakers I would like to wire it into are not passive, but active.
I am just wondering if the fact that there is an amplifier in the sonos speaker, which is sending amplified signal to the amplifier in the powered speaker, will cause issues for the speaker and potentially result in damage.
Each Sonos speaker actually has two channels (high and low frequencies) so I would also like to sum those into one signal for each speaker.
Would something like the diagram below work?

A: There are a few potential problems:

*

*The output of the Sonos will be several volts. The input to your powered speaker will be < 1 V max and exceeding this will result in clipping distortion.

*Turning down the volume of the Sonos will prevent the clipping but since the volume control will precede the power amplifier the hum and noise from the Sonos amplifier stage will not be attenuated. i.e., the signal (music) to noise ratio will decrease.

Figure 1. A bridge-mode amplifier configuration. Note that neither side of the speaker is grounded. (Ignore the 160 W reference.) Image source lost in the mists of time.

*

*The Sonos might be using a bridge-mode output which means that neither end of its speaker is grounded. That means that you have a problem with the COM / GND connection between the two systems.  For more see my answer to Single-supply amplifier design without output capacitor?.

Figure out the details of the Sonos, have a look at the power amplifier chips, read the datasheets and post the details in your question.

A: Just build an attenuator.

simulate this circuit – Schematic created using CircuitLab
If the sourcing amplifier is bridge mode, use spkr OUT+ and GND, and ignore spkr OUT-
Attenuator component values are fairly non-critical, values shown are a reasonable starting point. If it's too quiet, double R1.


text:
Q: The method isDefined(char) is undefined for the type Character I'm testing to see whether an input key is a unicode character (as opposed to caps lock, insert, etc) using the Character.isDefined method in GWT.  Here is the code sample for the key event.
public void onKeyDown(KeyDownEvent event) {
    if (isBlank() && (Character.isDefined((char)event.getNativeKeyCode()) &&
    !event.isAnyModifierKeyDown())) {
        textBox.removeStyleName("stylename");
        textBox.setValue("");
        setBlank(false);
    }
}

In the "if" statement I get a runtime error "The method isDefined(char) is undefined for the type Character." There are no compiler errors, and using other static Character methods like isLetter or isDigit works fine. I also tried not casting the NativeKeyCode as a char (instead using int for the codePoint) and it still gives an error. I have found nothing on the web that even remotely explains this.  Any help would be appreciated.

A: GWT implements only part of the java standard libraries. isDefined on the Character class is one of the method that is not implemented so you can not use it in your code. You can see how the Character methods are implemented here
It also describes why isDefined isn't defined (pardon the pun ;) )


text:
Q: Amazon Lex & Dialogflow suggestion text as quick buttons for conversation Just like Suggestion( Quick button ) like in Actions on Google, do we also have any class/Function to use in Amazon Lex ?
Actions on Google : agent.add(new Suggestion(' Your text here ')); // to provide quick suggestion to the user.

A: Like Google amazon lex also have a quick suggestion,i.e response cards. Below one is the sample image and JSON object you will get from lex with response cards.
Sample JSON Object from aws-lex which will generate response cards. i.e quick suggestions
for slots.
{
  "sampleUtterances": [

  ],
  "slotType": "",
  "slotTypeVersion": "4",
  "slotConstraint": "Optional",
  "valueElicitationPrompt": {
    "messages": [
      {
        "contentType": "PlainText",
        "content": "what do you want to schedule"
      }
    ],
    "responseCard": "{\"version\":1,\"contentType\":\"application/vnd.amazonaws.card.generic\",\"genericAttachments\":[{\"buttons\":[{\"text\":\"sales\",\"value\":\"sales consultation\"}]}]}",
    "maxAttempts": 2
  },
  "priority": 11,
  "name": "appointment"
}


text:
Q: Getting unknown length of nsstring out of nsstring So I have this long string that looks like this
{
    available = yes;
    from = player1;
    imageid = 13623367787816752r;
    time = 1367787816752;
}

There will always be a different length of imageid so I'm woundering how can I get the image id value only?
Thanks

A: You could probably use an NSScanner. You could scan for "available = ", then "yes;" or "no;", etc. until you're at the imageid. Once there, scan for characters in the set of numbers and letters, but not including a semicolon. (Or whatever is appropriate for your situation.)


text:
Q: Using Arara on windows in Texstudio to generate glossaries I am trying to generate glossaries in my LaTeX document using the article class and am using TeXStudio
I used the below code but nothing gets printed
\documentclass{article}
\usepackage{titlesec}
\usepackage[utf8]{inputenc}
\usepackage[hidelinks]{hyperref}
\usepackage{glossaries}

\makeglossaries

\newglossaryentry{culdesac}{name=cul-de-sac,description={passage or street closed at one end},plural=culs-de-sac}

\newacronym{led}{LED}{light-emitting-diode}
\begin{document}
\section{This is my section}

Some text

\end{document}

I googled and found out that I would need Arara to generate and print glossaries. I installed Arara.exe under C:\Program Files\arara\
and made a new command based on below link
How to configure TexStudio editor to use glossaries package with makeglossaries and xindy or how to configure TexStudio to use arara?
But I am getting the error :
Error: Could not start the command: C:\Program Files\arara\arara.exe -v -l "my_text_file"
Can someone help me please?
I just want to print acronyms and glossaries in my article.

A: I guess you need to differentiate between a) creating glossaries and b) controlling the process from your editor. With b) I can't help as I am not using TeXstudio.
Save the following document under the name sample.tex (the name is important!)
\documentclass{article}

\usepackage[colorlinks,linkcolor=blue]{hyperref}
\usepackage[style=long,toc,acronym=true]{glossaries}

\newglossaryentry{Perl}{name=\texttt{Perl},sort=Perl,description=A scripting language}

\newacronym{svm}{SVM}{Support Vector Machine}
\newacronym{xml}{XML}{Extensible Markup Language}

\makeglossaries

\begin{document}

\gls{Perl}

\gls{svm}

\printglossaries
\end{document}

Run the sample.tex through the LaTeX compiler of your choice, I usually use pdflatex
Run the next two commands from a) the command line or b) save them in a file with the extension .bat
makeindex -s sample.ist -t sample.glg -o sample.gls sample.glo
makeindex -s sample.ist -t sample.alg -o sample.acr sample.acn

Run LaTeX again on the TeX file. You should get the following PDF:

I nevertheless strongly recommend Nicolas manual, as the above code is a few years old (I took it from my example repository) and things may have changed in the meantime. Concerning arara I have created a short description for TeXworks, it may help you as well: http://uweziegenhagen.de/?p=2928
If you are not able to open a command window and run arara.exe I would guess the path setting is somehow corrupt. In this case locate arara.exe on your computer and add the directory it is located in to the Windows path variable.


text:
Q: Regular expression for Arabic in python I wrote this code to decode any ِsubString like that "أنا مبسوطة"
the problem is that can accept "أنا  سيشسيسشي مبسوطة  "
 s=ur"أنا  سيشسيسشي مبسوطة  "
        pattern=ur"أنا"+"\s"+".*"+ur"ة"
        l=re.findall(pattern,s)
        print(pattern)
        for tweet in l:
           print(tweet)
        length=l.__len__()
        if (length>0):
           print ("true",length)
        else:
           print ("false")

I want the output be true if input  "أنا مبسوطة" else if input "أنا  سيشسيسشي مبسوطة  "  false . I am using python 2

A: You can use the following pattern instead:
pattern=ur"أنا"+"\s*"+ur"[ا-ي]*"+ur"ة"


text:
Q: JAVA: Substitute one color with another using ColorModel I need to substitute one color with white on an image. I've read about ColorModel and RGBImageFilter.substituteColorModel, but I don't understand very well.
The color I want to substitute is:
R: 113
G: 75
B: 96
And of course, white is 255,255,255.
If you can give a direct solution will be great, but if not, a bit of explanation on how to do it also will be great. I don't want just the solution, I want to understand the hows and whys.
Thank u so much.

A: At my company we have to do this sort of switching frequently on embedded displays.  We use indexed bitmaps to accomplish what you are talking about.  The basic idea is to switch out the palette for a given index to get different looks and feels.
The idea with an indexed bitmap is that you have say 256 colors at your disposal in the pallete.  You can assign any RGB values that you want to each slot in the palette.  The image itself is just a list of indexes into the palette(single byte per pixel).  This is really cool on CPU and storage constrained platform(where you can't deal with decompressing images and you can't spare the space for full color bitmaps). You can make alternate palettes (greens, yellows, reds, etc).  You just switch out the palette and the graphics look completely different.  We use this to make really fine gradients on widgets that can switch color without having to carry around each state of a button.
To solve your specific problem with indexed bitmaps, you would just switch palettes and make sure that in one palette the index was (113,75,96) and in the second palette that same index held (255,255,255).
IndexColorModel is a good place to start in AWT.
Good luck!


text:
Q: VBA Excel using variables as cell reference I have the following VBA Code:
Public maxnumrows As Integer

Sub count_num_rows()
    maxnumrows = Sheets("Monetary All").UsedRange.Rows.Count
End Sub

Sub calc_external_sales()
    Sheets("Monetary All").[C5].FormulaLocal = "=SUMMEWENNS(Rawdata!K2:K3446;Rawdata!I2:I3446;""bezahlt"")"
End Sub

I would like the cell references in the calc_external_sales() to use the public variable in the range.
Example:
Rawdata!K2:K"maxnumrows"
How do I have to change the syntax?

A: This is how you can use a variable within a string
Sheets("Monetary All").[C5].FormulaLocal = _
"=SUMMEWENNS(Rawdata!K2:K" & maxnumrows & ";" & _
            "Rawdata!I2:I" & maxnumrows & ";""bezahlt"")"


text:
Q: Why doesn't passport save the user object after deserialization? Basically, I type in localhost:5000/auth/google on the browser address bar, it directs me to the log-in with google page. When I click on my profile it redirects me to the Cannot GET /auth/google/callback, which is fine so far.
However, when I go to the router that is supposed to display req.user object I get an undefined object (empty page). At localhost:5000/api/user.
What am I doing wrong in the Passport section of my code?
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('./config/keys');
const mongoose = require('mongoose');
require('./models/user'); // must be executed before User = mongoose.model('user')
const User = mongoose.model('users');
const cookie = require('cookie-session');

mongoose.Promise = global.Promise;
mongoose.connect(keys.mongoURI);

const app = express();

app.use(
    cookie({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey],
    })
);

// set passport middleware
app.use(passport.initialize());
app.use(passport.session());

/////////////////////// PASSPORT /////////////////////////////////

passport.serializeUser((user, done) => {
    console.log("seralized")
    done(null, user.id);
});

passport.deserializeUser((id, done) => {
    console.log("deserialized")
    User.findById(id).then(user => {
        done(null, user);
    });
});

passport.use(new GoogleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleClientSecret,
    callbackURL: '/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
    User.findOne({ googleId: profile.id }).then(
        existingUser => {
            existingUser ? done(null, existingUser) :
                new User({ googleId: profile.id }).save().then(
                    user => done(null, user)
                )
        }
    )
}));

/////////////////////// END PASSPORT /////////////////////////////////

///////////////////////////////ROUTING ///////////////////////////////

app.get('/', (req, res) => {
    res.send('<p> some html </p>');
});

app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile', 'email']
}));

app.get('/auth/google/callback', passport.authenticate('google'));

app.get('/api/user', (req, res) => {
    res.send(req.user);
});

app.listen(5000);

A: It turns out that the problem was that I was using the ternary operator under passport.use(new GoogleStrategy(...)).
Instead of,
passport.use(new GoogleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleClientSecret,
    callbackURL: '/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
    User.findOne({ googleId: profile.id }).then(
        existingUser => {
            existingUser ? done(null, existingUser) :
                new User({ googleId: profile.id }).save().then(
                    user => done(null, user)
                )
        }
    )
}));

I should have wrote,
passport.use(new GoogleStrategy({
    clientID: keys.googleClientID,
    clientSecret: keys.googleClientSecret,
    callbackURL: '/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
    User.findOne({ googleId: profile.id }).then(
        existingUser => {
            if(existingUser){
                done(null, existingUser)
            } else{
                new User({ googleId: profile.id }).save().then(
                    user => done(null, user)
                )
            }
        }
    )
}));

Does anyone happen to know why this is the case?


text:
Q: What is the intuitive reason behind doing rotations in Factor Analysis/PCA & how to select appropriate rotation? My Questions

*

*What is the intuitive reason behind doing rotations of factors in factor analysis (or components in PCA)?
My understanding is, if variables are almost equally loaded in the top components (or factors) then obviously it is difficult to differentiate the components. So in this case one could use rotation to get better differentiation of components. Is this correct?

*What are the consequence of doing rotations? What things does this affect?

*How to select appropriate rotation?
There are orthogonal rotations & oblique rotations. How to choose between these          and what are the implications of this choice?
Please explain intuitively with least mathematical equations. Few of the spread out answers were math heavy but I am looking more for intuitive reasons and rules of thumb.

A: *

*Reason for rotation. Rotations are done for the sake of interpretation of the extracted factors in factor analysis (or components in PCA, if you venture to use PCA as a factor analytic technique). You are right when you describe your understanding. Rotation is done in the pursuit of some structure of the loading matrix, which may be called simple structure. It is when different factors tend to load different variables $^1$. [I believe it is more correct to say that "a factor loads a variable" than "a variable loads a factor", because it is the factor that is "in" or "behind" variables to make them correlate, but you may say as you like.] In a sense, typical simple structure is where "clusters" of correlated variables show up. You then interpret a factor as the meaning which lies on the intersection of the meaning of the variables which are loaded enough by the factor; thus, to receive different meaning, factors should load variables differentially. A rule of thumb is that a factor should load decently at least 3 variables.

*Consequences. Rotation does not change the position of variables relative to each other in the space of the factors, i.e. correlations between variables are being preserved. What are changed are the coordinates of the variable vectors' end-points onto the factor axes - the loadings (please search this site for "loading plot" and "biplot", for more)$^2$. After an orthogonal rotation of the loading matrix, factor variances get changed, but factors remain uncorrelated and variable communalities are preserved.
In an oblique rotation factors are allowed to lose their uncorrelatedness if that will produce a clearer "simple structure". However, interpretation of correlated factors is a more difficult art because you have to derive meaning from one factor so that it does not contaminate the meaning of another one that it correlates with. That implies that you have to interpret factors, let us say, in parallel, and not one by one. Oblique rotation leaves you with two matrices of loadings instead of one: pattern matrix $\bf P$ and structure matrix $\bf S$. ($\bf S=PC$, where $\bf C$ is the matrix of correlations between the factors; $\bf C=Q'Q$, where $\bf Q$ is the matrix of oblique rotation: $\bf S=AQ$, where $\bf A$ was the loading matrix prior any rotation.) The pattern matrix is the matrix of regressional weights by which factors predict variables, while the structure matrix is the correlations (or covariances) between factors and variables. Most of the time we interpret factors by pattern loadings because these coefficients represent the unique individual investment of the factor in a variable. Oblique rotation preserves variable communalities, but the communalities are no longer equal to the row sums of squares in $\bf P$ or in $\bf S$. Moreover, because factors correlate, their variances partly superimpose$^3$.

Both orthogonal and oblique rotations, of course, affect factor/component scores which you might want to compute (please search "factor scores" on this site). Rotation, in effect, gives you other factors than those factors you had just after the extraction$^4$. They inherit their predictive power (for the variables and their correlations) but they will get different substantial meaning from you. After rotation, you may not say "this factor is more important than that one" because they were rotated vis-a-vis each other (to be honest, in FA, unlike PCA, you may hardly say it even after the extraction because factors are modelled as already "important").

*Choice. There are many forms of orthogonal and oblique rotations. Why? First, because the concept of "simple structure" is not univocal and can be formulated somewhat differently. For example, varimax - the most popular orthogonal method - tries to maximize variance among the squared values of loadings of each factor; the sometimes used orthogonal method quartimax minimizes the number of factors needed to explain a variable, and often produces the so called "general factor". Second, different rotations aim at different side objectives apart from simple structure. I won't go into the details of these complex topics, but you might want to read about them for yourself.

Should one prefer orthogonal or oblique rotation? Well, orthogonal factors are easier to interpret and the whole factor model is statistically simpler (orthogonal predictors, of course). But there you impose orthogonality on the latent traits you want to discover; are you sure they should be uncorrelated in the field you study? What if they are not? Oblique rotation methods$^5$ (albeit each having their own inclinations) allow, but don't force, factors to correlate, and are thus less restrictive. If oblique rotation shows that factors are only weakly correlated, you may be confident that "in reality" it is so, and then you may turn to orthogonal rotation with good conscience. If factors, on the other hand, are very much correlated, it looks unnatural (for conceptually distinct latent traits, especially if you are developing an inventory in psychology or such, - recall that a factor is itself a univariate trait, not a batch of phenomena), and you might want to extract less factors, or alternatively to use the oblique results as the batch source to extract the so-called second-order factors.

$^1$ Thurstone brought forward five ideal conditions of simple structure. The three most important are: (1) each variable must have at least one near-zero loading; (2) each factor must have near-zero loadings for at least m variables (m is the number of factors); (3) for each pair of factors, there are at least m variables with loadings near zero for one of them, and far enough from zero for the other. Consequently, for each pair of factors their loading plot should ideally look something like:

This is for purely exploratory FA, while if you are doing and redoing FA to develop a questionnaire, you eventually will want to drop all points except blue ones, provided you have only two factors. If there are more than two factors, you will want the red points to become blue for some of the other factors' loading plots.

$^2$

$^3$ The variance of a factor (or component) is the sum of its squared structure loadings $\bf S$, since they are covariances/correlations between variables and (unit-scaled) factors. After oblique rotation, factors can get correlated, and so their variances intersect. Consequently, the sum of their variances, SS in $\bf S$, exceeds the overall communality explained, SS in $\bf A$. If you want to reckon after factor i only the unique "clean" portion of its variance, multiply the variance by $1-R_i^2$ of the factor's dependence on the other factors, the quantity known as anti-image. It is the reciprocal of the i-th diagonal element of $\bf C^{-1}$. The sum of the "clean" portions of the variances will be less than the overall communality explained.

$^4$ You may not say "the 1st factor/component changed in rotation in this or that way" because the 1st factor/component in the rotated loading matrix is a different factor/component than the 1st one in the unrotated loading matrix. The same ordinal number ("1st") is misleading.

$^5$ Two most important oblique methods are promax and oblimin. Promax is the oblique enhancement of varimax: the varimax-based structure is then loosed in order to meet "simple structure" to a greater degree. It is often used in confirmatory FA. Oblimin is very flexible due to its parameter gamma which, when set to 0, makes oblimin the quartimin method yielding most oblique solutions. A gamma of 1 yields the least oblique solutions, the covarimin, which is yet another varimax-based oblique method alternative to promax. All oblique methods can be direct (=primary) and indirect (=secondary) versions - see the literature. All rotations, both orthogonal and oblique, can be done with Kaiser normalization (usually) or without it. The normalization makes all variables equally important at the rotation.

Some threads for further reading:
Can there be reason not to rotate factors at all? (Check this too.)
Which matrix to interpret after oblique rotation - pattern or structure?
What do the names of factor rotation techniques (varimax, etc.) mean? (A detailed answer with formulae and peseudocode for the orthogonal factor rotation methods)
Is PCA with components rotated still PCA or is a factor analysis?


text:
Q: Display the saved file on the webbrowser I have written a code to capture the packets on the interface using libpcap library  and saved in the file i need to display it on the web browser .can any one suggest how to display the saved file on the browser .

A: Why not use Wireshark instead for your purpose. Why the browser? I dont think your browser can interpret pcap files.
However, there does exist a paid service called CloudShark which basically allows you to upload your pcap files to their server and perform analysis using your browser as the Interface.
More at:
https://appliance.cloudshark.org/


text:
Q: Python socket accept() not working when called from a thread The connection is happening during the first execution of method in the following code , but from the second time execution of the function within the thread , the accept() function is not accepting any functoin , it just stays at the prompt and does nothing even if i connect from other local devices . Any help would be really helpfull. Here is the code. I am really new to threading. So please correct my mistakes and give full explaination for any errors in my code.
def serverwaiter():
    myip = "192.168.1.2";
    port = 6027;
    s = socket.socket();
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1);
    s.bind((myip, 6027));
    s.listen(10);
    print("My ip  :- {}".format(myip)) ;
    cobj , addr = s.accept() ;
    mythread = threading.Thread(target = serverwaiter, name = "TCP connection waiter {}".format(threading.active_count()-1))
    threads.append((cobj,addr)) ;
    mythread.start() ;
    print("Connected to {}".format(addr[0])) ;
    data = cobj.recv(1024) ;
    print("Host {} sent data = {}".format(addr, data));

    while(len(data)!=0):
        print("Waiting for Data from {}".format(addr[0])) ;
        data = cobj.recv(1024) ;
        data = data.decode() ;
        print("Host {} sent data = {}".format(addr ,data)) ;

serverwaiter() ;

A: You should run the thread's target within a while-true loop. I also suggest you organize your code for better understanding.
def mythread():
        while True:
               accept()

Remember to always pass the variables as arguments so nothing is left behind

A: Spin off threads just for servicing the client.  Now you are starting another server each time a client connects.  Try this:
import socket
import threading

def serverwaiter():
    port = 6027
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind(('',6027))
    s.listen(10)
    while True:
        cobj,addr = s.accept()
        mythread = threading.Thread(target=client,name='TCP client {}'.format(threading.active_count()-1),args=(cobj,addr))
        mythread.daemon = True # So client threads die on main thread exit.
        mythread.start()

def client(cobj,addr):
    print('Connected to',addr)
    while True:
        data = cobj.recv(1024)
        if not data: break
        print('Host {} sent data = {}'.format(addr,data.decode()))
    cobj.close()

serverwaiter()


text:
Q: Error in vusial studio (E0869, could not set locale ".1252") info:
Visual studio 2019
Windows 10(russian locale)
project - any c++ project (projects on other languages works perfectly)
after creating any c++ project visual studio, wrote E0869 error on first string
I could find
https://developercommunity.visualstudio.com/content/problem/405876/e0869-could-not-set-locale-1252.html
They offer a few steps.
On step 'wrote "chcp 1252"' i got "invalid code page". (I guess it may be related with problem in visual studio)
Searching in search engines (Google\yandex) haven't results.
Did anybody meet and solve this problem?

A: After two hours of searching the solution came by accident:
compiler additional options "--locale=US"


text:
Q: illegal string offset(codeigniter 3) Hi been trying to retrieve records from my database, but I keep getting this error "Severity: Warning Message: Illegal string offset " in several fields.
controller
public function get_discount(){
    if($this->session->has_userdata('logged_in')){
        // redirect(base_url());
    }
    else{
        $output = array();
        $output['error']="failed";
        $coupon_code=$this->input->post('coupon_code');
        $product_price=$this->input->post('product_price');

        $condition=array('coupon_code'=>$coupon_code,
                         'product_price'=>$product_price
        );
        $count['discount']= $this->Form_model->get_discount('coupon',$condition);

        foreach($count['discount'] as $row)
        {
            echo json_encode($count['discount']);

            if($count > 0){
                $discount = $row['discount'] / 100;
                $total = $discount * $product_price;
                $array['discount'] = $row['discount'];
                $array['product_price'] = $product_price - $total;

                $output['success']="success";
                echo json_encode($output);
            }
        }
    }
}

this is my model
public function get_discount($data){
    $sql = "SELECT * FROM coupon WHERE (coupon_code = ? ) AND  status= 'valid' ";
    $query = $this->db->query($sql, array($data['coupon_code']));
    $result = $query->row() ;
    if($query->num_rows()==1){
        return $result;
    }
}

This is my view
<form action="/get_discount" method="post">

*Optional

    Coupon Code
    <input class="form-control" name="coupon_code" type="text" id="coupon_code" />
    <input type="hidden" value="<?php echo $product->product_price?>" id="price" />

    <button class="btn btn-primary" id="activate">Activate Code</button>

</form>

  Total Price
  <input class="form-control" type="number" value="<?php echo $product->product_price?>" id="total" readonly="readonly" lang="en-150" />

A: You're calling get_data() with too many arguments. It only $condition should be the only argument.
        $count['discount']= $this->Form_model->get_discount($condition);

The error is because $data is the first parameter, which you're passing the string 'coupon' to in your call.


text:
Q: Uber API - Making advance booking I can see the advance booking button in Uber Rider app. Is there an API for advance booking?
I am building a travel booking app and would like to book rides like months before the actual travel dates of the customers.
Is it in the API?

A: Uber API's does not support booking scheduled rides upfront right now - so you can't book future trips. You can record scheduled rides via your code somewhere - and when is the time for the ride - you trigger your ride request.


text:
Q: Android Refresh Listview issue. I am having an issue with a listview refresh, I have a refresh function that works on load and when I click a button tied to it. What it will not do is refresh after I add info to the SQLite database and call the refresh function.
    //Add item to order Table.
    public void addItemToOrder()
{
    itemNumberValue = qoItemNumber.getText().toString();
    orderQtyValue = qoOrderQty.getText().toString();
    itemDescValue = qoItemDesc.getText().toString();

    Intent searchItem = new Intent(getApplicationContext(),inputOrder.class);

    searchItem.putExtra("itemnumb", itemNumberValue);
    searchItem.putExtra("orderqty", orderQtyValue);
    searchItem.putExtra("qoitemdesc", itemDescValue);

    startActivity(searchItem);
    fillData();

}

    //Load item table to listview
    public void fillData() {
        // Get all of the rows from the database and create the item list
        mNotesCursor = mDbHelper.fetchAllOrders();
        startManagingCursor(mNotesCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{HDWDBHelper.KEY_ITEMNUM, HDWDBHelper.KEY_DESC, HDWDBHelper.KEY_QTY};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        //int[] to = new int[]{R.id.text1};
        int[] to = new int[]{R.id.tvItemNum, R.id.tvItemDesc, R.id.tvQty};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter notes =
                new SimpleCursorAdapter(this, R.layout.itemlist, mNotesCursor, from, to);

        notes.notifyDataSetChanged();
        setListAdapter(notes);
        notes.notifyDataSetChanged();
        Log.v("fillData", "In fillData");
    }

When I call fillData() at onCreate() or on button click, it works but when I call it in the addItemToOrder() function, nothing happens. The listview still shows previous items listed until I click the refresh button then it shows the new item added.


text:
Q: IOS - UIDateView to UITextField I have implemented a UIDatePicker IOS7 View into a static tableview with the help of  - iOS 7 - How to display a date picker in place in a table view?
All works great- my only issue now is how to display the result in my UITextField once a date has been selected?  Sounds like it should be a simple thing - but as its a static field I'm not sure how to access the date property once a selection is made or which method to apply the code to!?

A: A good pattern to follow would be sending the date selected in the UIDatePicker back to the UIViewController that is handling the UITableView via delegation. This can be done by assigning an IBAction to the valueChanged: control event of the date picker.
Once you have obtained the NSDate, you can transform it into text with the format of your choosing using an NSDateFormatter


text:
Q: Error: [$injector:nomod] Module 'ui.bootstrap' is not available! while Karma run in webstorm Hi I'm getting the following error in webstorm while running karma test run
Error: [$injector:nomod] Module 'ui.bootstrap', 'ui.unique' is not available!
You either misspelled the module name or forgot to load it.
If registering a module ensure that you specify the dependencies as the second argument.

i looked in the internet and they said to check dependency file ui.bootstrap might be missed like that.
but the application works fine
and while testing only it shows this error
in my karma.conf.js
files: [
            //angular files

            'app/js/vendor/angular/ui.bootstrap.js',
            'app/js/vendor/angular/ui.bootstrap-0.10.0.js',

            'app/js/vendor/angular/angular.js',
            'app/js/vendor/angular/angular-mocks-0.10.6.js',

            'app/js/app.js',
            'test/**/*Spec.js'
        ],

in my Module declartion
var myApp = angular.module('myApp', ['ui.bootstrap']);

Could you please help ??

A: ui.unique is a module from angular-ui-utils. That has to be included in karma conf and injected to the app as well, if being used.
var myApp = angular.module('myApp', ['ui.bootstrap', 'ui.utils']);

or you can specifically inject ui.unique instead of injecting ui.utils, if only unique module is used.


text:
Q: SQL Server Replication : Removing broken subscriptions at the publisher We have multiple subscriptions (merge pull) at our subscriber for only 1 "real" subscription. I think we actually broke it like this by adding and removing the subscription from the subscriber side, and then trying to replicate it... multiple times.
Now the problem is not that the replication does not work, I'm pretty confident that I the answer for that. The problem is that I can't drop/delete the broken subscriptions at the subscriber anymore. It just does not work.
When trying to run sp_dropmergepullsubscription at the publisher, it tells me "No subscription is on this publication article".
When trying to run sp_dropsubscription at the publisher, it tells me "This database is not enabled for subscription"
Yes I've checked that I was running all these scripts on the correct database and all that.
Has anybody had a problem like this before ?
Do I need to re-do the publication and the subscription ?
Thanks guys and gals ! :)

A: Try the following on the publisher:
EXEC sp_dropmergesubscription
  @publication = '<publicationName>',
  @subscriber = '<subscriberName>',
  @subscriber_db = '<dbName>;
GO

delete sysmergesubscriptions where subscriber_server = '<subscriberName>'

use distribution
go
delete msmerge_Agents where subscriber_name = '<subscriberName>'

delete msmerge_subscriptions where subscriber = '<subscriberName>'

...then try setting the pull subscription back up


text:
Q: How to test role-based API permissions with Cypress I am trying to use Cypress to test user permissions for a REST API. Authorisation is done via a JWT token which is generated by calling another API endpoint. A 200 and a 401 response is returned for authorised and unauthorised users respectively for the list users endpoint.
Let's say the SUT has 8 roles: Role1, Role2...etc
Role1 and Role2 should be allowed to access the list users endpoint.
As shown below, I currently have it set up so that it will correctly test that Role1 gets the correct response, however, I'm not sure how I should do it for multiple roles so that I can test that Role1 and Role2 get a 200 whilst Role3 etc receive a 401 response
I guess I want to wrap the entire suite of tests (i.e all endpoints, not just list users) in a "for each role in roles" loop but can't see how you can do that and not sure it would be the best way.
Any help would be appreciated
describe('Users - list', () => {
beforeEach(() => {
    cy.request({
        url:'users',
        headers: {
        'Authorization': 'JWT Role1Token'
      }}).as('response')
})

it('Correct response code is returned', () => {
    cy.get('@response')
    .its('status')
    .should('equal', 200)
})

})


text:
Q: Can I call bind() and then connect() on same socket descriptor? Just a curious question about networking socket programming in a Windows Application with C/C++:
How can I tell the connect() function to use a particular source IP and source port values?

*

*After a socket is created, application calls connect() to remote IP and port by using the sockaddr structure.

*the connect() function internally selects the source IP and port for the connection.
Rather than the system deciding the source IP and/or port for the connect(), let that be the application's responsibility to decide which source IP and/or port to bind to.

A: bind() requests port that is not in use so it can claim it and become a server, while connect() wants a port that is already in use, so it can connect to it and talk to the server.
As user stark said, you need to call bind if you want to specify which interface/port combination to use, although if you want next call to bind it to a random available port number, you can opt out from bind() call because client doesn't necessarily has to have a fixed port number.
It is possible to ask the kernel to select a specific port before calling connect(), but if I may ask - why you wouldn't want to kernel to allocate source ports, as far as I know it's not best practice.

A:
How can I tell the connect() function to use a particular source IP and source port values?

Use the socket library's bind() function for that.  Yes, you can call bind() before connect() for an outgoing socket.  That is a perfectly legitimate operation for both UDP and TCP sockets.

A: Yes, you can.  Indeed there's a reason to do that:  In case your routing policy makes your connection to be established from an IP address which is not the one you want to use, you can force in a multihomed/routing host a specific IP address as source by means of bind(2) system call.  Another use is to specify a fixed source port for the connection, but this is not as usual as the previous case.
But beware: you can select only one of the already configured IP addresses you have, not any address you can imagine.


text:
Q: How to make "Enter" key in a textarea submit a form I have a chat that uses textarea instead of text for obvious reasons. This is why each time members hit ENTER they get a new line instead of sending the message.
I would like to change this, so every time they hit ENTER =the message to be submitted and then the cursor to return on textarea for their next message typing.
I've tried different codes found on this site, most didnt work and those who seemed to do something  were just refreshing the page and i got a blank page.
My code:
<form name="message" action="">
    <textarea name="usermsg" autocomplete="off" type="text" id="usermsg" rows="4" cols="30" style="width: 450px; margin-left: 25px;">
    </textarea>

<input name="submitmsg" type="submit"  id="submitmsg" value="Send" />

</form>

Thank you very much for your time.

A: Try this (note that pressing Enter submits, and Shift+Enter adds a new line).
$("#textareaId").keypress(function (e) {
    if(e.which === 13 && !e.shiftKey) {
        e.preventDefault();

        $(this).closest("form").submit();
    }
});

A: Well, supposing you were using jquery it would be a simple listener on your input field:
In your footer before :

In your html head add this:

but if js or jquery is out of the question then perhaps update your question to specifically exclude it.

A: Vanilla JavaScript solution
function submitOnEnter(event) {
    if (event.which === 13) {
        if (!event.repeat) {
            const newEvent = new Event("submit", {cancelable: true});
            event.target.form.dispatchEvent(newEvent);
        }

        event.preventDefault(); // Prevents the addition of a new line in the text field
    }
}

document.getElementById("usermsg").addEventListener("keydown", submitOnEnter);

If you would prefer to add a new line when Shift is held all you need to do is change line 2 to:
if (event.which === 13 && !event.shiftKey) {

To clear the textarea just add this after the dispatchEvent line:
event.target.value = "";

To use this with Internet Explorer 11 change line 4 and 5 to:
var newEvent = document.createEvent("Event");
newEvent.initEvent("submit", false, true);
event.target.form.dispatchEvent(newEvent);

But wait? Why not use event.target.form.submit();?

When you invoke the submit method of the form the event listeners will not be called.

function submitOnEnter(event) {
    if (event.which === 13) {
        if (!event.repeat) {
            const newEvent = new Event("submit", {cancelable: true});
            event.target.form.dispatchEvent(newEvent);
        }

        event.preventDefault(); // Prevents the addition of a new line in the text field
    }
}

document.getElementById("usermsg").addEventListener("keydown", submitOnEnter);

document.getElementById("form").addEventListener("submit", (event) => {
    event.preventDefault();
    console.log("form submitted");
});
<form id="form">
    <textarea id="usermsg"></textarea>
    <button type="Submit">Submit</button>
</form>

A: I have created a jsfiddle with an example on how to do it with jQuery and the keypressfunction and which property: http://jsfiddle.net/GcdUE/
Not sure exactly what you are asking for more than this, so please specify your question further if possible.
$(function() {
    $("#usermsg").keypress(function (e) {
        if(e.which == 13) {
            //submit form via ajax, this is not JS but server side scripting so not showing here
            $("#chatbox").append($(this).val() + "
");
            $(this).val("");
            e.preventDefault();
        }
    });
});

A: Use <input type=text> instead of <textarea>. Then you have much better chances. In textarea, hitting Enter is supposed to mean a line break in text, not submission of text.

A: function KP()
{
var x = event.keyCode;
   if(x==13)
        {
            // alert (x);
            document.message.submit();
        }
}

php
echo '<textarea  name="usrMsg" id="usrMsg" OnKeyPress="KP();">'txt'</textarea>';


text:
Q: Second page of pagination displays all results I have spent days on this and can't make any progress, any help will be really appreciated. I have a page that processes a query from a form and displays the results. The first page of results works as expected showing number of rows found and displaying some of the results but when I click to the next page I just get all the results in the database, like the query has been forgotten.
<?php include_once "db_conx.php";

if (isset($_GET['submit']) && $_GET['submit'] == 'submit_1'){

//Build Search Query from form data

$whereClauses = array();
  if (! empty($_GET['location'])) $whereClauses[] ="(location ='".mysqli_real_escape_string($db_conx,$_GET['location'])."' OR location_2 ='".mysqli_real_escape_string($db_conx,$_GET['location'])."' OR location_3 ='".mysqli_real_escape_string($db_conx,$_GET['location'])."' OR location_4 ='".mysqli_real_escape_string($db_conx,$_GET['location'])."')";
  if (! empty($_GET['jobtitle'])) $whereClauses[] ="(jobtitle LIKE '%".mysqli_real_escape_string($db_conx,$_GET['jobtitle'])."')";
if (!empty($_GET['start']))
    if ($_GET['start'] == "today") {
        $whereClauses[] = "START = CURDATE()";
    }
else if ($_GET['start'] == "tomorrow") {
        $whereClauses[] = "START = DATE_ADD( CURDATE( ) , INTERVAL( 9 - IF( DAYOFWEEK( CURDATE( ) ) =1, 8, DAYOFWEEK( CURDATE( ) ) ) ) DAY )";
    }
else if ($_GET['start'] == "next_week") {
        $whereClauses[] = "START = DATE_ADD( CURDATE( ) , INTERVAL( 9 - IF( DAYOFWEEK( CURDATE( ) ) =1, 8, DAYOFWEEK( CURDATE( ) ) ) )
DAY )";
    }
else if ($_GET['start'] == "this_month") {
        $whereClauses[] = "START BETWEEN DATE_SUB( CURDATE( ) , INTERVAL( DAY( CURDATE( ) ) -1 ) DAY ) AND LAST_DAY( NOW( ) )";
    }
    else if ($_GET['start'] == "next_month") {
        $whereClauses[] = "start BETWEEN DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)))-1 DAY) AND LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH))";
    }
else if ($_GET['start'] == "in_future") {
        $whereClauses[] = "START > CURDATE()";
    }

  $where = '';

if (count($whereClauses) > 0) {
$where = ' WHERE '.implode(' AND ',$whereClauses);
}

// The first query to count the number of rows
$sql = "SELECT COUNT(id) FROM users " .$where."";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
// Here we have the total row count
$rows = $row[0];

// The number of results to display per page
$page_rows = 5;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
    $last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
    $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// Make sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
    $pagenum = 1;
} else if ($pagenum > $last) {
    $pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;

// The Query again to get just one page worth of rows by applying $limit

$sql="SELECT * FROM users " .$where." ORDER BY notescheck DESC $limit";

$query = mysqli_query($db_conx, $sql);
// This shows the user what page they are on, and the total number of pages
$textline1 = "Results ($rows)";
$textline2 = "Page $pagenum of $last";
// Establish the $paginationCtrls variable
$paginationCtrls = '';

// If there is more than 1 page worth of results
if($last != 1){
    /* First we check if we are on page one. If we are then we don't need a link to
       the previous page or the first page so we do nothing. If we aren't then we
       generate links to the first page, and to the previous page. */
    if ($pagenum > 1) {

        $previous = $pagenum - 1;
        $paginationCtrls .= '

Previous

     ';// Render clickable number links that should appear on the left of the target page number
        for($i = $pagenum-4; $i < $pagenum; $i++){
            if($i > 0){
                $paginationCtrls .= '

'.$i.'

   ';
            }
        }
    }
    // Render the target page number, but without it being a link

    // Render clickable number links that should appear on the right of the target page number
    for($i = $pagenum+1; $i <= $last; $i++){
        $paginationCtrls .= '

'.$i.'

   ';
        if($i >= $pagenum+4){
            break;
        }
    }
    // This does the same as above, only checking if we are on the last page, and then generating the "Next"
    if ($pagenum != $last) {
        $next = $pagenum + 1;
        $paginationCtrls .= '

Next

     ';
    }
}
}
$list = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
    $id = $row["id"];
    $firstname = $row["firstname"];
    $lastname = $row["lastname"];
$list .= '
'.$firstname.' '.$lastname.' Profile - Click the link to view user

';
}
// Close your database connection
mysqli_close($db_conx);
?>

A: $_SERVER['PHP_SELF'] refers to the script, but not the full url. This means that you loose all the information you previously had in your query string. Actually, the only reason this works, is because your script name is the same as the url. PHP_SELF is actually for internal use (including files) and not intended for building urls at all.
You can solve this by storing the values in cookies, or by using the full url (including query string) when you build the links for previous and next pages.
When building the url, you can use $_SERVER['REQUEST_URI']. This gives you the relative url to your script, similar to $_SERVER['PHP_SELF'], but actually giving the document part of the request url.
Additionally, you can use $_SERVER['QUERY_STRING'] to get the entire query string of the request, or you can use $_GET[] to get each of the query string values and only copy those that you want to use in the url.
To simply copy everything that is in the url, and just change the page number, you can do this:
$pagenum = 5; // example.

$urlParams = $_GET; // Copy the entiry query string.

$urlParams['pn'] = $pagenum - 1; // Replace the page number.
$previous = http_build_query($urlParams); // Build a new query string.

$urlParams['pn'] = $pagenum + 1;
$next = http_build_query($urlParams);

And then you can build a link like this:
'Previous page
 Next page'


text:
Q: Quadratic congruence with linear term I'm trying to determine whether the congruence $x^2+x-1\equiv0\pmod{61}$ has a solution.
I know how to do this without the linear term, for instance, $x^2-5\equiv0\pmod{61}$.
I can solve it just by using the properties of the Legendre symbol.
But what do I do if there's a linear term?

A: We complete the square!
$$x^2+x-1 \equiv 0 \pmod{61} \iff 4x^2+4x-4 \equiv 0 \pmod{61} \iff (2x+1)^2 \equiv 5 \pmod{61}$$
Therefore, it suffices to find $$\left( \frac{5}{61} \right)$$ which can be done easily by the law of quadratic reciprocity.


text:
Q: Optimizing Pygame sprite images? I am developing a game in pygame and everything is working. But I thought of something and wasn't sure if it mattered.
My game makes use of projectiles using the sprite class and currently code looks like this
class Enemy_Attack_Sprite(pygame.sprite.Sprite):
    def __init__(self, image, w=200, h=20):
        pygame.sprite.Sprite.__init__(self)
        image_load = pygame.image.load(image)
        self.image = pygame.transform.smoothscale(image_load,(w,h))

With 'Image' being the file name as string. So I would call
projectile = Enemy_Attack_Sprite('projectile.png')

Does that mean every single time a shot is fired the programe is loading the .png again? would it be more efficient or make a significant difference to do it like this:
projectile_image = pygame.image.load('projectile.png')
class Enemy_Attack_Sprite(pygame.sprite.Sprite):
    def __init__(self, image, w=200, h=20):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.transform.smoothscale(image,(w,h))

and then call it with:
projectile = Enemy_Attack_Sprite(projectile_image)

Everything is working okay now, But I'm wondering if re-writing the images and sprite functions in my game would make a difference in performance?


text:
Q: HTML5 Canvas Layer Display I'm coding a simple image manipulation/drawing utility using HTML5 canvas. It currently works fine with a single canvas layer.
I'm trying to add a feature of a "preview", such that instead of a cursor displaying when it is moved over the canvas, the effect of clicking the mouse at that position is displayed. For example, if you have an image loaded in the main canvas and the selected globalCompositeOperation is saturation, you can see a preview of what the image would look like by moving the mouse around to different parts. The preview is the size of the current tool, so if it's a circle tool, radius 5, you see the effect rendered for whatever that circle is covering. If you don't click down, you only see the preview. If you click down, the effect is applied to the canvas in the area that was shown in the preview.
I have an event listener on my main canvas for mousemove, mouseup, and mousedown. Here's my current code (JS and CSS). There are two canvas tags (not shown in code below). One is my main canvas with context ctx, and the other is the mouse preview canvas, with context mouseCtx. CS refers to a global "Canvas State" object.
The code functions properly now, except that the mouse preview appears behind any elements on the main canvas (which I'd expect given the lower z-index). When I click to place an element, it pops in front of all the content. However, if I give the mouseover a higher Z-index, nothing displays on the main canvas at all.
Am I missing something silly, or is my strategy for implementing this feature way off? Thanks much for any hints toward a right direction.

canvas.addEventListener('mousemove', mouseTrack);
canvas.addEventListener('mousedown', mouseTrack);
canvas.addEventListener('mouseup', mouseTrack);

function mouseTrack(e) {
  (e.type === 'mousedown') ? CS.isDrawing = true: 0;
  (e.type === 'mouseup') ? CS.isDrawing = false: 0;
  let mouseParams = {
    x: e.layerX,
    y: e.layerY,
    movArr: [e.movementX, e.movementY],
    windowArr: [e.clientX, e.clientY]
  };
  if (CS.isDrawing === false) {
    mouseCtx.clearRect(0, 0, mouseLayer.width, mouseLayer.height);
    mouseCtx.drawImage(canvas, 0, 0); //copy the current canvas
    console.log((CS.isDrawing === true) + " is drawing");
    mouseCtx.strokeStyle = CS.strokeS || randomRGBA();
    mouseCtx.fillStyle = CS.fillS || randomRGBA();
    mouseCtx.globalAlpha = CS.lOpacity;
    mouseCtx.beginPath(); //draw the thing on the current canvas
    switch (CS.tool) {
      case 'tBrush':
        drawBrush(mouseParams, mouseCtx, CS.brush, CS.brushSize);
        break;
      case 'tLine':
        drawLine(mouseParams, mouseCtx);
        break;
      case 'tCurve':
        drawBezier(mouseParams, mouseCtx);
        break;
      case 'tCircle':
        drawCircle(mouseParams, mouseCtx);
        break;
      case 'tSquare':
        drawSquare(mouseParams, mouseCtx);
        break;
    }
  } else {
    ctx.drawImage(mouseLayer, 0, 0);
  }
}
canvas {
  position: absolute;
  left: 0px;
  top: 0px;
  border: 2px solid green;
  outline: none;
  -webkit-user-select: none;
  /* Chrome all / Safari all */
  -moz-user-select: none;
  /* Firefox all */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
  cursor: none;
  z-index: 1;
}
canvas.mouseOverlay {
  position: absolute;
  left: 0px;
  top: 0px;
  border: 2px solid green;
  outline: none;
  -webkit-user-select: none;
  /* Chrome all / Safari all */
  -moz-user-select: none;
  /* Firefox all */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
  cursor: none;
  z-index: 0;
}

A: What might be happening is that your preview canvas is preventing events from being fired on the main canvas by getting in the way. Have you checked that the mousedown event on your main canvas is being fired? If it is indeed not being fired, try adding pointer-events:none; to your canvas.mouseOver css (with the z-index being higher).
Note: this might be a bad solution if you need to support older versions of IE


text:
Q: Project on update/create (set values from another object en masse) in LINQ2DB? When using LINQ2DB for my application I tried to use entity-DTO mapping using Expression<Func<Entity, DTO>> and vice versa like described here: https://github.com/linq2db/linq2db/issues/1283#issuecomment-413509043
This works great for projecting using a select, but what do I do when I need to update/insert a new record? I've skimmed over Update and Set extension methods but couldn't find anything.
What I am trying to achieve is basically expression-based two-way mapping between an entity class and a DTO, kinda like AutoMapper's projection for EF but manually written per-DTO, in the form of two expressions for two-way conversion.
Sadly I am not an expert in expression trees and LINQ to SQL translation, so would appreciate if anyone suggests something that works like this:
Expression<Func<SomeDTO, SomeEntityTable>> projectExpr =
    x => new SomeEntity
    {
        ID = x.ID,
        Name = x.Name,
        // ...
    }; // this is just so that I can write two mapping expressions per DTO and don't ever repeat them, for stuff like CRUD

// ...

using var db = ConnectionFactory.Instance.GetMainDB();
await db.SomeEntityTable
    .Where(e => e.ID == dto.ID)
    .Set(dto, projectExpr) // dto is of SomeDTO type here; this will set ONLY the values that are written in the expression
    .Set(e => e.LastEditedAt, DateTime.Now()) // able to append some more stuff after
    .UpdateAsync();

// similar for insert operation, using the same expression

A: These extension methods should provide needed mapping:
using var db = ConnectionFactory.Instance.GetMainDB();

await db.SomeEntityTable
    .Where(e => e.ID == dto.ID)
    .AsUpdatable()
    .Set(dto, projectExpr) // new extension method
    .Set(e => e.LastEditedAt, DateTime.Now())
    .UpdateAsync();

await db.SomeEntityTable
    .AsValueInsertable()
    .Values(dto, projectExpr) // new extension method
    .Value(e => e.LastEditedAt, DateTime.Now())
    .InsertAsync();

And implementation:
public static class InsertUpdateExtensions
{
    private static MethodInfo _withIUpdatable       = Methods.LinqToDB.Update.SetUpdatableExpression;
    private static MethodInfo _withIValueInsertable = Methods.LinqToDB.Insert.VI.ValueExpression;

    public static IUpdatable<TEntity> Set<TEntity, TDto>(
        this IUpdatable<TEntity>        updatable,
        TDto                            obj,
        Expression<Func<TDto, TEntity>> projection)
    {
        var body = projection.GetBody(Expression.Constant(obj));

        var entityParam = Expression.Parameter(typeof(TEntity), "e");

        var pairs = EnumeratePairs(body, entityParam);

        foreach (var pair in pairs)
        {
            updatable = (IUpdatable<TEntity>)_withIUpdatable.MakeGenericMethod(typeof(TEntity), pair.Item1.Type)
                .Invoke(null,
                    new object?[]
                    {
                        updatable,
                        Expression.Lambda(pair.Item1, entityParam),
                        Expression.Lambda(pair.Item2)
                    })!;
        }

        return updatable;
    }

    public static IValueInsertable<TEntity> Values<TEntity, TDto>(
        this IValueInsertable<TEntity>  insertable,
        TDto                            obj,
        Expression<Func<TDto, TEntity>> projection)
    {
        var body = projection.GetBody(Expression.Constant(obj));

        var entityParam = Expression.Parameter(typeof(TEntity), "e");

        var pairs = EnumeratePairs(body, entityParam);

        foreach (var pair in pairs)
        {
            insertable = (IValueInsertable<TEntity>)_withIValueInsertable.MakeGenericMethod(typeof(TEntity), pair.Item1.Type)
                .Invoke(null,
                    new object?[]
                    {
                        insertable,
                        Expression.Lambda(pair.Item1, entityParam),
                        Expression.Lambda(pair.Item2)
                    })!;
        }

        return insertable;
    }

    private static IEnumerable<Tuple<Expression, Expression>> EnumeratePairs(Expression projection, Expression entityPath)
    {
        switch (projection.NodeType)
        {
            case ExpressionType.MemberInit:
            {
                var mi = (MemberInitExpression)projection;
                foreach (var b in mi.Bindings)
                {
                    if (b.BindingType == MemberBindingType.Assignment)
                    {
                        var assignment = (MemberAssignment)b;
                        foreach (var p in EnumeratePairs(Expression.MakeMemberAccess(entityPath, assignment.Member),
                                        assignment.Expression))
                        {
                            yield return p;
                        }
                    }
                }
                break;
            }

            case ExpressionType.New:
            {
                var ne = (NewExpression)projection;
                if (ne.Members != null)
                {
                    for (var index = 0; index < ne.Arguments.Count; index++)
                    {
                        var expr   = ne.Arguments[index];
                        var member = ne.Members[index];

                        foreach (var p in EnumeratePairs(Expression.MakeMemberAccess(entityPath, member), expr))
                        {
                            yield return p;
                        }
                    }
                }
                break;
            }

            case ExpressionType.MemberAccess:
            {
                yield return Tuple.Create(projection, entityPath);
                break;

            }
            default:
                throw new NotImplementedException();
        }
    }
}


text:
Q: Does spring sometimes do some slow processes before and after controller method execution? I have a spring boot application running in a k8s environment.
When I was doing some tests to see how our app handles multiple request I have noticed that the application is losing some time before and after controller method execution. The application has some filters in place which are executing before and after controller method execution, but they aren't doing anything heavy, just reading some information from requests and removing some cached strings.
I have tracing setup so I can track the executions of certain parts of the application, mostly external calls, but for testing purposes I added tracing in additional parts. Trace root span is started in a filter which sits at the top of the filter chain.
You can see the weird behaviour in the image of traces bellow.
In red I have marked spans which represent the controller methods, in black I have marked spans which represent spans of last two filters which are placed at the end of the filter chain.
In this image we can see that after taas_tenant_support_check fitler, which is second from last in the filter chain finished it's execution, controller method execution started 50ms later.
In this image we can see that taas_remove_bo_user_context filter, which is last in the filter chain, was executed at around 80ms later after controller method finished executing.
This behaviour was only captured while the application is running in k8s environment, on my local machine under the same load (which is currently just 50 parallel requests) this never happens.
Pod in which our application is running uses maximum of 1 CPU and 2GB of memory.
I have also ran an application on my local machine inside a docker container with similar resource restrictions, but the weird behaviour wasn't recorded.
Trace spans are exported in batches and that exporter is running in a separate thread from the main application and I don't think that this is slowing us down.
With debugger I went through the spring's source code to see what is going on before and after a controller method gets executed, but I haven't found anything that could cause this behaviour.
Does anyone have an idea what might be going on here?


text:
Q: Android Studio 3.1.4 issues I'm new to AS and i'm having some teething issues.
I am following this tutorial with the kotlin path
https://developer.android.com/training/basics/firstapp/
I am getting these errors when attempting to run the app

e: C:\Users\Dan\Downloads\Whackamole-Making-toast-v1.0\MyFirstApp\app\src\main\java\com\example\dan\myfirstapp\DisplayMessageActivity.kt: (19, 52): Unresolved reference: textView
e: C:\Users\Dan\Downloads\Whackamole-Making-toast-v1.0\MyFirstApp\app\src\main\java\com\example\dan\myfirstapp\MainActivity.kt: (20, 22): Expression 'intent' of type 'Intent!' cannot be invoked as a function. The function 'invoke()' is not found
e: C:\Users\Dan\Downloads\Whackamole-Making-toast-v1.0\MyFirstApp\app\src\main\java\com\example\dan\myfirstapp\MainActivity.kt: (21, 13): Unresolved reference: putExtra

As far as I can tell I have entered the code exactly as it should be. Any help is greatfully appreciated
EDIT: Heres the code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myfirstapp.MainActivity">

<EditText
    android:id="@+id/editText"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:ems="10"
    android:hint="@string/edit_message"
    android:inputType="textPersonName"
    app:layout_constraintEnd_toStartOf="@+id/button"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    android:onClick="sendMessage"
    android:text="@string/button_send"
    app:layout_constraintBaseline_toBaselineOf="@+id/editText"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/editText" />
</android.support.constraint.ConstraintLayout>

MainActivity.kt
package com.example.dan.myfirstapp

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.EditText

const val EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}
fun sendMessage(view: View) {
    val editText = findViewById<EditText>(R.id.editText)
    val message = editText.text.toString()
    val intent = intent(this, DisplayMessageActivity::class.java).apply {
        putExtra(EXTRA_MESSAGE, message)
    }
    startActivity(intent)
}
}

activity_display_message.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

DisplayMessageActivity.kt
package com.example.dan.myfirstapp

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class DisplayMessageActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_display_message)

    //Get the Intent that started this activity and extract the string
    val message = intent.getStringExtra(EXTRA_MESSAGE)

    //Capture the layout's TextView and set the string as it's text
    val textView = findViewById<TextView>(R.id.textView).apply {
        text = message
    }
}
}

A: *

*textView does not exist in activity_display_message.xml

*val intent = Intent(..)
instead of val intent = intent(..)
For the 1st: place a TextView with id textView in activity_display_message.xml
For the 2nd: you instantiate the variable intent as an instance of the class Intent.
Edit: I found the lesson you're working on and I see that you missed the part with the title: "Add a text view"


text:
Q: Passing data structures from Python to Java using Jython This seems like a really basic question, but I haven't been able to find the answer...
I have a Java web app built with GWT.  It needs to call some code that's written in Python.  I've followed the tutorial and written an object factory for the methods that use simple data types.
However, one of the python methods includes this code:
titles_ranked = []
 for i in range(len(sort_index)):
     doc['title'] = self.titles[sort_index[i]][0][0]
     doc['role'] = self.RDS[:,sort_index[i]].toarray().reshape(6,)
     titles_ranked.append(doc.copy())
 return titles_ranked

How can I represent this in the Java wrapper class so that I can access it from Java?  Alternatively, do I need to use some other data structure?

A: I figured it out, it's a PyArray.


text:
Q: AppGyver sharing data across views in a MPA I have a search form that is being used to query a database. I'm able to get the data returned so I can display it on the same view that it's being queried from, but I'd like to display the data on a results page, and then be able to display a single entry with more information about it.
I've reviewed the docs and so far I've been unable to make any of their methods work for what I'm doing.
If it matters, all of my attempts have been with an Android phone using the scanner app. If someone knows of an example application that I can look at to see how data-sharing should be implemented, I would appreciate it.

A: I have got the publish subscribe pattern working most of the time. The only catch would be that subscribing view should already be loaded. (Either pre-loaded or manually loaded). Never got the superscope approach working.
One thing that always worked for me is the localstorage method.
One can always do a
localStorage.setItem("readitems", JSON.stringify(localreadItems));

and
 var readitems = JSON.parse(localStorage.getItem("readitems"));