text:
Q: IE7 Not Playing Nice with My Floating Sidebar I'm trying to get a dynamically sized sidebar to float in the upper right portion of my web pages (but below the header and nav) and have the main content on the page flow around it (sort of in an "L" shape except with the bottom part of the "L" really thick).  The width and height of the sidebar will vary from page to page so I can't use any hard values.
My css looks like:
#main {
    width: 850px;
    height: auto;
}

#sidebar {
    width: auto;
    float: right;
}

(plus some padding, margin, and background color code I think is inconsequential)
My html looks like:

    /* header stuff */

       /* nav stuff */

        /* my sidebar content, really just an h3 and a ul */

        /* lots of content here */

I don't completely understand why I have to have the sidebar div first, but it this code works fine in FF, Chrome, Safari (Windows), and IE8.  But on IE7 (and IE6, which I don't care about), the main content gets pushed down below the bottom of the sidebar, as if there was a "clear: left" on the sidebar div (but there isn't).
I have a feeling this is one of those evil IE7 non-compliance bugs, especially because IE8 behaves exactly like the other browsers.  But I have no idea how to fix it.
Any ideas? TIA.

A: First, make sure you are using a doctype that will put IE7 into strict mode (see http://hsivonen.iki.fi/doctype/ for an explaination).  if that doesn't do it, it may be that you need some play in your margin widths.
The reason why you have to have the sidebar div first, is since div is a displayed as a block element anything after it, will be below it (unless you float the main div).
By floating the sidebar div and putting it first, the browser knows it can display the main div to the right of the sidebar.  You could get a similar effect by adding float left to the main div and removing the float from the sidebar div and moving it after the main div.

A: From what you describe, it sounds like your sidebar is behaving as if it was a block element.  Maybe try some different display options like inline-block.  I'd also try experimenting with the width min-width attributes.  Hard to say though.

A: Bingo!  Fixed!  The guys who mentioned playing around with widths and margins get the gold stars tonight.  It turned out that all I had to do was remove the fixed width on the main div, then add some padding on the right to create a gutter for text and images.  Tested and confirmed in FF3, Chrome, Safari (Win), and most importantly, IE6 & IE7 (even though I still hate IE).
I guess the IE rendering engine was saying, "I see that you want your main div to be 850px wide, but with that sidebar you stuck up there, I don't have room so I'll have to shove it underneath the sidebar".  Of course, every other browser's rendering engine said, "Dude, I totally get what you're trying to do!  No problem, I'll lay out everything exactly as you'd like it."


text:
Q: How to re-initialized flutter animation in previous page when click android back button? flutter
page A has an animation , most code is in "initState" .
page A has navigated to page B.
when click back button on anroid machine to page A again , i want page A to replay the animation on page A . but i don't want to add some "animationcontroller.reset()" and "animationcontroller.forward()" in "build" method in page A .
how should i do that ?

A: Since the Navigator's push methods are a Futures, you could "await" them to resolve and then execute the code to reset the animation.
Like:
Navigator.push(...).then((_) => _animationController.reset());

redpajama_set_name: RedPajamaStackExchange


text:
Q: How about website suggestion based on something such as tags? Sometimes I don't know which Stack Exchange website is suitable for my question. For example, in the past, I had a question about anonymousness of VPN. I asked this question on Network Engineering. But guys told me that is an off-topic question. Finally I found it is suitable for Information Security and got a good answer there.
So I'm wondering if Stack Exchange could add a function to provide suggestion about suitable website based on some information. I guess the easiest one is tag. If I add "networking" and "anonymous" tags, it could suggest me to ask this question on Information Security.

A: If you want to know whether something is on-topic on a certain site or not, take a look at their help center:
https://example.stackexchange.com/help/on-topic
Works for every SE site.
If you don't know what sites there are, you can take a look at the overview.
As I already said in the comments, implementing automated recommendations based on keywords is hard. It's very, very error-prone and will likely create more trouble than it solves. Heck, I'll guarantee you it will.
So, please, no.


text:
Q: Run matlab code on javascript I have a simple matlab code. It loads a file and draws a graph using datas in this file. I want that when I press a html button, the graph is drew.I read some recommendations on web/blogs. Have to I use com server?
EDIT
My app is not a web app yet. I run it local pc, it is just a htm file.I use google chrome for now.

A: The answer to your question is not necessary, you could have some workarounds to avoid using a COM server (although it's well explained in the official documentation).
It depends if your webapp is a Java application, PHP, etc.
A simple approach using PHP would be using passthru to run your matlab app and later you could link to the generated file.
Related questions:

*

*Can I run MATLAB code on a web site?

*How to run MATLAB code from Java?

A: One way to do so would be for you to generate the C++ code out of Matlab code using Matlab coder, then there are a few way ways to run C/C++ codes in the browser, see below links:
Running C in A Browser and Native client
It is worthwhile to mention that it might not be the best idea and you might face many fundamental issues since you are practically converting Matlab code two times to different programming languages. Currently, there are many issues with Google Native Client, including the fact that you can not run it on every browser, other services are essentially better than the google native client.
Finally, if you have a simple code I would recommend you to rewrite it in JS instead of going throw all the trouble.


text:
Q: iOS6 Twitter integration There seems to be a difference between the iPhone simulator and actual device when checking if Twitter is available.
I check if a Twitter account is setup by using this code: [SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter];
In the simulator there is a nice UIAlertView informing the user that there are no Twitter accounts setup and two buttons one for Settings and one for Cancel.
However when I run my app on my device it will not show the above UIAlertView. Why is that? And how can I catch what button is tapped in the above UIAlertView (since I did not instantiate it?)
This is what it looks like on the simulator:

A: To handle the result of the Twitter call, You can use this snippet :
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
        SLComposeViewControllerCompletionHandler __block completionHandler=^(SLComposeViewControllerResult result){

        [twitterController dismissViewControllerAnimated:YES completion:nil];

        switch(result){
        case SLComposeViewControllerResultCancelled:
        default:
        {
            NSLog(@"Cancelled.....");

        }
            break;
        case SLComposeViewControllerResultDone:
        {
            NSLog(@"Posted....");
        }
            break;
    }};

    [twitterController setCompletionHandler:completionHandler];
    ...
    ...
   }

A: I also am having the same issue that the device doesn't display the UIAlert like the simulator does. Until Apple fixes it, this is what I'm doing (not as clean or nice as the simulator, and requires the user to manually go to the homescreen) Apple, please fix this!
Edit: the stock Apple apps show the UIAlert perfectly of course, example: sharing a photo from the photo app without having a Twitter/Facebook account will display the correct UIAlert.
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
        [mySLComposerSheet setInitialText:@"Check out the app:"];
        [mySLComposerSheet addImage:[UIImage imageNamed:@"test.png"]];
        [mySLComposerSheet addURL:[NSURL URLWithString:@"http://urlofyourapp.com"]];
        [self presentViewController:mySLComposerSheet animated:YES completion:nil];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You need to setup an account in the Settings app under Twitter to use this feature." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
    [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {

        if (result == SLComposeViewControllerResultCancelled){[mySLComposerSheet dismissModalViewControllerAnimated:YES];}
        else if (result == SLComposeViewControllerResultDone){[mySLComposerSheet dismissModalViewControllerAnimated:YES];}

    }];


text:
Q: Can we export multiple non-AMD functions from a module in requirejs? If I have a non-AMD module named old.js and inside this script I have two functions f1 and f2 defined. I need to use them, how do I export both?
require.config({
    paths: {
        "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min",
    },
    shim: {
        "old": {
            deps: ["jquery"],
            exports: ["f1", "f2"]
        }
    },
    urlArgs: "bust=" + (new Date()).getTime()
});

This wouldn't work. I will get split error. The doc doesn't mention multiple (http://requirejs.org/docs/api.html#config-shim) I assume this is because even those jquery examples are individual files and they have "entry" function / class.

A: Generally, if you want to export more than a single object from a module, you... still need to export a single object. The standard form is to attach your functions to an export object and return that:
function f1() { ... }
function f2() { ... }

return {
    f1: f1,
    f2: f2
};

If this is non-AMD code, you might not have the return statement, but you'd still need to add the export object.
It looks like the recommended option for old code is to only specify f1 in the exports property, but then do further munging in the init function. Presumably require is actually using the exports property to check that the file has loaded, so it doesn't matter whether you include all items. Assuming f1 and f2 are both globals, you could probably do this:
shim: {
    "old": {
        deps: ["jquery"],
        exports: "f1",
        init: function() {
            return {
                f1: f1,
                f2: f2
            };
        }
    }
}

This ought to allow you to require old and get the export object, rather than f1:
require(['old'], function(old) {
    old.f1();
    old.f2();
});


text:
Q: Retrieve all window opened on Windows I try to retrieve some information(x,y,width,height and title) for all opened window on Windows with a simple C++ code(see below):
#include <iostream>
#include <windows.h>
using namespace std;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int     iCmdShow)
{
    EnumWindows(EnumWindowsProc, NULL);
    //system("PAUSE");
    return 0;
}

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
char class_name[255];
char title[255];
int tmpWidth;
int tmpHeight;
HWND currenthwnd;
RECT WindowRect;

GetClassName(hwnd,class_name, sizeof(class_name));
GetWindowText(hwnd,title,sizeof(title));
GetWindowRect(hwnd,&WindowRect);

//if(WindowRect.left>-50 && title != "" && title != NULL && strlen(title)>0){
    tmpHeight = WindowRect.bottom - WindowRect.top;
    tmpWidth = WindowRect.right - WindowRect.left;
    cout <<"@@##@@"<<title<<",(@@#@@)";
    cout <<WindowRect.left<<",(@@#@@)";
    cout <<WindowRect.top<<",(@@#@@)";
    cout <<tmpWidth<<",(@@#@@)";
    cout <<tmpHeight<<",(@@#@@)";
    currenthwnd=GetForegroundWindow();
    if (currenthwnd!=hwnd){
       cout <<title<<",(@@#@@)false";
    }else{
       cout <<title<<",(@@#@@)true";
    }
 //}

 return TRUE;
}

But I encountered some issue with this code, I also try with PowerShell with Get-Process function, but this function doesn't return all opened windows but all existing process.
How can I retrieve title, x,y, with, heigth of all opened window ?
Thanks for your help

A: In powershell you can use the WASP Module and wrote something like this:
Get-Process | Where-Object {$_.MainWindowTitle -ne ""}  |
% {$_.processname + "-" + $_.mainwindowtitle;
       Get-WindowPosition -Window $_.handle }

This is a result example for my actual powershell windows:
powershell - Posh - Admin
Location : {X=4,Y=44}
Size     : {Width=885, Height=129}
X        : 4
Y        : 44
Width    : 885
Height   : 129
Left     : 4
Top      : 44
Right    : 889
Bottom   : 173
IsEmpty  : False


text:
Q: Sort array by highest value calculated from contents I have an array of strings like this:

["Brazil (62)", "PalestinianTerritoryOccupied (6)", "Macedonia (2)",
  "Germany (6)"]

I want to sort them by the highest value but it's got me stumped. I've tried all sorts of weird, wonderful (and useless) things like:
cont.sort! { |it| it.scan(/\d+/).to_s.to_i}

A: sort_by {|e| e[/\d+/].to_i }.reverse

should do the trick. You can write this one in a more efficient and elegant way (see comments), like in the following:
sort_by {|e| -e[/\d+/].to_i }

Note the -.
Using sort you can do:
sort {|a, b| b[/\d+/].to_i <=> a[/\d+/].to_i }

EDIT
String#[] has been suggested in the comments.


text:
Q: AngularJS updating custom directive variable I have one variable in my controller used as flag. i use this variable in directives scope. i call my controller function from directive (passing directive scope with this function) and try to update flag variable, variable is update in controller(got updated value in console.log()) but i am not getting updated value inside directive.

A: Need your code to know what's the relationship between your directive and controller.
Here is my simple example. $scope.test can be updated.
JavaScript:
angular.module('myApp',[]);

angular.module('myApp').controller('myCtrl',['$scope', function($scope){
  $scope.test='msg from myCtrl';
  $scope.onClick=function(){
    $scope.test='msg from function in myCtrl';
  };

}]);

angular.module('myApp').directive('myDirective', function(){
  return{
    restrict:'E',
    template:'
Hello! {{test}}
<button class="btn btn-default" type="button" ng-click=onClick()>Change value</button>',
    controller:['$scope','$element',function($scope, $element){
      $scope.test='msg from myDirective controller.'
    }],
    link: function(scope, element, attrs){

    },
  };
});

HTML:

  {{test}}

  <my-directive />


text:
Q: Microservices with spring boot, WITHOUT spring cloud I am new in Microservice. Can we implement a microservice with the help of spring boot, without spring cloud. In every tutorial it has been mentioned as create Microservice using spring boot and spring cloud. Kindly elaborate.

A: Definitely yes.
Microservice architecture doesn't necessarily assume that a microservice will run in a cloud environment.
Spring cloud provides "extra" features usually required in cloud environments, for instance centralized configuration management, service discovery, etc.
So using spring boot allows running microservice (strictly speaking you can even have spring boot driven monoliths) but without all the aforementioned features for cloud.

A: Yes, you can. Here's a pretty much simplest possible spring boot microservice:
@RestController
class HelloworldController {
  @RequestMapping("/")
  String home() {
    return "Hello world!"
  }
}

which you can save into Helloworld.groovy and run with spring run Helloworld.groovy, assuming you have spring boot cli installed.


text:
Q: Using eclipse streaming audio from web url I have tried to find the answer online and none are clear to me. I am starting of programming and dont know much so any assistance that makes sense would help. My brother developed a website I'm trying to stream audio from and found on the developer web page a code to use. eclipse gives me no errors but when I run the app it forces close here is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  String url = "http://beatswith.us/uploads/Mac%20Miller%20-  %20Paper%20Route%20feat.%20Kev%20Da%20Hustla.mp3"; // your URL here
  MediaPlayer mediaPlayer = new MediaPlayer();
  mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

  try {
    mediaPlayer.setDataSource(url);
  } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  } catch (IllegalStateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  try {
    mediaPlayer.prepare();
  } catch (IllegalStateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  } // might take long! (for buffering, etc)

  mediaPlayer.start();
}
};

A: Its probably throwing an exception at mediaPlayer.start()
The url must be bad. looks to me like theres an actual space in your String, which is invalid. You should put setDataSource, prepare, and start in the same try/catch block
Edit:nevermind the url seems fine. Can you post the stacktrace of the exception?
Edit2: did you add your activity to the AndroidManifest.xml? Are you navigating here from another activity?

A: Found the Answer I had my button set up with the wrong package name


text:
Q: What are the differences between jquery-rails and rails-assets-jquery? Generally I used the jquery-rails gem to embed jQuery into my rails projects. Now I started to use rails-assets and some of the gems have depend on rails-assets-jquery, which also provides jquery.
My question is, can I just remove jquery-rails? Is there something special about jquery-rails or another reason to keep it in my project?
My gem file (shortened version) looks like this:
source 'https://rubygems.org'
source 'https://rails-assets.org'

gem 'rails', '4.1.5'

#gem 'jquery-rails', '~> 3.1.2' # jQuery
gem 'rails-assets-jquery'
gem 'rails-assets-slick-carousel'

A: The difference is, the rails-assets-WHATEVER is a package from Bower.io while the other one is from RubyGems. So, in a ideal world there's no difference between rails-assets-jquery and jquery-rails. So, you have to assume that the authors are pushing new versions at the same time to both repositories: Bower and RubyGems. However, in real world there are different maintainers of packages and the numbering of versions does not always match. Rails Assets project tries to unify packaging systems (of Ruby and JavaScript projects) into a single file (Gemfile).
Anyway, the recommended usage is:
source 'https://rubygems.org'
gem 'rails', '4.1.5'
#gem 'jquery-rails', '~> 3.1.2' # jQuery

source 'https://rails-assets.org' do
  gem 'rails-assets-jquery'
  gem 'rails-assets-slick-carousel'
end

just to make clear, that your not downloading rails-assets-jquery from RubyGems, in fact someone might have uploaded such a package to RubyGems.


text:
Q: Send data from script.js to Node.js file (Using Sendgrid API) Trying to insert data into a node.js server file from a submit event on another js.file client.
But it wont work could you see if there is any wrong with code? Looks kinda good to me but ofcourse something is wrong.
Client submit event code
`window.onload = function() {

            document.getElementById('contact-form').addEventListener('submit', function(event) {
                event.preventDefault();

                const customMessage = document.getElementById('contact-form');

                $.post("/request", {
                  mes: customMessage

              }, function(data, status) {
                  console.log(data);
              });

            });
        }`

Server node js code
// require necessary modules
`const express = require('express');
const bodyParser = require('body-parser');
const sgMail = require("@sendgrid/mail");
require('dotenv').config({ path: './dist/sendgrid/.env' });`

// set up the express app
`const app = express();
const port = process.env.PORT || 3000;`

// use body-parser middleware to parse request body
`app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());`

// set up the SendGrid API key
`sgMail.setApiKey(process.env.SENDGRID_API_KEY);`

// define route to handle POST request from client
`app.post('/request', async (req, res) =\> {
try {
// extract message from request body
const { mes } = req.body;
`
    // send email using SendGrid
 `  await sgMail.send({
      to: 'test@gmail.com',
      from: 'test2@gmail.com',
      subject: 'test text not working',
      text: mes
    });

  console.log('Email sent successfully');
    res.status(200).send('Email sent successfully');`

} catch (error) {
console.error(error);

    if (error.response) {
     console.error(error.response.body);
    }

    res.status(500).send('Internal server error');

}
});`

// start the server
`app.listen(port, () =\> {
console.log(`Server started on port ${port}`);
});

`
This is basic code that is working on single execute:
`
require("dotenv").config();

const sgMail = require("@sendgrid/mail");

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const sendMail = async(msg) =\> {
try{
await sgMail.send(msg);
console.log("message sent succes");
} catch (error) {
console.error(error);

        if (error.response) {
            console.error(error.response.body);
        }
    }

};

sendMail({

     to: 'test@gmail.com',
      from: 'test2@gmail.com',
      subject: 'test text',
    text: "this test works"

});`


text:
Q: SSLError when using open_by_key(Spreadsheet ID) I referred to the following site. After completing each setting, I wrote gspread_simple.py which shown the site.
https://qiita.com/164kondo/items/eec4d1d8fd7648217935
As a result, the following error was output (I replaced a folder name under C:\Users with ********).
Traceback (most recent call last):
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 696, in urlopen
    self._prepare_proxy(conn)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 964, in _prepare_proxy
    conn.connect()
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 359, in connect
    conn = self._connect_tls_proxy(hostname, conn)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 496, in _connect_tls_proxy
    return ssl_wrap_socket(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
    ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
    return ssl_context.wrap_socket(sock)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1122)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 783, in urlopen
    return self.urlopen(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 783, in urlopen
    return self.urlopen(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 783, in urlopen
    return self.urlopen(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\retry.py", line 573, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1122)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\auth\transport\requests.py", line 182, in __call__
    response = self.session.request(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1122)')))

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\********\samp\module1.py", line 18, in <module>
    ws = connect_gspread(jsonf,spread_sheet_key)
  File "C:\Users\********\samp\module1.py", line 12, in connect_gspread
    worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\gspread\models.py", line 123, in sheet1
    return self.get_worksheet(0)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\gspread\models.py", line 283, in get_worksheet
    sheet_data = self.fetch_sheet_metadata()
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\gspread\models.py", line 265, in fetch_sheet_metadata
    r = self.client.request('get', url, params=params)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\gspread\client.py", line 61, in request
    response = getattr(self.session, method)(
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\auth\transport\requests.py", line 460, in request
    self.credentials.before_request(auth_request, method, url, request_headers)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\auth\credentials.py", line 133, in before_request
    self.refresh(request)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\service_account.py", line 361, in refresh
    access_token, expiry, _ = _client.jwt_grant(request, self._token_uri, assertion)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 153, in jwt_grant
    response_data = _token_endpoint_request(request, token_uri, body)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\oauth2\_client.py", line 105, in _token_endpoint_request
    response = request(method="POST", url=token_uri, headers=headers, body=body)
  File "C:\Users\********\AppData\Local\Programs\Python\Python39\lib\site-packages\google\auth\transport\requests.py", line 188, in __call__
    six.raise_from(new_exc, caught_exc)
  File "<string>", line 3, in raise_from
google.auth.exceptions.TransportError: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1122)')))

I referred to the following site and so on.
https://qiita.com/vmmhypervisor/items/c8ef0ad87318656facb2

*

*OS: Windows10

*Python: 3.9

My Python is not 2.7 series.
As a test, I tried the command.
pip uninstall -y certifi && pip install certifi==2015.04.28

But the output was the same.
And I tried the command.
pip install -U certifi

But the output was the same.


text:
Q: How to add a new span in POS customer view? Odoo 14 I want to add a span in POS customer view . I tried with this code , but doesn't work.
//customer.xml
<?xml version="1.0" encoding="UTF-8" ?>
<templates id="point_of_sale.template" xml:space="preserve">
<t t-extend="ClientDetailsEdit">
        <t t-jquery=".client-details-right" t-operation="append">

                Test

        </t>
    </t>

</templates>

//manifest.py
"qweb": [
        'static/src/xml/customer.xml',
        ],

What's wrong in my code ? Any help please ? Thanks.

A: If I look in Odoo addons an example of extend, the templates is declared like this
<templates id="template" xml:space="preserve">

in your case your declare the template like this
<templates id="point_of_sale.template" xml:space="preserve">

And in your module when you write this id="point_of_sale.template" Odoo will overridden the base templates. But in the logical of templates the t-name must be unique in all modules.
If I follow this logical you should write:
<?xml version="1.0" encoding="UTF-8" ?>
<templates id="template" xml:space="preserve">
<t t-extend="ClientDetailsEdit">
        <t t-jquery=".client-details-right" t-operation="append">

                Test

        </t>
    </t>

</templates>

In this solution you don't overridden the template point_of_sale.template but you will create a new template will extend t-name ClientDetailsEdit
PS: For more information I look addons/iap/statis/src/xml/iap_template.xml
And the code is
<?xml version="1.0" encoding="UTF-8"?>
<template id="template" xml:space="preserve">

        <t t-if="data.body">

        </t>
        <t t-if="!data.body">
            <t t-if="data.message">

            </t>
            <t t-if="!data.message">
                Insufficient credit to perform this service.
            </t>
        </t>

    <t t-extend="DashboardMain">
        <t t-jquery=".o_web_settings_apps" t-operation="after">

        </t>
    </t>

            <button class="btn btn-link buy_credits"> Buy credits</button>

</template>


text:
Q: log4j is not working in weblogic server? I am using weblogic 10.3.4, I am trying to write log with log4j. but at runtime my application is not getting any log4j.properties. even this is not generating any warning as "initialization of log4j has error".
I have tried my properties file to put in src folder, classes folder and then I created one jar and put it in domain lib. still its not picking. even when I am writing log with same jar in standalone application, its working fine.
please help me with valuable suggestions.

A: I tried the solution proposed at Oracle forums.
Excerpt from that link at Oracle forums:
I've only modified the scritp startWebLogic.cmd:
 set LOG4J_CONFIG_FILE=log4j.xml
 set SAVE_JAVA_OPTIONS=%JAVA_OPTIONS% -Dlog4j.configuration=%LOG4J_CONFIG_FILE%

 @REM set SAVE_CLASSPATH=%CLASSPATH%
 set SAVE_CLASSPATH=%CLASSPATH%;C:\Oracle\Middleware\user_projects\domains\domain\config

In this way I've put all the config folder inside the classpath, and I can use it in future to hold other libraries configuration files (for example oracle coherence config).
I tried this approach on a different properties file as well and that worked well!

A: You need to either specify where the application should find its log4j.properties, or put it onto the classpath of the application. Where the classpath is varies, but in general WEB-INF/classes should work. Other options depend upon how you're deploying the application.
A better long term strategy is to configure your system so that you can change the log4j.properties depending upon the environment. When you're in production, you won't want all of the debug information to appear. Look at the answer to this question or this question for more ideas. One strategy is to define a variable on the command line which gets picked up and defines a directory which contains your configuration files. This works for Tomcat, but there may be other, better, strategies for Weblogic.
It is not a good idea to change the configuration of your server, in particular, don't replace the log4j.jar or log4j.properties in your server directories. The server will depend upon the version that it was designed to use, which may or may not be the same as your version. You can do everything you need to do by changing the war that you're deploying.

A: I have used this code:
    ClassLoader cl = this.getClass().getClassLoader();
    URL log4jCfg = cl.getResource(configFile);
    if (log4jCfg != null) {
        DOMConfigurator.configure(log4jCfg);
    }
log.info("log4j is now working on Web App.");

In my case, we used XML configuration:
log4jCfg = "mylog4j.xml";

In WebLogic, we were able to place such file (mylog4j.xml), equivalent to your log4j.properties file, at WebLogic's domain path (specific to the domain were we deploy). This means that domain folder belongs to your application's path. I just tested it with Web applications, I'm not sure if with SOA or EJB projects it works the same way.

A: When you deploy any application on any server that application should use servers log4j jar.
So if you have added any log4j jar in your application jar/tar/ear, remove it and copy log4j.properties file in the conf folder of the server from where server is picking its configuration files. Or just copy your log4j property content in servers log4j property file.


text:
Q: Isomorphic TypeScript / require I have 4 files
Settings.ts
type sayType = () => string;

export interface SettingsModule {
    sayEnv: sayType;
}

settings.node.ts
import { SettingsModule } from '@/core/persistant/Settings';

export const mod: SettingsModule = {
    sayEnv: sayInternalEnv,
};

function sayInternalEnv(): string {
    return 'Node';
}

settings.browser.ts
import { SettingsModule } from '@/core/persistant/Settings';

export const mod: SettingsModule = {
    sayEnv: sayInternalEnv,
};

function sayInternalEnv(): string {
    return 'Browser';
}

settings.impl.ts
import { SettingsModule } from '@/core/persistant/Settings';

let settingsModule: SettingsModule;

if (window.indexedDB) {
    // tslint:disable-next-line:no-var-requires
    const m = require('./settings.browser') as { mod: SettingsModule };
    settingsModule = m.mod;
} else {
    // tslint:disable-next-line:no-var-requires
    const m = require('./settings.node') as { mod: SettingsModule };
    settingsModule = m.mod;
}

export const sayEnv = settingsModule.sayEnv;

The whole thing works like a charm but my question is it really safe to use require this way?
I mean - it works fine for such small files but is require always synchronous? Can I be sure that 'sayEnv' is always set?


text:
Q: Compiling an OCaml Book example on Hashtbl I've tried to compile the following example
open Core.Std
module Foo_and_bar : sig
    type t = S of string | I of int
    include Hashable.S with type t := t
  end = struct
    module T = struct
      type t = S of string | I of int with sexp, compare
      let hash t1 t2 = (hashData t1)
    end
    include T
    include Comparable.Make(T)
  end;;

with camlopt -o exec core.cmxa algebra.ml that could be found on this book but as a result, I obtain an error with sexp declaration. Where am I going wrong?

A: Core library comes with a tool that simplifies your life. It is named corebuild. With it you can compile just with:
corebuild algebra.native

And it will produce executable named algrebra.native
What concerning your try, then you are referring to core.cmxa and ocamlopt doesn't know where to find it. Moreover, you need to use camlp4 preprocessor, to enable syntax extensions. With ocamlfind wrapper around ocamlopt this can be achieved quite easily:
ocamlfind ocamlopt -thread -syntax camlp4o -package core.syntax algebra.ml -o exec

Here, -syntax camlp4o enables syntax extensions, -package core.syntax enables core and, also enables Core's syntax extensions.
But I still suggest to use corebuild, at least for the start.


text:
Q: Facebook Login in jQuery Dialog - MVC 4 ActionResult in jQuery Dialog Someone can suggest me what is the clean and proper way to render, what was a MVC 4 RedirectResult, in a jQuery Dialog?
I have a Facebook Plugin that return a "RedirectResult" so that during the login process the user is redirect on the facebook login page and then back to the website.
I would like to load the login page in a jQuery dialog so to not leave the website page.
In my controller I have:
    if (result.Result != null) return result.Result;

    return HttpContext.Request.IsAuthenticated ? new RedirectResult(!string.IsNullOrEmpty(returnUrl) ? returnUrl : "~/") : new RedirectResult(Url.LogOn(returnUrl));

"result.Result" is a RedirectResult Type and here I have the URL that contain the redirect.
Following the view with the jQuery Dialog where I would like to load the login facebook page:
   @using Nop.Web.Framework.UI
    @{
    Layout = "";
    Html.AddCssFileParts("./Plugins/ExternalAuth.Facebook/Content/facebookstyles.css");
    }

<fieldset class="facebook-login-block">
    <legend>@T("Plugins.ExternalAuth.Facebook.Login")</legend>

</fieldset>

This is the original call:

I tried to move it in the load function but this have not produce any result.
Any suggestion will be really appreciated.
Thanks

A: I think that I found a possible solution by myself, I don't know if is this is the best and clean way, but works. Following the details.
I changed my controller to this:
        if (result.Result != null) // return result.Result;
        {
            RedirectResult RR = (RedirectResult)result.Result;
            return Content(RR.Url);
        }

        return HttpContext.Request.IsAuthenticated ? new RedirectResult(!string.IsNullOrEmpty(returnUrl) ? returnUrl : "~/") : new RedirectResult(Url.LogOn(returnUrl));

and my view to this:
<fieldset class="facebook-login-block">
    <legend>@T("Plugins.ExternalAuth.Facebook.Login")</legend>

    @*
         *@

</fieldset>

Any other solutions are welcome.


text:
Q: Simulating Geographic data from Longitude & Latitude in R I am trying to perform some simulations on models I am testing, which have both phylogenetic and geographic networks.
I wish to test the effects of these independently to compare the methods estimation abilities on each dimension. However I am having trouble generating a continuous variable that shows significant geographic spatial auto=correlation. So far I have used average yearly temperature (this is country-level data), but this does not allow me to control the size of the spatial auto-correlation. Also it has the disadvantage of not knowing the true value of spatial auto-correlation.
I have a list of Longitude and Latitude points, and I was wondering if there was a simple or common way to generate a continuous response variable that would show spatial auto-correlation, and to be able to control the size of that correlation? Preferably within R, however, as long as they can be converted to a R-compatible format, other methods would be acceptable.
Any advice would be appreciated and please ask if there is any information you would find helpful.

A: Following the approach in Dormann et al. (2007), you could do something like this:
N <- 3000
p <- 1/N

# generate some points
set.seed(1234)
x.coord <- runif(N,0,100)
y.coord <- runif(N,0,100)
points <- cbind(x.coord,y.coord)

# distance matrix between points
Dd <- as.matrix(dist(points))

# weights matrix
w <- exp(-p * Dd)
Ww <- chol(w)

# errors
z <- t(Ww) %*% rnorm(N,0,1)

# plot
df <- data.frame(x = x.coord, y = y.coord, z = z)
require(ggplot2)
ggplot(df, aes(x = x, y = y, col = z)) +
  geom_point() +
  scale_colour_gradient(low="red", high="white")

where variable p controls the size of auto-correlation (here I set it to 1/3000 = 0.000333).
p = 0 would be no correlation.

Reference: Dormann, C. F., McPherson, J. M., Araujo, M. B., Bivand, R., Bolliger, J., Carl, G., … Wilson, R. (2007). Methods to account for spatial autocorrelation in the analysis of species distributional data: a review. Ecography, 30(5), 609–628.


text:
Q: Some Menus look incorrect Can someone explain to me why a clean install of 11.04, x64 is having these strange menu issues? Example:

This seems to happen on a few "Right-Click" menus, and not all system menus are affected. Can someone give me hand on fixing this?
I am using Ubuntu Classic for my session

A: I just checked mine, after having seen your posted pic, and found that mine are the same.  I did not notice this in Unity, but started experimenting with the Classic interface today.

A: Sounds like I'll need to file a bug report. I'll get the details back here when I do.


text:
Q: Cannot read property '0' of undefined in mdbreact Hey guys I'm using mdbreact to make a cart but I got some errors.
I'm using code from this section: https://mdbootstrap.com/docs/react/sections/e-commerce/
Here my code:

import React from "react";
import {  MDBRow, MDBCol, MDBCard, MDBCardImage, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardFooter, MDBIcon, MDBTooltip } from "mdbreact";

const Item = () => {
  return (

        Our bestsellers

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit,
        error amet numquam iure provident voluptate esse quasi, veritatis
        totam voluptas nostrum quisquam eum porro a pariatur veniam.

      <MDBRow>
        <MDBCol lg="3" md="6" className="mb-lg-0 mb-4">
          <MDBCard cascade narrow ecommerce>
            <MDBCardImage
              cascade
              src="https://mdbootstrap.com/img/Photos/Horizontal/E-commerce/Vertical/1.jpg"
              top
              alt="sample photo"
              overlay="white-slight"
            />
            <MDBCardBody cascade className="text-center">

Denim

              <MDBCardTitle>

                  Denim trousers

              </MDBCardTitle>

                  <MDBIcon icon="star" />

                  <MDBIcon icon="star" />

                  <MDBIcon icon="star" />

                  <MDBIcon icon="star" />

                  <MDBIcon far icon="star" />

              <MDBCardText>
                Neque porro quisquam est, qui dolorem ipsum quia dolor sit.
              </MDBCardText>
              <MDBCardFooter className="px-1">

                  49$

                  <MDBTooltip
                    placement="top"
                    tag="a"
                    component="i"
                    componentClass="fa fa-shopping-cart grey-text ml-3"
                    tooltipContent="Add to cart"
                  />
                  <MDBTooltip
                    placement="top"
                    tag="a"
                    component="i"
                    componentClass="fa fa-share-alt grey-text ml-3"
                    tooltipContent="Share"
                  />
                  <MDBTooltip
                    placement="top"
                    tag="a"
                    component="i"
                    className="active"
                    componentClass="fa fa-heart ml-3"
                    tooltipContent="Added to watchlist"
                  />

              </MDBCardFooter>
            </MDBCardBody>
          </MDBCard>
        </MDBCol>

      </MDBRow>

  );
}

export default Item;

The log says
TypeError: Cannot read property '0' of undefined.
Is this an issue from mdbreact or something ?
If true, can someone suggest me other alternative UI library for reactjs please ? React Bootstrap doesn't look good to me since I'm bad at CSS. Thank you

A: The error is in your implementation of MDBTooltip. From the documentation, it appears that component needs two children, the first being what the tooltip is attached to, and the second the content. Click here for a working example which implements the following code
import React from "react";
import { MDBBtn, MDBRow, MDBCol, MDBCard, MDBCardImage, MDBCardBody, MDBCardTitle, MDBCardText, MDBCardFooter, MDBIcon, MDBTooltip } from "mdbreact";

const Item = () => {
  return (

        Our bestsellers

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit,
        error amet numquam iure provident voluptate esse quasi, veritatis
        totam voluptas nostrum quisquam eum porro a pariatur veniam.

      <MDBRow>
        <MDBCol lg="3" md="6" className="mb-lg-0 mb-4">
          <MDBCard cascade narrow ecommerce>
            <MDBCardImage
              cascade
              src="https://mdbootstrap.com/img/Photos/Horizontal/E-commerce/Vertical/1.jpg"
              top
              alt="sample photo"
              overlay="white-slight"
            />
            <MDBCardBody cascade className="text-center">

Denim

              <MDBCardTitle>

                  Denim trousers

              </MDBCardTitle>

                  <MDBIcon icon="star" />

                  <MDBIcon icon="star" />

                  <MDBIcon icon="star" />

                  <MDBIcon icon="star" />

                  <MDBIcon far icon="star" />

              <MDBCardText>
                Neque porro quisquam est, qui dolorem ipsum quia dolor sit.
              </MDBCardText>
              <MDBCardFooter className="px-1">

                  49$

                  <MDBTooltip
                    placement="top"
                    tag="a"
                    component="i"
                    componentClass="fa fa-shopping-cart grey-text ml-3"
                    tooltipContent="Add to cart"
                  >
                    <MDBBtn>Tooltip button</MDBBtn>

                      Tooltip content

                  </MDBTooltip>
                  <MDBTooltip
                    placement="top"
                    tag="a"
                    component="i"
                    componentClass="fa fa-share-alt grey-text ml-3"
                    tooltipContent="Share"
                  >
                  <MDBBtn>Tooltip button</MDBBtn>

                      Tooltip content

                  </MDBTooltip>
                  <MDBTooltip
                    placement="top"
                    tag="a"
                    component="i"
                    className="active"
                    componentClass="fa fa-heart ml-3"
                    tooltipContent="Added to watchlist"
                  >
                  <MDBBtn>Tooltip button</MDBBtn>

                      Tooltip  content

                  </MDBTooltip>

              </MDBCardFooter>
            </MDBCardBody>
          </MDBCard>
        </MDBCol>
      </MDBRow>

  );
}

export default Item;


text:
Q: Switch from local to synced Realm I would like to use the Realm Mobile Platform to provide syncing for my app, but not force the user to register or sign in. I.e., I would like to use a local Realm at first, then switch to a synced Realm if the user decides to use that feature.
Is this possible? I couldn't find anything regarding this in the documentation.

A: This is possible to do, but you cannot automatically convert a standalone Realm into a synchronized Realm (in the future this could change). Instead, you would create a second synchronized Realm and then just copy the data from the standalone Realm into it.
As for requiring a login, currently to open a synchronized Realm you need an authorized User and the synced Realm URL. To get an authorized User, you must login with various credential mechanisms: username/password, Google, and Facebook are currently supported.
What it sounds like you need is an "anonymous" User, where Realm Object Server would generate an authorized User without a login. We plan to add this functionality in a later version and support for adding credentials to a User. This means that you could open a synchronized Realm immediately without a login via an "anonymous" User then later ask the end user to login, attaching actual credentials to the User object, such that if the end user used another device, they could login and identify themselves with the same underlying User object.


text:
Q: How do I display the handle for all front-end enqueued scripts in plugin options page? I use the following function in my plugin to display all the scripts handles in my plugin options page but it display only the handles of admin scripts:
function my_detected_scripts() {
  global $wp_scripts;
  foreach( $wp_scripts->queue as $handle ) :
    echo $handle . ' <br /> ';
  endforeach;
}

Then:
echo my_detected_scripts()

How can get the handles of all front-end enqueued scripts only?
Thanks in advance!

A: I think it's not possible to get the front-end scripts in a script called in the back-end, because the front-end scripts are all registered in scripts called only on the front-end. I think the only way would be to save a transient option including the front-end scripts on front-end page loading and get the transient option via ajax in the back-end. Maybe it will be not the best way, but I don't see other solutions. Then of course you can add all the conditions with nonces ... to save the transient only in specific conditions ...


text:
Q: postgres 9.1 performance parameters To improve the performance, I tuned the parameters shared_buffers and work_mem. Though i tried for different combinations of above parameters, my query taking the same time. I restarted the server when ever the 'shared_buffer' is changed
My Environment is
Postgres 9.1
OS   windows 7
RAM    8GB
I tried shared_buffers for 1gb,2gb and 3gb. But query execution time changes very minimally( in milli seconds)
I am giving the explain plan of query
GroupAggregate  (cost=11100.99..12737.10 rows=50342 width=24) (actual time=181.789..268.733 rows=49829 loops=1)
  ->  Sort  (cost=11100.99..11226.84 rows=50342 width=24) (actual time=181.761..188.323 rows=50000 loops=1)
        Sort Key: (date(t_proof_of_play.play_timestamp)), (date_trunc(''hour''::text, t_proof_of_play.play_timestamp)), t_device_endpoint.venue_hierarchy_id, t_device_endpoint.device_config_id, t_proof_of_play.asset_id
        Sort Method: quicksort  Memory: 5443kB
        ->  Hash Join  (cost=2629.37..7169.41 rows=50342 width=24) (actual time=15.416..112.175 rows=50000 loops=1)
              Hash Cond: (t_proof_of_play.device_endpoint_id = t_device_endpoint.id)
              ->  Bitmap Heap Scan on t_proof_of_play  (cost=2628.28..6224.41 rows=50342 width=20) (actual time=15.332..29.004 rows=50000 loops=1
                    Recheck Cond: ((is_processed = 0) AND (is_revenue = 1))
                    -> Bitmap Index Scan on process_revenue  (cost=0.00..2615.69 rows=50342 width=0) (actual time=15.081..15.081 rows=50000 loops=1)
                          Index Cond: ((is_processed = 0) AND (is_revenue = 1))
              ->   Hash  (cost=1.04..1.04 rows=4 width=12) (actual time=0.026..0.026 rows=4 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 1kB
                    ->  Seq Scan on t_device_endpoint  (cost=0.00..1.04 rows=4 width=12) (actual time=0.009..0.015 rows=4 loops=1)
Total runtime: 276.027 ms

Tabulated version on explain.depesz
The suggestions are welcomed.
Thanks in advance
regards

A: As @RichardHuxton points out, you are retrieving results at about 5 microseconds per row. It's hard to complain too much about that; but that rate proves that you have a very high cache hit ratio. You might want to try adjusting the cost factors on a connection to reflect that (using the SET command), and try the query again to see if you get a better plan.
SET cpu_tuple_cost = 0.03;
SET random_page_cost = 1;
SET effective_cache_size = '4GB';
-- (your query here)

Of course, @regilero is right about shared_buffers -- on Windows it must be kept small
Even fairly simple queries rarely take less than 2 microseconds per result row, so on a query with a join, a sort, and an aggregate you don't have a whole lot of room for improvement.

A: It can be difficult to pick out the important figures from a raw EXPLAIN. Luckily, a long-time community member built a useful tool to tabulate it for us - I added a link to depesz.com.
Firstly, I can't see how changing shared_buffers would have any effect on any particular query and in any case you didn't provide values. It's a general value to change the overall balance of memory usage on the machine. You would tune it based on the overall workload rather than a particular query.
The three major parts of the query are the join, the sort and the aggregate. That seems reasonable.
I don't know what aggregate you're running (you didn't give the query). Presumably you're summarising over day/hour on play_timestamp (based on the sort). Do you need both levels?
For your fairly detailed sort (5 columns, two based on function-calls) as long as work_mem is big enough for the sort there's nothing much to do there.
So - we might be able to improve the join. It's possible that a partial index might help. Something like:
CREATE INDEX idx1 ON t_proof_of_play (device_endpoint_id) WHERE is_processed=0 AND is_revenue=1

Of course, nothing is free and you'll be paying the maintenance costs on this index whenever you update t_proof_of_play.
Even then, if you halve the join-time that is only going to reduce the overall time from 276ms to about 235ms. You're processing 50,000 rows in about 0.25 of a second - that's 5 micro-seconds per row.

A: In complement to @Richard Huxton answer.
As stated in the documentation on Windows you cannot use a very high amount of shared_buffers:

Also, on Windows, large values for shared_buffers aren't as effective. You may find better results keeping the setting relatively low and using the operating system cache more instead. The useful range for shared_buffers on Windows systems is generally from 64MB to 512MB.

So you should set this parameter to 512MB, PostgreSQL will not be able to optimize his memory usage with more shared memory on Windows. In my mind Windows is not the best OS for a PostgreSQL server, anyway you could also try to tweak effective_cache_size to 50% or 75% of available memory (so maybe something like 2 or 4GB). This is a hint for PostgreSQL, telling it the OS will certainly use available RAM to store recently used files. This way your query optimizer will maybe decide that accessing disk data is not as costly as it usually think.


text:
Q: Why friction between two smooth surfaces is high? If we place two smooth surface one over the other why friction increases or becomes high ?

A: It depends on the surfaces how high the friction becomes.
If they are smooth and clean enough how do they "know" that they are separate surfaces? It is possible for them to actually weld into a a single part. Although this is difficult to achieve in practice - it is annoying when you don't want it to happen.

A: If the two surfaces of the same material are very smooth, the molecules and atoms of one surface get closer to the molecules and atoms of the other surface. As they get closer the molecular cohesive forces begin to take effect and the two surfaces will actually stick to each other. If the surfaces are rough there are far fewer molecules that are close but the rough surface against another rough surface causes friction as in two bricks rubbing against eachother. You can try this with two polished surfaces of metal or glass.


text:
Q: Why do I get product details ONLY from the first web page instead of all the 25pages I have a python script I divided into different functions. My first function 'get_url' is supposed to get the product url after the user have inputted the required product name in the prompt. I want to get the product details in all the pages of the site. Now when i run my code, I get product details ONLY from the first web page instead of all the 25pages. please help @Nathan Mills
HERE'S MY CODE BLOCK
from selenium import webdriver

import time

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.common.by import By

import pandas as pd

def get_url(product):
    for x in range(1, 26):
        product = product.replace(' ', '%20')
        template = 'https://www.konga.com/search?search=={product}&page=={x}'
        url = template.format(product, x)
        return url

def get_all_products(nest):
    name = nest.find_element(By.CLASS_NAME, 'af885_1iPzH').text.strip()
    current_price = nest.find_element(By.CLASS_NAME, 'd7c0f_sJAqi').text.strip()
    reviews = nest.find_element(By.CLASS_NAME, 'eea9b_1Ma8-').text.strip()
    product_info = (name, current_price, reviews)
    return product_info

def main(product):
    product_list = []
    url = get_url(product)

    service = Service(executable_path="C:/driver/chromedriver_win32/chromedriver.exe")
    driver = webdriver.Chrome(service=service)
    driver.get(url)
    driver.maximize_window()
    time.sleep(5)

    product_cards = driver.find_elements(By.CLASS_NAME, 'bbe45_3oExY')
    time.sleep(5)

    for everyCard in product_cards:
        productDetails = get_all_products(everyCard)
        product_list.append(productDetails)

    col = ['Product_Name', 'Current_Price', 'Product_Reviews']
    df = pd.DataFrame(product_list, columns=col)
    df.to_csv("C:\\Users\LP\Documents\MainTest\MainTest.csv", index=False, encoding='utf-8', mode='a')

product = input('Enter Product You Are Looking For : ')

main(product)

A: The function get_url() has a loop that ends with return. So the function stops working after the first cycle. It generates one URL, returns it and that's all it does.
To fix that you can collect all urls into a variable inside the function and return it or change return to yield. This yield will turn your function into a generator and you can use it as a list.
Also I changed the line url = template.format(product, x) to url = template.format(product=product, x=x) as it was not working.
So the code with yield is the following:
from selenium import webdriver

import time

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.common.by import By

import pandas as pd

def get_url(product):
    for x in range(1, 26):
        product = product.replace(' ', '%20')
        template = 'https://www.konga.com/search?search={product}&page={x}'
        url = template.format(product=product, x=x)
        yield url

def get_all_products(nest):
    name = nest.find_element(By.CLASS_NAME, 'af885_1iPzH').text.strip()
    current_price = nest.find_element(By.CLASS_NAME, 'd7c0f_sJAqi').text.strip()
    reviews = nest.find_element(By.CLASS_NAME, 'eea9b_1Ma8-').text.strip()
    product_info = (name, current_price, reviews)
    return product_info

def main(product):
    product_list = []
    url = get_url(product)

    for one_url in url:
        service = Service(executable_path="C:/driver/chromedriver_win32/chromedriver.exe")
        driver = webdriver.Chrome(service=service)
        driver.get(one_url)
        driver.maximize_window()
        time.sleep(5)

        product_cards = driver.find_elements(By.CLASS_NAME, 'bbe45_3oExY')
        time.sleep(5)

        for everyCard in product_cards:
            productDetails = get_all_products(everyCard)
            product_list.append(productDetails)

        col = ['Product_Name', 'Current_Price', 'Product_Reviews']
        df = pd.DataFrame(product_list, columns=col)
        df.to_csv("C:\\Users\LP\Documents\MainTest\MainTest.csv", index=False, encoding='utf-8', mode='a')
        driver.quit()

product = input('Enter Product You Are Looking For : ')

main(product)


text:
Q: Nested routes on static route prefix for Ruby on Rails New to Ruby on Rails and can't get my routes to work how I want them to. Basically, I have two api endpoints: One is for one of the platform services I offer, and the second is for a child platform I'd like to offer next.The resulting URL schemes I want are
...com/api/ # First API platform
...com/stubs/api # Second API platform
The second API platform has resources, but there are no specific resources for "subs" or "api". I am just using that as delineation between the products.
Here is what my routes.rb looks like:
# routes.rb
Rails.application.routes.draw do

  resources :auth

  match :api, to: 'api#index', via: :all

  match :stubs, to: 'stubs#index', via: :get

  match 'stubs/api', to: 'stubs/api#index', via: :get
  scope  'stubs/api' do
    resources :enpoints
  end

end

and then my Controllers...
# controllers/stubs/api/endpoints_controller.rb
class Stubs::Api::EndpointsController < ApplicationController
    def index
        render :json => {}
    end
end

When I try to render /stubs/api/endpionts I get the error:

No route matches [GET] "/stubs/api/endpoints"

My apologies in advance if this is a bad noob problem, bu the articles I found didn't seem to resolve the issue.... Likely because I am thinking of it wrong from the ground up? In any case, thanks for your help in advance!
And even more confusing my routes show the endpoint is there as expected:
UPDATE
Adding my folder structure too in case that helps.

How is this a possible result page????

A: try below routes in route.rb file:
# routes.rb
Rails.application.routes.draw do
  namespace :stubs do #use namespace instead of scope
    namespace :api do
      resources :enpoints
    end
  end

  resources :auth

  match :api, to: 'api#index', via: :all

  match :stubs, to: 'stubs#index', via: :get

  match 'stubs/api', to: 'stubs/api#index', via: :get

end


text:
Q: parsing attribute of tag iphone sdk i've got this error after parsing.
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString stringValue]: unrecognized selector sent to instance 0x4b68480'
Code is
-(void)parser: (NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if([elementName isEqualToString:@"gallery"]){

}
else if ([elementName isEqualToString:@"asset"]){

    NSString *str ;
    str = [[attributeDict objectForKey:@"type"] stringValue];     <- HERE
    NSLog(@"type = %@",str);
    str = [[attributeDict objectForKey:@"thumbnail"] stringValue];      <- HERE
    NSLog(@"thumbnail = %@",str);
    str = [[attributeDict objectForKey:@"large"] stringValue];        <- HERE
    NSLog(@"large = %@",str);

}
 NSLog(@"Processing Element: %@",elementName);

}
XML tree looks like
"<"gallery ...">"
"<"asset type="image" thumbnail="/..." large="/..." ">"
...
Thank you for help!

A: The error tells obviously [attributeDict objectForKey:...] is returning NSString already. So, you do not have to call stringValue to store into str. i.e., instead of
str = [[attributeDict objectForKey:@"type"] stringValue];

you can just do
str = [attributeDict objectForKey:@"type"];


text:
Q: Pipe password argument to mount shell command Status quo
Given are following /etc/fstab mount points:
//server/app /home/user/server/app cifs noauto,user,vers=3.11  0 0
//server/code /home/user/server/code cifs noauto,user,vers=3.11  0 0

These are to be mounted with user priviledge (without sudo). Given user is logged in, password currently is interactively prompted - no credentials file and no hardcoded password in /etc/fstab.
In addition: all shares have the same credentials user with same password.
What is the problem?
Let's say, we want to mount all shares at startup. For share app:
mount ~/server/app # `user` is active
# password interactively requested
Password for user@//server/app:  (press TAB for no echo)

The problem is, I would have to type the same password for all shares, since it won't be cached.
What I tried
# type password once and store it in process memory
echo "Enter password for mounts:"
read -s mount_pass
[[ -z "mount_pass" ]] && echo "Password empty, exiting" && exit

# mount all shares - how to feed every mount command with given password?
mount ~/server/app
mount ~/server/code

# My attempts
echo $mount_pass | mount ~/server/app
mount ~/server/app < <(echo $mount_pass)

(Excuse my superficial shell knowledge)
Is there a way to pass the password stored in $mount_pass to mount command, so that it can be automatically read by its standard input and no interactive prompt is opened?

A: It seems, mount via /etc/fstab always wants to read the password interactively from the terminal device and there is no solution to pipe it via standard input.
Here is a workaround making use of GNOME Keyring/secret-tool and the sudo -S option to pass the password via stdin.

*

*Store the password in the keyring:

secret-tool store --label='share app credentials' share app
# then input your password

*Mount the share

secret-tool lookup share app | sudo -S mount -t cifs \
 -o username=bela,password=$(secret-tool lookup share app),vers=3.11,uid=bela \
 //share/app ~/local/share/app
# share := attribute, app := value

The caveat is, we have to use mount with elevated priviledges. The local sudo credentials are assumed to be equal to the remote share server credentials.


text:
Q: Express API | Heroku - JWT (error - secret or private key must have a value) I deployed my API to Heroku and when I try to use it (login). I get some errors.
my code -
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");

// IMPORT FILES

const user = require("./routes/user");

// MONGOOSE CONNECTION
mongoose.connect(
  "CONNECTION URL HERE",
  { useNewUrlParser: true },
  () => {
    console.log("Connected to DB");
  }
);

// MIDDLEWARE CONFIGS
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
mongoose.Promise = global.Promise;

// ROUTES REDIRECTION

app.use("/", user);

// SERVER
const server = app.listen(process.env.PORT || 8080, () => {
  const port = server.address().port;
  console.log(`Server is running on port ${port}`);
});

JWT FILE
const jwt = require("jsonwebtoken");

module.exports = function (req, res, next) {
  const token = req.header("token");
  if (!token) return res.status(401).send("please login again");

  try {
    const verify = jwt.verify(token, "JWT SECRET HERE");
    req.user = verify;
    next();
  } catch (err) {
    res.status(400).send("invalid token");
  }
};

Some pictures of errors-
Error in Heroku logs --tails
error is browser
PS: i had .env for the variables but took 'em out for delpoyment's sake as I was getting Application error.
thank you! help is appreciated.

A: Have you added your environment variables to heroku config vars?
If not then follow the heroku documentation to do so.
https://devcenter.heroku.com/articles/config-vars
You can use the heroku cli or use the heroku dashboard to add the variables. Refer the docs for a detailed explanation.


text:
Q: Send push notification to user when they go to certain location [IOS] So I'm using Parse for my back-end. I basically want to be able to send a user a push notification when the user enters a certain location. Let's say, When i go into town i'd like to get a notification saying "Welcome to Town" or something like that. Is this possible to do on ios and with parse?

A: What you want isn't a push notification. Look at UILocalNotification.region and the CLRegion class.


text:
Q: Sharing multiple variables between methods in Java What is the best way to pass multiple variables between methods? I have done it one way in which there is a return statement in the first method, but I want to access every variable from the first method in the second method. The variable "value0" in method "addTasks0" is not recognized.
public Integer addValues(){
int value0 = sliderExample.getValue();
int value1 = sliderExample1.getValue();
int value2 = sliderExample2.getValue();
int value3 = sliderExample3.getValue();
int value4 = sliderExample4.getValue();
int value5 = sliderExample5.getValue();
int value6 = sliderExample6.getValue();
int value7 = sliderExample7.getValue();
int totalValue = (value0 + value1 + value2 + value3 + value4 + value5 + value6 +     value7);

return totalValue;
}

public void addTasks0(){
    Integer totalValue = addValues();

      if (totalValue <= 100) {
      progressBar.setValue(value0);
  }
  else{
      int overkill = (totalValue - 100);
      int margin = (value0 - overkill);
      String taskTitle = inputText.getText();
      String marginmessage = "The maximum priority of " + taskTitle + " is" + Integer.toString(margin) + "%";
      sliderExample.setValue(0);
          //custom title, warning icon
    JOptionPane.showMessageDialog(null, marginmessage, "Check Math", JOptionPane.WARNING_MESSAGE);
  }
}

A: In your code you are showing that you have still access to the sliderExample in the addTasks0 method, so as in addValues you can again do
int value0 = sliderExample.getValue();

in the addTasks0 method.  You do not need to pass the value.
However if you really want to you could return an int array from addValues where arr[0] == value0 and arr[1] == totalValue
or of course you could just move these variables as class fields

A: You could define your variables in the beginning of your class so that they are accessible to all methods of the class.
class ClassName {
    private int value0, value1, value2...;

    public Integer addValues() {
        value0 = sliderExample.getValue();
        value1 = sliderExample1.getValue();
        value2 = sliderExample2.getValue();
        // etc.
    }

    public void addTasks0() {
        Integer totalValue = addValues();

        if (totalValue <= 100) {
            progressBar.setValue(value0)    // Initialized in addValues method
        }

A: I would do it this way
ArrayList<SliderExample> sliderExamples = new ArrayList<>();

public int addValues() {
    int sum = 0;
    for(SliderExample se: sliderExamples) sum += se.getValue();
    return sum;
}

public void addTask(int taskNr) {
    SliderExample se = sliderExamples.get(taskNr);
    int value = se.getValue();
    ...
}

A: You can try to pass in a list of key value pairs where each function can access the requisite data by using a specific key name
Map<String key,Object value) params;
...
funcA(Map params){
 params.add(somePredefinedKey,newProperty);
...
funcB(params);
}

funcB(Map params){
Object paramA=params.get(somePredefinedKey);

...
    }
This is particularaly useful if you are passing your parameters through multiple methods in sequence


text:
Q: Homology question and reduced homology I'm looking at rotman, page 103. May someone elaborate why the following holds:
Since $H_0(X)\cong \tilde{H}_0(X)\oplus \mathbb{Z}$ then $H_0(X)\cong \tilde{H}_0(X,x_0)$..
Does the following more general result hold:
If $F$ is free abelian and $F\cong F'\oplus \mathbb{Z}$, where $F'$ is abelian then $F\cong F'$?
May someone elaborate on why either holds?

A: Does the following more general result hold:
If $F$ is free abelian and $F\cong F'\oplus \mathbb{Z}$, where $F'$ is abelian, then $F\cong F'$?
No. Take $F = \mathbb Z \oplus \mathbb Z$ and $F' = \mathbb Z$. I am sure you mean

If $F$ is free abelian and $F \oplus \mathbb Z \cong F'\oplus \mathbb{Z}$, where $F'$ is abelian, then $F\cong F'$?

Here the answer is yes. $G= F\oplus \mathbb Z$ is free abelian and $F'$ embeds as a subgroup into $G$, thus $F'$ is free abelian. If $F$ has finite rank $n$, then $G$ has rank $n+1$, thus $F'\oplus \mathbb{Z}$ has rank $n+1$ and we conclude that $F'$ must also have rank $n$.  Similarly, if $F$ has infinite rank, then $G$ has the same rank rank as $F$ and so has $F'\oplus \mathbb{Z}$. We conclude that $F'$ has the same rank as $F$.
Now look at the exact sequence
$$\ldots \to H_0(x_0) \to H_0(X) \to H_0(X,x_0) \to 0 .$$
This gives a split exact sequence
$$0 \to H_0(x_0) \to H_0(X) \to H_0(X,x_0) \to 0 $$
since the unique map $c : X \to \{x_0\}$ induces a right inverse for $H_0(x_0) \to H_0(X)$. We conclude
$$\tilde{H}_0(X)\oplus \mathbb{Z} \cong H_0(X) \cong H_0(X,x_0) \oplus H_0(x_0) \cong H_0(X,x_0) \oplus \mathbb Z$$
which implies
$$\tilde{H}_0(X) \cong H_0(X,x_0) .$$

A: Note that $x_0$ is a retract of $X$. Hence $H_0(X)\cong H_0(X,x_0)\oplus H_0(x_0)$ . Since singletons are path connected, $H_0(x_0)\cong \mathbb{Z}$, and so we have $H_0(X,x_0)\oplus H_0(x_0)\cong H_0(X,x_0)\oplus \mathbb{Z}$. Now, as you've shown, we have $H_0(X)\cong \tilde{H}_0(X)\oplus \mathbb{Z}$. In particular we have the following isomorphisms:
$H_0(X)\cong H_0(X,x_0)\oplus \mathbb{Z}\cong \tilde{H}_0(X)\oplus \mathbb{Z}$ .
Since $H_0(X,x_0)$ is free abelian, the result follows.


text:
Q: Generate Jupyter Notebook password without Python Following https://jupyter-docker-stacks.readthedocs.io/en/latest/using/common.html#docker-options you can define your own password for starting Jupyter Notebook when using docker image.
docker run -d -p 8888:8888 jupyter/base-notebook start-notebook.sh --NotebookApp.password='sha1:74ba40f8a388:c913541b7ee99d15d5ed31d4226bf7838f83a50e'

I can only find that the used salted sha1 password can be generated using IPython.lib.passwd(). But, how to generate it without using Python? I do not have IPython or maybe just do not know how to use it. I am on CentOS Stream.

A: You can approximate the original password generation algorithm with the following small shell script:
#!/bin/bash

passphrase="hello, world"

# generate salt
salt=$(openssl rand -hex 6)

# generate hash
algorithm=sha1
echo -n "$(echo ${passphrase} | iconv -t utf-8)${salt}" | openssl dgst -${algorithm} | awk -v alg="${algorithm}" -v salt="${salt}" '{print alg ":" salt ":" $NF}'

Why does this work (sort of)?
You mentioned that the original password generating algorithm is based on IPython.lib.passwd which is actually implemented in IPython.lib.security. The relevant code portions are:
salt_len = 12

h = hashlib.new(algorithm)
salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii'))

return ':'.join((algorithm, salt, h.hexdigest()))

In order to understand what this code does, it is useful to first look at the produced output once again. From your question, we have an example of the generated password:

sha1:74ba40f8a388:c913541b7ee99d15d5ed31d4226bf7838f83a50e

The colons divide this string into three parts:
<hashing-algorithm> : <salt> : <hashed salted passphrase>

With that in mind, let's go through the IPython code. At the top, we define the number of characters used for the salt. Let's double check - yes, indeed, in your example the salt consists of 12 characters: 74ba40f8a388.
Next, a new instance h of a hashing algorithm is created. As we know from your example, the value for the algorithm parameter is "sha1".
After that, a random salt is generated. Now this line is interesting. If you don't have a Python background, the percentage sign (%) might remind you of an integer modulo operator. But in fact, it is not, because the parameter left of the percentage sign is of type string. So, rather, this is (now kind of obsolete) Python syntax for formatting a string, quite similar to printf in C, except that you're not limited to printing in Python, you can use this formatting operation anywhere you have a string.
Given that we know that salt_len is 12, this line basically reduces to:
salt = '%012x' % random.getrandbits(48)

which means that the salt should be a bit string of 48 bits, formatted as a 12 digit hexadecimal string.
Why 48 bits? Well, you need two hexadecimal character to encode a single byte (0x00 through 0xff), so if we're aiming for 12 characters, we need 6 bytes = 48 bits.
The last line before the return applies the sha1 algorithm to the concatenation of the utf-8-encoded passphrase and the ascii-encoded salt.
Finally, the algorithm, the salt, and the hashed salted passphrase are returned as a concatenated string with colons (:) as separators.
Now, if you inspect the shell script I posted above you will find more or less the same steps in there as well. But there is a notable difference, and that's why I wrote initially that it is just an approximation of the actual algorithm.
The difference is in the way the salt is generated. Although the result is in both cases a 12-digit hexadecimal string, the IPython code uses an implementation of the Mersenne-Twister, while my script is based on MD5 hashing. This will result in different cryptographic properties.
But you can decide for yourself whether it is acceptable or not. Unfortunately, I was not able to source an implementation of the Mersenne Twister that's available just from the command line. But if you know of a good alternative for generating the salt, feel free to update the script. The remainder of it should not be affected.

Alternatively, if you prefer a solution without openssl, you could also use this version:
#!/bin/bash

passphrase="hello, world"

# generate salt
salt=$(tr -dc a-f0-9 < /dev/urandom | head -c 12)

# generate hash
algorithm=sha1
echo -n "$(echo ${passphrase} | iconv -t utf-8)${salt}" | sha1sum | awk -v alg="${algorithm}" -v salt="${salt}" '{print alg ":" salt ":" $1}'

But unfortunately, I cannot state anything about the properties of a salt generated via /dev/urandom this way.


text:
Q: Executing a script remotely through ssh using expect I am new to using expect. I try the code below and it fails:
expect -c 'spawn ssh user@host < script.ecma3
expect Password: ;
send "******\r";
send "exit\r";'

anyone could clarify

A: This might help you
#!/usr/bin/expect
set timeout -1

spawn -noecho bash -c "ssh -t user@host '<here-comes-your-command>'"

expect {
  -re ".*assword.*" {
    exp_send "$env(PASS_WORD)\n"
    exp_continue
  }
}

Note :-
1) Copy script to remote host before running it. passing whole script is not good thing to do.
2) to access enviornment variables in expect , $env(variable_name) is used.
In above example , for $PASS_WORD, i used $env(PASS_WORD) .


text:
Q: Compactness of spaces Which of the following metric spaces $X$ are compact?
(a) Let $S$ is an infinite set, let $X$ be $\{ f:S \rightarrow \mathbb{R} \mid \| f\|_\infty \leq 1 \}$ equipped with sup norm
$$\|f-g\|_\infty = \sup_{s\in S}|f(s)-g(s)|.$$
(b) $X = \{(x_1,x_2,...) \mid x_n \in [0,\frac{1}{n}] \}$ with $l^2$ norm
$$d(x,y)=\sqrt{\sum(x_i - y_i)^2}.$$
To clarify what I have tried for (b), here is my attempt. I believe that there is a slicker method.
Proof. Let $((x_n)^{(k)})_{k\geq1}$ be a sequence in $X$. Consider $((x_1)^{(k)})_{k\geq1}$, since $[0,1]$ is compact, there exists a convergent subsequence $((x_1)^{(k_1)})_{k_1\geq1}$ which converges to $x_1$. Now consider $((x_2)^{(k_1)})_{k_1\geq1}$, similarly there exists a convergent subsequence $((x_1)^{(k_2)})_{k_2\geq1}$ which converges to $x_2$. Iterate this process.
We claim that the following subsequence $((x_n)^{(k_l)})_{l\geq1}$
$$(x_n)^{(k_1=1)}, (x_n)^{(k_2=2)}, (x_n)^{(k_3=3)}, ...$$
of the original sequence $((x_n)^{(k)})_{k\geq1}$ converges to $(x_n)$. Let $\epsilon > 0$, let $N$ be large so that
$$\sum _{n=N}^{\infty}\frac{1}{n^2} < \epsilon.$$
For $M$ large enough, for all $1 \leq i \leq N$,
\begin{alignat}{1}
  m \geq M
    &\implies |x_i^{(l_m)}-x_i|^2 < \frac{\epsilon}{i^2}\\
    &\implies \sum_{i=1}^N |x_i^{(l_m)}-x_i|^2 \ <
      \ \sum_{i=1}^N\frac{\epsilon}{i^2}\ \leq \ \epsilon \frac{\pi^2}{6}\\
    &\implies \sum_{i=1}^{\infty} |x_i^{(l_m)}-x_i|^2\ \leq \epsilon (\frac{\pi^2}{6} + 1).
\end{alignat}

A: Hints:  If you can find an infinite subset $\{a_n\}$ in your metric space such that $d(a_n, a_m) = 1$ for $n \ne m$, then your space is not compact. For part (b) a famous theorem in measure/integration theory may be useful.
Edit: Your proof for part (b) looks fine to me.  You can avoid the estimates as follows:  by Tychonoff, or by your diagonal subsequence argument, there is a subsequence of your original sequence in $X$ that converges pointwise.  But every element in $X$ is bounded in absolute value by the $\ell^2$ sequence $(1/n)_{n \ge 0}$.   Hence by the dominated convergence theorem, pointwise convergence implies $\ell^2$ convergence. But your estimates are not difficult, and in my opinion it is better to do it directly when you can.


text:
Q: Using Linq to merge to List I have the code like this.
public class Employee
{
    public int ID { get; set; }

     public string Name { get; set; }

     public string NickName { get; set; }
}

var table1 = new List<Employee>() {
                new Employee(){ ID=1, Name="A"},
                new Employee(){ ID=2, Name="B"},
                new Employee(){ ID=3, Name="C"},
                new Employee(){ ID=5, Name="E"},
            };
var table2 = new List<Employee>() {
                new Employee(){ ID=1, NickName="NickA"},
                new Employee(){ ID=2, NickName="NickB"},
                new Employee(){ ID=3, NickName="NickC"},
                new Employee(){ ID=4, NickName="NickD"}
            };

I want to merge two lists above to something like this:
{ID=1, Name="A", NickName="NickA"}
{ID=2, Name="B", NickName="NickB"}
{ID=3, Name="C", NickName="NickC"}
{ID=4, Name=null, NickName="NickD"}
{ID=5, Name="E", NickName=null}

How can I do it using LinQ. Please help me out!

A: Something like:
var results = table1.Select(t1 => {
                 var t2 = table2.First(x => x.ID == t1.ID);
                 return new Employee {
                   ID = t1.ID,
                   Name = t1.Name,
                   NickName = t2.NickName
                 };
              }).ToList();

If table2 is sufficiently large (tens of thousands of entries or more) consider (ie. performance measure) building a Dictionary or sort the array  to provide quicker lookup by ID (in the latter case using the BinarySearch method with the custom IComparer just comparing ids). The cost of setting up this intermediate structure is non-trivial, and modern computers can search a few thousand simple rows very quickly.

A: You can group by ID, and pick the "first of" value for each field, like this:
var res = table1.Concat(table2).GroupBy(e => e.ID)
    .Select(g => new Employee {
        ID = g.Key
    ,   Name = g.Select(e => e.Name).FirstOrDefault(s => s != null)
    ,   NickName = g.Select(e => NickName).FirstOrDefault(s => s != null)
    });

Note that if you take this approach it does not matter from what table the Name or the NickName comes: you could mix assignments in your lists, and let LINQ group them back for you.


text:
Q: Why would one autorelease one's own property in Objective-C? Here's a code example to show what I mean:
- (void) setup {
  [self setupObjectModel];
  [self setupStoreCoordinator];
}

- (void) setupObjectModel {
  NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
  self.managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] autorelease];
}

A: In case managedObjectModelis a strongproperty or defined with attribute retain, the setter will automatically retain the passed argument, thus autoreleaseing it will prevent a memory leak (if you don't do it, the retain count of the NSManagedObjectModel will be 2 although only managedObjectModelpoints to it.)
This is equivalent to
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

assuming the setter has the default behaviour


text:
Q: Motion of molecules is random or uniform vibration with a frequency? Every substance has an entropy, entropy is defined as the randomness in a system. There's also a term called molecular vibration which tells the periodic vibration of molecules and gives them a frequency. I've always thought heat of a substance is a property which defines the amount of random movement of the molecules in a substance, if it is random I don't think we can define a frequency to the molecules' movement, but the vibrations defined have a frequency which means they trace the same path again and again, i.e., not random. So my question is do molecules have frequency? If they have, how is entropy defined? Is it different for different states of matter(difference maybe between fluids and solids, I'm not sure)?

A:
I've always thought heat of a substance is a property which defines
the amount of random movement of the molecules in a substance

That is not heat. It is a component of the internal molecular kinetic energy of the substance. Heat is not a thermodynamic property. Heat is energy transfer between substances due solely to temperature difference. The energy transfer can result in an increase or decrease in the internal energy of a substance.

if it is random I don't think we can define a frequency to the
molecules' movement, but the vibrations defined have a frequency which
means they trace the same path again and again, i.e., not random.

Molecular vibrational, as well as molecular rotational kinetic energy is not random motion. Translational kinetic energy is random motion. The total molecular kinetic energy (total internal kinetic energy) is the sum of vibrational, rotational, and translational kinetic energies.

So my question is do molecules have frequency?

Yes, it's there vibrational frequency. See the Wikipedia article on "Molecular vibration".

If they have, how is entropy defined? Is it different for different
states of matter(difference maybe between fluids and solids, I'm not
sure)

Molecular vibration, rotation, and translation are three potential molecular degrees of freedom. The more degrees of freedom, the higher the entropy since increasing the number of degrees of freedom increases the entropy. Only a perfectly ordered, crystalline substance at absolute zero would exhibit no molecular motion and have zero entropy.
The entropy of a substance increases as it undergoes phase changes from a solid, to a  liquid, to gas.

I've one more doubt, what do you mean by more degrees of freedom? Do
you mean magnitude or fourth degree of motion?

I'm referring to the three types or categories of molecular degrees of freedom and their association with entropy. In that respect, a molecule can have potentially have three molecular types of degrees of freedom: translational, vibrational, and rotational, and a total number of 3N degrees of freedom, where N equals the number of atoms in the molecule. For example, in the case of a monatomic gas where $N=1$, rotational and vibrational modes do not apply, only translational. Thus the number of degrees of freedom is 3 for motion in 3 dimensions of space. I'm no expert on all the details, so I suggest you check out "Modes in Polyatomic Molecules" on the chem.librexts.org web site or other resource.
In any case, these three types of molecular degrees of freedom are ways in which molecules can store energy. The greater the molecular motion of a system, the greater the number of possible microstates and the higher the entropy.

hi, just a clarification. I thought all the atoms of molecule have the
same molecular vibration, does each atom have different molecular
vibration?

It can be different, it depends on the molecule. For example, there are three possible vibration modes in a non linear triatomic molecule: 1.symmetrical stretching, 2. asymmetrical stretching, and 3. scissoring (bending). You can see an animation of these by looking up "Particle Model of Thermal Energy" on the phy.libretexts.org website.

If there's only one atom in molecule why doesn't vibrational modes
doesn't apply? I thought all atoms and molecules always vibrate unless
it's 0K temperature

Molecular vibration motion is due to atoms bonded to each other within a molecule having certain freedom of movement relative to each other. Think of a diatomic (two atom) gas with a spring connecting the two atoms and the two atoms oscillating.  A monatomic molecule only has one atom so there can be no relative movement between atoms of a monatomic molecule.
Hope this helps.

A: Molecules can vibrate with one or more frequencies , given the energy  and move around, some of the energy goes to oscillation, but you can  run around randomly  and move you head or arm with some fixed frequency


text:
Q: Populate UITableView with list of files from Documents Directory in iPhone SDK 5.0 I am developing for iOS 5. What I would like to do is read the list of files in my app's Documents Directory and list them in the UITableView. I found an article on StackOverflow, but the API's used have been deprecated. Any ideas on what to do here?

A: You can insert the files of the directory into an NSArray and list them in the cells like this:
cellForRowAtIndexPath:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileListAct = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];

cell.textLabel.text = NSString stringWithFormat:@"%@",[fileListAct objectAtIndex:indexPath.row]];

This still works in iOS5 and has not been deprecated.


text: Q: Practice avoiding off-by-one errors? I feel that I am quite bad at reasoning about boundary conditions in loops. I make a lot of mistakes and usually have off by one errors. Is there any way/site where i can practice problems related to corner cases/boundary conditions?


text:
Q: Changing the Audio Source of a Player in a NextJS App I have two functional components written in a NextJS (React) app. One of the components provides a 'select track from a tracklist' fn and the other component - the player component - has a custom HTML5 audio element where the source, src, is updated by the track selected on the tracklist component, via a Context hook.
The problem is that although (I think) the src is updated 'onClicking' a track from the tracklist, there is no call to the .load() method after a new track is selected, which is probably why the src doesn't actually change - if you press play the same initialised track will continue to play:

*

*On page load, the initialised track will play (when I click play). If I select a new track, the same initialised track will continue playing if I press play (even though I selected a new track) - clearly, the src for the audio element has not actually updated.

Here is the interpolated string which 'should' update the value of src:
/[..]/[..]/${track}.mp3
I 'think' that the path is right because I can console.log track and it is does correctly update onClick. But it seems that the player is not actually updating its source src when the user selected a new one.
How can the source be updated?
As an aside: the player has a play button and a pause button. Clicking either triggers a separate function. Is there a way to create hooks for play and pause? e.g. via useState or useEffect?

Code:
// the component will receive the user-selected {track} onClick
export default function MusicPlayer() {

  const { track } = useContext(AudioContext);

  function play() {
    var audio = document.getElementById("a1");
    audio.play();
  }

  function pause() {
    var audio = document.getElementById("a1");
    audio.pause();
  }

// ... /
  return (
    <audio id="a1">
          <source
            src={track}
            type="audio/mpeg"
          />
    </audio>

The following code will create an Audio element on a NextJS app:
  const [audio, setAudio] = useState(null);
  useEffect(() => {
    setAudio(new Audio(URL));
  }, []);

The challenge I see it is to set the src (i.e. the URL parameter) via the Context hook, but I'm not entirely sure how!
The context is essentially this:
const [trackToPlay, setTrackToPlay] = useState("Track-1");
const changeTrack = (chapter) => setTrackToPlay(chapter);

The below code shows how track can be selected from a list of tracks.
{[
    { chapter: "1" },
    { chapter: "2" },
              ].map((d) => (

 changeTrack(d.chapter)}>
                    {d.chapter}{" "}

))}


text:
Q: PHP Short Open Tag prints "1 " When i write php code with html using php short open tag, it prints 1 every time.
<?= include_once 'includes/footer.php';?>

Why it's happening ?

A: Because it returns true. You need to use include_once without the short open tag, so like this:
<?php include_once 'includes/footer.php';?>

When you write an open short tag, like this;
<?= include_once 'includes/footer.php';?>

You actually write this:
<?php echo include_once 'includes/footer.php';?>

Which results in "1" on your screen.

A: Php Short Tag is used to echo the variable not for including the file
<?= ?> (echo short tags)

See this http://php.net/manual/en/language.basic-syntax.phptags.php

A: Because include_once return TRUE, so if you print it it will display "1"

A: Just remove the = sign and try. In short tags = used for echo and since you're including the file without any problem it returns 1 and it will be echoed back.


text:
Q: Flutter Web Space button not working on keyboard on IOS I have a Flutter Web app deployed on Firebase.
On chrome and safari everything is fine when on an Android
But on IOS,  the space button does nothing when inputting text in a TextField.
Tried dev, stable and master channel
Even while using this sample code for a CupertinoTextField it has the issue with space button on IOS not working on Flutter Web
https://gallery.flutter.dev/#/demo/cupertino-text-field
C:\Users\Takabayashi\dpp_web>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel master, 2.3.0-13.0.pre.73, on Microsoft Windows [Version 10.0.19042.985], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.2.0)
[√] VS Code (version 1.56.2)
[√] Connected device (2 available)

• No issues found!


text:
Q: How to add a property to a map dynamically in velocity? I have the following code
$pageName = "test";

$Container = {};

I like to set a property of $Container by a variable. I tried $Container.set("test", $pageName);. It didn't raise any errors, but $Container.test or $Container.get("test"); display nothing.
How do I fix it?

A: The problem is that set is the wrong method.  You need to do a put.  Remember - Velocity is calling the Java methods.  There is no "set" method on a Map object.
Specifically, you can do
$Container.put("test", $pageName)

Now, one weird thing is that this will print "true" or "false" in the page, since the Map.put() method returns a boolean.  So I always do
#set($dummy = $Container.put("test", $pageName))

which does the put and stores the result in another reference (which you can then ignore) instead of rendering it to the page.

A: Hey I ran into the same problem is the "true" or "false" printed on the page, and there is a simpler way to handle it.  What I did is a little weird, and I did it Confluence, which of course uses Velocity under the covers.  I mention that because I understand Velocity can be used in may different applications.
With a Confluence user macro, I check for a previously created attribute on the req variable, the request variable, i.e. "myPageVars".  Then I use the put method to put a new key-value pair, based on the macro parameters.  By using the $! prefix, rather than just $, the output isn't sent to the screen.
...
$!req.getAttribute("myPageVars").put( $paramKey, $paramValue )
...
I'm somewhat new to Velocity, so I can't guarantee this will work in every context, but it seems syntactically easier than the whole #set ($dummy etc. line.


text:
Q: How can I hide moment errors in nodejs? I'm fairly new to both node and javascript so I apologize if this is a tired question, but the solutions I have found in my research so far have not worked for me.
I have the following function that checks if a date string (received from the user as a command line argument) is valid:
var checkDate = (d) => {
    if (isNaN(d) && moment(d).isValid()) {
        return moment(d);
    } else if (!isNaN(d)) {
        return moment(parseInt(d, 10));
    } else {
        console.error(`Error! ${d} is not a valid date string.`);
        process.exit(1);
    };
};

The issue is that if the string is not a valid date, moment(d).isValid() will throw an error.  I would like to not see this error as it really isn't of much use and I am throwing my own under the else anyway.
Is there a way I can suppress the error thrown by the moment().isValid() function?

A: This is an issue with moment that will throw a deprecation warning when the value provided is not in a recognized RFC2822 or ISO format.
To avoid the warning, create a fallback function:
const moment = require('moment');

moment.createFromInputFallback = function (config) {
    config._d = new Date(NaN);
}

const checkDate = (d) => {
    if (isNaN(d) && moment(d).isValid()) {
        return moment(d);
    } else if (!isNaN(d)) {
        return moment(parseInt(d, 10));
    } else {
        console.error(`Error! ${d} is not a valid date string.`)
        process.exit(1);
    };
};

Or you can supress the warning directly with:
moment.suppressDeprecationWarnings = true;


text:
Q: Haskell "parse error on input `=>' " first :: (a,b,c) -> a
first (x, _, _) = x

second :: (a,b,c) -> b
second (_,y,_) = y

third:: (a,b,c)-> c
third (_,_,z) => z

I got error message from this piece of code.
"parse error on input `=>'
"

I cannot see any reason. Could anyone help me to point out?
thanks.

A: You used bad lexeme: in first and second = and in third =>. Replace it with =.