text:
Q: Getting java.net.SocketTimeoutException alwayse in downloading files with OkHttp I am using OkHttp to download a file from the server.
And this is my code:
I set read and write timeout for it:
 public static final String API_BASE_URL = "http://XXXX:8080/tablet/";
    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
      .connectTimeout(60,TimeUnit.SECONDS)
      .writeTimeout(60,TimeUnit.SECONDS);

This is my createServiceFile:
public static <S> S createServiceFile(Class<S> serviceClass, final String token) {
        if (token != null) {

            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request original = chain.request();
                    Request.Builder requestBuilder = original.newBuilder()
                      .header("Authorization", token)
                      .header("Accept", "text/html,application/xhtml+xml,application/pdf,application/xml;q=0.9," +
                        "image/webp,audio/mpeg ,image/png,audio/mp4,image/jpeg,*/*;q=0.8")
                      .method(original.method(), original.body());
                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }
        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);
    }

And this is my code that I write the response to SD Card (in response contentLength is -1 because the server doesn't send it to me):
public DownloadRequest DownloadFile() {

    //Creating folder for Application in SD Card if it's not created yet in App Class!
    new java.io.File(G.DIR_APP).mkdirs();
    new java.io.File(G.DIR_MEDIA).mkdirs();

    APIService downloadService = ServiceGenerator.createServiceFile(APIService.class, G.TOKEN);
    downloadService.downloadFileWithDynamicUrlSync(url)//set URL of the  file
      .subscribeOn(Schedulers.newThread())
      .observeOn(Schedulers.io())
      .delay(30, TimeUnit.MILLISECONDS)
      .subscribe(new Observer<ResponseBody>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(ResponseBody responseBody) {

          Log.i(TAG, "On Next And Current App is: " + fileName);

          if (writeResponseBodyToDisk(responseBody)) {

            Log.i(TAG, fileName + "Downloaded successful");

            //This Download was successful Then try to set downloadResult true
            result = true;

          } else {
            result = false;
          }
        }

        @Override
        public void onError(Throwable e) {

          Log.i(TAG, "!!!!!!!!!!!!!!!!\n\nOn Error And Current App is: " +
            fileName + " And Error is" + e.toString() + "\n\n!!!!!!!!!!!!!!!!\n\n");

          //Set downloadResult false
          result = false;
          if (listener != null) {
            listener.onDownloadCompleteListener(false);
          }
        }

        @Override
        public void onComplete() {
          Log.i(TAG, "On Complete And Current App is: " + fileName);

          if (listener != null) {
            if (result) {
              listener.onDownloadCompleteListener(true);
            } else {
              listener.onDownloadCompleteListener(false);
            }
          }

        }
      });

    return this;
  }

And this code will write response to disck:
  private boolean writeResponseBodyToDisk(ResponseBody body) {

    // Location to save downloaded file and filename
    java.io.File file = new java.io.File(destinationPath + fileName + "." + extension);

    try {

      InputStream inputStream = null;
      OutputStream outputStream = null;
      int bytesBuffered = 0;

      try {
        byte[] fileReader = new byte[bufferSize];

        downloadSize = 0;
        inputStream = body.byteStream();

        /*
         * If append requested we have to append new bytes to
         * Exists bytes on the storage
         */
        if (appendNeed) {
          outputStream = new FileOutputStream(file, true);
        } else {
          outputStream = new FileOutputStream(file);
        }

        while (true) {

          int read = inputStream.read(fileReader);
          if (read == -1) {
            break;
          }

          bytesBuffered += read;

          if (bytesBuffered > 1024 * 1024) {
            //  outputStream.write(fileReader, 0, read);
            outputStream.flush();
            bytesBuffered = 0;
          }
          outputStream.write(fileReader, 0, read);
          downloadSize += read;

          percent = (int) (100.0f * (float) downloadSize / totalSize);
          if (listener != null) {
            listener.onDownloadPercentListener(percent);
          }
        }
        outputStream.flush();
        inputStream.close();
        outputStream.close();

        return true;
      } catch (IOException e) {

        Log.i(TAG, "Error in download" + e.toString());
        return false;

      } finally {
        if (inputStream != null) {
          inputStream.close();
        }
        if (outputStream != null) {
          outputStream.close();
        }
      }
    } catch (IOException e) {
      Log.i(TAG, "Error in download" + e.toString());
      return false;
    }
  }

But I get false from this method (writeResponseBodyToDisk)with error of
java.net.SocketTimeoutException while the file is downloaded correctly!
I think this problem it about contentLength that is -1 for me.
Thank you for your answers.


text:
Q: How to to iterate over hrefs with selenium? I've been trying to get all the hrefs of a news article home page. In the end, I want to create something that gives me the n-most used words from all the news articles. To do that, I figured I needed the hrefs first to then click on them one after another.
With a lot of help from another user of this platform, this is the code I've got right now:
from bs4 import BeautifulSoup
from selenium import webdriver

url = 'https://ad.nl'

# launch firefox with your url above
# note that you could change this to some other webdriver (e.g. Chrome)
driver = webdriver.Chrome()
driver.get(url)

# click the "accept cookies" button
btn = driver.find_element_by_name('action')
btn.click()

# grab the html. It'll wait here until the page is finished loading
html = driver.page_source

# parse the html soup
soup = BeautifulSoup(html.lower(), "html.parser")
articles = soup.findAll("article")

for i in articles:
    article = driver.find_element_by_class_name('ankeiler')
    hrefs = article.find_element_by_css_selector('a').get_attribute('href')
    print(hrefs)
driver.quit()

It gives me the first href I think, but it won't iterate over the next ones. It just gives me the first href as many times as it has to iterate. Does anyone know how I make it go to the next href instead of being stuck on the first one?
PS. if anyone has some suggestions on how to further do my little project, feel free to share them as I have a lot of things yet to learn about Python and programming in general.

A: Instead of using beautiful soup, how about this?
articles = driver.find_elements_by_css_selector('article')

for i in articles:
    href = i.find_element_by_css_selector('a').get_attribute('href')
    print(href)

A: To get all hrefs in an article you can do:
hrefs = article.find_elements_by_xpath('//a')
#OR article.find_element_by_css_selector('a')

for href in hrefs:
  print(href.get_attribute('href'))

To progress with the project though, maybe the bellow would help:
hrefs = article.find_elements_by_xpath('//a')
links = [href.get_attribute("href") for href in hrefs]

for link in link:
  driver.get(link)
  #Add all words in the article to a dictionary with the key being the words and
  #the value being the number of times they occur

A: To improve on my previous answer, I have written a full solution to your problem:
from selenium import webdriver

url = 'https://ad.nl'

#Set up selenium driver
driver = webdriver.Chrome()
driver.get(url)

#Click the accept cookies button
btn = driver.find_element_by_name('action')
btn.click()

#Get the links of all articles
article_elements = driver.find_elements_by_xpath('//a[@class="ankeiler__link"]')
links = [link.get_attribute('href') for link in article_elements]

#Create a dictionary for every word in the articles
words = dict()

#Iterate through every article
for link in links:
    #Get the article
    driver.get(link)

    #get the elements that are the body of the article
    article_elements = driver.find_elements_by_xpath('//*[@class="article__paragraph"]')

    #Initalise a empty string
    article_text = ''

    #Add all the text from the elements to the one string
    for element in article_elements:
        article_text+= element.text + " "

    #Convert all character to lower case
    article_text = article_text.lower()

    #Remove all punctuation other than spaces
    for char in article_text:
        if ord(char) > 122 or ord(char) < 97:
            if ord(char) != 32:
                article_text = article_text.replace(char,"")

    #Split the article into words
    for word in article_text.split(" "):
        #If the word is already in the article update the count
        if word  in words:
            words[word] += 1
        #Otherwise make a new entry
        else:
            words[word] = 1

#Print the final dictionary (Very large so maybe sort for most occurring words and display top 10)
#print(words)

#Sort words by most used
most_used = sorted(words.items(), key=lambda x: x[1],reverse=True)

#Print top 10 used words
print("TOP 10 MOST USED: ")
for i in range(10):
    print(most_used[i])

driver.quit()

Works fine for me, let me know if you get any errors.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dual Monitor Problem xrandr Using fluxbox with Linux Mint.
I have this script to set dual screen in fluxbox
xrandr --output DP-1 --off --output DVI-I-1 --mode 1600x900 --pos 1440x0 --rotate normal --output DVI-D-1 --mode 1440x900 --pos 0x0 --rotate normal --output HDMI-1 --off

However my Login screen is not extended
Is there anyway I can set this script to run when the OS start?
Or (if possible)  Boot linux without any desktop manager, start X and initialize fluxbox in command line.

A: You could use
sudo apt-get purge lightdm

and before you accept the changes make sure it is not also going to remove any applications you want to keep or need to use in the process.
Do the same for gdm or gdm3 and any other dm(s) that may still be installed; I've never done it but it should boot to one of the tty screens if no dm is present.
Use the command,
startx

after you login.
dbus should already be started, however, if it's not, you won't be able to start X without it. To start dbus use:
sudo service dbus start


text:
Q: How to Write a Composable AJAX Call in Polymer I am trying to write a component that exposes the data from an AJAX call in Polymer.  I would like to end with something like.
<get-db data={{data}}></get-db>

<template is="dom-repeat" items="{{data}}">
    <div>{{item}}</div>
</template>

However, when I expose the data property from get-db component in another element, the data doesn't bind to the dom-repeat template.

The get-db component parts are as follows

<iron-ajax id="ajax"
  url="https://api/endpoint"
  method="post"
  handle-as="json"
  content-type="application/json"
  body="[[request]]"
  last-response="{{response}}"></iron-ajax>

...
  static get properties() {
    return {

      response: Object,

      request: Object,

      username: String,

      data: Object

    }
  }

  getResponse() {
    if (this.username && this.apiKey) {
      this.request = {
        "body": "bodyText"
      };
      let request = this.$.ajax.generateRequest();
      request.completes.then(req => {
        this.setResponse();
      })
      .catch(rejected => {
        console.log(rejected.request);
        console.log(rejected.error);
      })
    }
  }

  setResponse() {
    if(this.response[0]) {
      this.data = this.response[0];
    }
  }

A: The data property needs to be set to notify.
 data: {
   type: Object,
   notify: true
 }

A: You need to add notify but also you need to use this.set method in order to get observable changes for data properties. Also you are setting only one item to data properties (assuming you have a array at response properties.) I guess you need all array instead only 0. index as you are looping in dom-repeat. That's why this below code may help:
static get properties() {
    return {

      response:{
         type:Object,
         observer:'checkResponce'},

      request: Object,

      username: String,

      data: {
         type:Array,
         notify:true}

    }
  }
 static get observers() { return [ 'checkUserNApi(username,apiKey)']}

  checkUserNApi(u,a){
      if (u && a) this.$.ajax.generateRequest();
  }
  checkResponce(d) {
      if (d) {
          this.set('data',d); //with this method data property at parent will change upon you received responce
      }
  }

Finally, you may add to iron-ajax  a line check error on-error="{{error}}" if you want to see an error report.
DEMO


text:
Q: How do I center a dynamic number of divs using bootstrap? I am dynamically displaying either 3 or 4 divs that need to be centered within a container div. How do I ensure that the divs are always centered given their static bootstrap column values?

foo

bar

foo

bar

A: it looks like you're pairing this with AngularJS
in which case you can apply a ternary operator on ng-class to your
s so that they dynamically change class based upon the state of settings.isShown:

foo

bar

foo

bar

This solution assumes you are on Angular 1.1.5 or higher (they only added ternary operator support since then)
For other options on applying conditional classes to elements with AngularJS see https://stackoverflow.com/a/12151555/648350


text:
Q: Custom login route in Laravel How do i alter the default login route within Laravel as it seems to be defaulting to /login when i would like to be using /account/signin to keep my system catagorised.

A: There's only one reference to a route 'login' in Laravel source code, but it is in your  app/filters.php file and this file is yours:
Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::guest('login');
});

So you can change it whenever you need to:
Route::filter('auth', function()
{
    if (Auth::guest()) return Redirect::guest('account/signin');
});


text:
Q: Convert does in shell, but not in shell_exec There seem to many related questions and after trawling through many of them I still cannot seem to find a solution.
Executing the following in a shell does the trick:
/usr/local/bin/convert -trim -density 300 /Users/fullpath/file.pdf /Users/fullpath/file.png
yet doing it in a php file as follows:
    <?php
    putenv("PATH=/usr/local/bin:/usr/bin:/bin");
    echo shell_exec('/usr/local/bin/convert -trim -density 300 /Users/fullpath/file.pdf /Users/fullpath/file.png  2>&1');
    ?>

doesn't. The error message displayed is:

convert: UnableToCreateTemporaryFile
  `/Users/fullpath/file.pdf': Permission denied

My specs are:
Mac: snow leopard
Running Apache, through localhost.
Obviously it is a permissions problem, but where? The file itself and associated folders are all at 777.

A: this seems very odd, but can you try setting a specific temporary?
Try this code, where I just added a new environment variable setting the temporary dir to /tmp (you can try another locations):
<?php
putenv("PATH=/usr/local/bin:/usr/bin:/bin");
putenv("MAGICK_TEMPDIR=/tmp");
echo shell_exec('/usr/local/bin/convert -trim -density 300 /Users/fullpath/file.pdf /Users/fullpath/file.png  2>&1');
?>


text:
Q: Role handling in JDA Java Discord API I'm learning Java at the moment by coding a discord bot using JDA. Now I just can't figure what my mistake is using the Role entitiy.
    if (content.equalsIgnoreCase("$addrole")){
            channel.sendMessage("Please select the role you want!\n\n\u2694\uFE0F\tFighter\n\uD83D\uDEE1\tTank").queue(message -> {
                message.addReaction("\u2694\uFE0F").queue();
                message.addReaction("\uD83D\uDEE1").queue();
            });

            //Role role = event.getGuild().getRolesByName("@everyone", true).get(0);

            if (event.getGuild().getRolesByName("fighter", true).isEmpty()){
                role1 = event.getGuild().createRole().setName("Fighter").setPermissions(0L).complete();
            } else {
                System.out.println("Role already exists");
            }
            if (event.getGuild().getRolesByName("tank", true).isEmpty()){
                role2 = event.getGuild().createRole().setName("Tank").setPermissions(0L).complete();
            } else {
                System.out.println("Role already exists");
            }

            System.out.println("Role1 ID is: " + role1.getId());
            System.out.println("Role2 ID is: " + role2.getId());
        }

I do create role1 and role2 as empty objects at the beginning of my MessageListener using Role role1; and Role role2;.
Now when executing the command $addrole, the message appears and the roles are created, but I can't use role1 and role2. Whenever I try to call them e.g. in System.out.println("Role1 ID is: " + role1.getId()); I get a load of errors including a nullpointer exception saying that "this.role1 is null". I just can't find my mistake.

A: I tried your code, and it worked the first time I was executing the code. The second time it did not work and threw me a NPE. I quickly found out that the issue you have is that you are trying to print out the Role-ID even if the role already exists. Note that you only assign the role to the variables role1 or role2 if the role does not exist.
So to fix this, you could either return after the printing that the role already exists or just assigning the existing role to the variable.
An example implementation of that would be:
String content = e.getMessage().getContentRaw();
TextChannel channel = e.getTextChannel();

Role role1 = null;
Role role2 = null;

    if (content.equalsIgnoreCase("$addrole")) {
        channel.sendMessage("Please select the role you want!\n\n\u2694\uFE0F\tFighter\n\uD83D\uDEE1\tTank")
                    .queue(message -> {
                        message.addReaction("\u2694\uFE0F").queue();
                        message.addReaction("\uD83D\uDEE1").queue();
                    });

        if (e.getGuild().getRolesByName("fighter", true).isEmpty()) {
            role1 = e.getGuild().createRole().setName("fighter").setPermissions(0L).complete();
        } else {
            role1 = e.getGuild().getRolesByName("fighter", true).get(0);
        }
        if (e.getGuild().getRolesByName("tank", true).isEmpty()) {
            role2 = e.getGuild().createRole().setName("tank").setPermissions(0L).complete();
        } else {
            role2 = e.getGuild().getRolesByName("tank", true).get(0);
        }

        System.out.println("Role1 ID is: " + role1.getId());
        System.out.println("Role2 ID is: " + role2.getId());
    }


text:
Q: How to use a pre-trained object detection in tensorflow? How can I use the weights of a pre-trained network in my tensorflow project?
I know some theory information about this but no information about coding in tensorflow.

A: As been pointed out by @Matias Valdenegro in the comments, your first question does not make sense. For your second question however, there are multiple ways to do so. The term that you're searching for is Transfer Learning (TL). TL means transferring the "knowledge" (basically it's just the weights) from a pre-trained model into your model. Now there are several types of TL.
1) You transfer the entire weights from a pre-trained model into your model and use that as a starting point to train your network.

*

*This is done in a situation where you now have extra data to train your model but you don't want to start over the training again. Therefore you just load the weights from your previous model and resume the training.

2) You transfer only some of the weights from a pre-trained model into your new model.

*

*This is done in a situation where you have a model trained to classify between, say, 5 classes of objects. Now, you want to add/remove a class. You don't have to re-train the whole network from the start if the new class that you're adding has somewhat similar features with (an) existing class(es). Therefore, you build another model with the same exact architecture as your previous model except the fully-connected layers where now you have different output size. In this case, you'll want to load the weights of the convolutional layers from the previous model and freeze them while only re-train the fully-connected layers.

To perform these in Tensorflow,
1) The first type of TL can be performed by creating a model with the same exact architecture as the previous model and simply loading the model using tf.train.Saver().restore() module and continue the training.
2) The second type of TL can be performed by creating a model with the same exact architecture for the parts where you want to retain the weights and then specify the name of the weights in which you want to load from the previous pre-trained weights. You can use the parameter "trainable=False" to prevent Tensorflow from updating them.
I hope this helps.


text:
Q: Error while querying inherited class from telerik open access ORM I am using latest version of Telerik Open Access ORM in my ASP.net  C# web application.
In my EntitiesModel1.rlinq , I have  mapped a table named "Customer " from a database. Then I have created a domain class named "SubCustomer" and added anew property field named "SubName : String" into it. Then deleted default property filed from the domain class. Then I have applied inheritance for Customer-SubCustomer classes. So the inheritance arrow pointing from  SubCustomer to Customer entity now.
I have then applied vertical inheritance stuff to SubCustomer class and mapped "SubName" field with "CustomerName" field in Customer Class using "Default *mapping*". The Update from database model and validate all process have been completed successfully without having any error or warning.
While deploying  this context in my web application and querying like :
        using (EntitiesModel1 context = new EntitiesModel1())
        {
            List<SubCustomer> lstCustomer = (from entity in context.SubCustomer
                                        select entity).ToList();
        }

I am getting an error:
*Error executing query: Telerik.OpenAccess.RT.sql.SQLException: Invalid object name 'SubCustomer.
   at Telerik.OpenAccess.RT.Adonet2Generic.Impl.PreparedStatementImp.executeQuery()
   at OpenAccessRuntime.Relational.conn.PooledPreparedStatement.executeQuery()
   at OpenAccessRuntime.Relational.fetch.FetchResultImp.Execute()
SQL:
SELECT a.[CustomerID] AS COL1, b.[voa_class] AS COL2, a.[SubName] AS COL3, b.*
I have tried to query "Customer" entity as well  but getting the same error.
Please help.
Regards,
Praveen.


text:
Q: Rounding a timestamp to 15 minute intervals in LegacySQL I am pulling some data showing average interactions by hour, but I would like to group this so that it shows me average interactions per 15 minute blocks using a timestamp, unfortunately I am restricted to LegacySQL. I've read several solutions for achieving this with StandardSQL, but how could I do it with Legacy?
Here is my code so far:
SELECT
DAYOFWEEK(meta_recordDate) AS day_num,
HOUR(property_event_ts)+1 AS hour,
IF(page_type = 'transaction',COUNT(transaction_id),0)/4 AS average_interactions,
FROM [TABLE]
WHERE (TIMESTAMP(meta_recordDate) BETWEEN DATE_ADD(TIMESTAMP(CURRENT_DATE()), -31, 'DAY') AND DATE_ADD(TIMESTAMP(CURRENT_DATE()), -1, 'DAY'))
AND dayofweek(current_date()) = DAYOFWEEK(meta_recordDate)
AND page_type = 'transaction'
GROUP BY page_type,day,hour,day_num
ORDER BY hour

My data from this query looks like this:

A: To round minutes of a timestamp to 15 minute intervals in LegacySQL - you can use below expressions
15 * INTEGER(MINUTE(property_event_ts)/15 + 1)

So, add 15 * INTEGER(MINUTE(property_event_ts)/15 + 1) AS mnt into your SELECT list and mnt to GROUP BY list
Depends on which way you want to round you can potentially remove + 1 portion


text:
Q: Trouble getting basic searchlogic plugin code to work in Rails App My rails app is throwing this error:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

I am trying to make a basic form that will allow a user to search for a "match" by "country".  It is just a proof of concept as I am still learning.
Here is my model:
class OmMatch < ActiveRecord::Base
end

Here is my controller:
class OmMatchesController < ApplicationController

 def search
  @search = OmMatch.search(params[:search])
  @match = @search.all
 end
end

Here is the view:

  <title>"Matches"</title>

    <% form_for @search do |f| %>

      <%= f.label :country_equals, "Country" %>

      <%= f.text_field :country_equals %>

      <%= f.submit "Submit" %>

  <% end %>

    "Match Name"
    "Country"

  <% @match.each do |match| %>

    <%=h match.matchname %>
    <%=h match.country %>

 <% end %>

I believe that the problem is from search not being initialized but I am not sure how to that.

A: When you do
<% form_for @search do |f| %>

It is expecting @search to be an initialized active record object with routes defined in the routes.rb file.
I assume the problem you are having is when doing a GET request to the OmMatch search action.
If search is an object you can initialize, then just add
@search = Search.new

to your controller.
You need to consider the workflow here for what action is run when the form is requested via a link, and what occurs when a user posts the form.
Remember that you can run
rake routes

to see all the routes that your application knows about for your resources and controllers.
I would recommend that you check out the railscasts screen casts, especially the ones on routing.  It is very important that you understand how your controller code is mapped by urls. http://railscasts.com/episodes?search=routing  Once you have your routes mapped correctly and you understand when each action will be invoked, you can ensure that your objects are created before you need them.


text:
Q: Screen does not update after SignIn in flutter/firebase I'm new to Flutter & Firebase, and i'm currently stuck in a problem where i can't update the screen (from Sign in Screen to Home Screen) after signing in using email & password, where i have to restart the application in order to see the update. let's not forget that Sign out work perfectly fine.
For my example, the user has to choose first wether he is a client or a service provider through the 'ChooseBox Screen', then he will proceed to the sign in Screen that belongs to the chosen option.
Scenario: :MyApp => Wrapper => chooseBox Screen => Sign in Screen => Home Screen
Note: the sign in works perfectly fine and update to the Home Screen when i remove the chooseBox where the scenario becomes this:
Scenario 2: MyApp => Wrapper => Sign in Screen => Home Screen
main.dart
import 'package:RemedyBox/Services/authentication.dart';
import 'package:RemedyBox/generatedRoutes.dart';
import 'package:RemedyBox/wrapper.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<AuthService>(
          create: (_) => AuthService(FirebaseAuth.instance),
        ),
        StreamProvider(
            create: (context) => context.read<AuthService>().authStateChange),
      ],
      child: MaterialApp(
        onGenerateRoute: RouteGenerator.generateRoute,
        debugShowCheckedModeBanner: false,
        home: wrapper(),
      ),
    );
  }
}

Wrapper.dart
import 'package:RemedyBox/Screens/Authentications/chooseBox.dart';
import 'package:RemedyBox/SignPage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'Screens/Home/homeFile.dart';

class wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = context.watch<User>();

    if (user == null) {
      return chooseBox();
    }
    return homeScreen();
  }
}

ChooseBox.dart, this is the widget where i use to push the chooseBox to the sign in Screen
child: OutlinedButton(
                      onPressed: () {
                        Navigator.of(context).pushNamed('/SignIn');
                      },

SignIn.dart
import 'package:RemedyBox/Services/authentication.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SignInPage extends StatelessWidget {
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: MediaQuery.of(context).padding,
        child: Column(
          children: [
            TextField(
              controller: emailController,
              decoration: InputDecoration(
                labelText: "Email",
              ),
            ),
            TextField(
              controller: passwordController,
              decoration: InputDecoration(
                labelText: "Password",
              ),
            ),
            TextButton(
              onPressed: () {
                context.read<AuthService>().SignIn(
                      email: emailController.text.trim(),
                      password: passwordController.text.trim(),
                    );
              },
              child: Text("Sign in"),
            )
          ],
        ),
      ),
    );
  }
}

A: As it turns out, that the Sign in page was not part of the wrapper tree, and showing the Home page after the sign in can't be done cause the sign in page was still present. The solution was to push replacement towards the root so it can update the status and show the home page.
SignIn.dart
TextButton(
              onPressed: () async {
                await context.read<AuthService>().SignIn(
                      email: emailController.text.trim(),
                      password: passwordController.text.trim(),
                    );
                Navigator.pushReplacement(
                    context, MaterialPageRoute(builder: (_) => MyApp()));
              },
              child: Text("Sign in"),
            )


text:
Q: Use Central Limit Theorem to determine distribution Task
Let $X_1, X_2, ...$ be a sequence of independent random variables with standard uniform distribution $U(0, 1)$.
Lets define $Y_1 = X_1$ and
$$
Y_i = \begin{cases} X_i & i \mbox{ is even} \\ 1 - X_{i-1} & i \mbox{ is odd, } i > 2 \end{cases}
$$
$$
W_n = \sum_{i=1}^{n} Y_i \qquad n \in \mathbb{N}
$$
$$
B_n = \frac{W_n - \mathbb{E}(W_n)}{\sqrt{Var(W_n)}}
$$
I need to figure out the distribution of the $B_n$ (as $n \to \infty$) using CLT.
My attempt
$$
W_n = \begin{cases} X_1 + \frac{n - 2}{2} + X_n & n \mbox{ is even} \\ X_1 + \frac{n-1}{2} & n \mbox{ is odd}\end{cases}
$$
But I don't know how to determine the distribution of $B_n$ using it.


text:
Q: cannot import saved openVPN configuration file in Ubuntu 16.04 LTS I am trying to import a .ovpn file from the network manager.
Here are the steps I follow.

Network Manager → VPN Connections → configure VPN

This opens the Network Connections dialogue.
Then,

Add → import saved vpn configuration → choose .ovpn file

This should load my .ovpn configuration, but instead I get a prompt saying

ERROR: plugin does not support import capability.

I can still use VPN using the command
sudo openvpn --config ~/openvpn/xxx.conf

is this a bug that needs to be filed?

A: I know this is an old question but since I still couldn't find an (easy) answer I want to help others (and future me).
Use this
sudo nmcli connection import type openvpn file FILE_NAME

offcourse replace FILE_NAME with the full path to your file name
This will tell you exactly what's wrong with the file and which lines you should edit/delete.
After you edited the file with the recommendations the command gave you. You can import the file.

A: On commenting out the following line with #, I was able to successfully import the VPN config:
#route remote_host 255.255.255.255 net_gateway default

Others have reported that commenting out, or removing, this line works for them as well per bug #606365 in launchpad in spite of this being a valid argument.
That said, while I'm able to successfully connect to the VPN, I'm not able to hit any host over the VPN. On trying to manually set these values using the network manager GUI, I see that only numerical IP addresses are accepted. String values like remote_host or net_gateway cannot be entered via the GUI.
I've also had success importing the same .OVPN file without any modification in Fedora 23, Windows 10 (using Viscosity), OS X El Capitan (using Viscosity) and earlier versions of Ubuntu. Something is definitely broken in 16.04.

A: Importing .ovpn profiles inside network manager has recently been improved, but there are still bugs and misleading error messages. Sometimes you can successfully import the .ovpn file by removing a single line that breaks the import procedure. In my case, I removed the line float 1 from my .ovpn file and the file has been imported successfully.

A: Its working :)
from https://zorrovpn.com/howto/openvpn/ubuntu?lang=en
Open .ovpn file with a text editor.
And change lines that looks like
remote 11.2.2.2 443 tcp-client

to
remote 11.2.2.2
port 443
proto tcp-client

Then save .ovpn file and try again to import VPN connection.

A: worked for me:
sudo apt install network-manager-openvpn-gnome

A: *

*open your .ovpn file with any editor

*add # to the beginning of this line to comment it out
route remote_host 255.255.255.255 net_gateway default

*Go to IPv4 settings > routes > Check the option "Use this connection only for resources on its network" > press OK > Save
Done!
This is just a wrap up of what worked for me on ubuntu 16.04 based on the other answers and comments here.

A: I am experiencing the same issue.  It looks like a bug, according to this link:
https://bugs.launchpad.net/ubuntu/+source/network-manager-openvpn/+bug/606365

A: You might be suffering from the NetworkManager-openvpn bug #83.
Current suggested workaround is a downgrade to 1.8.10-1, however this version is not available in Ubuntu 21.10.
In my case the issue was caused by a PKCS#12 certificate from which I extracted a PKCS#8 CA certificate with
openssl pkcs12 -in [input.p12] -cacerts -nokeys -out ca.crt

and specified
ca ca.crt

in the config file before being able to import the connection with
sudo nmcli connection import type openvpn file your-file.ovpn

You might have to enter your certificate password for every connection. Consider this a workaround until the issue is fixed upstream and you can import your configuration through the UI without issues again.

A: I've found out that changing
remote REMOTE_SERVER 12345

with
remote REMOTE_SERVER
port 12345

Fixed the issue.

A: For me (Ubuntu 16.04.1 LTS), removing the section
<extra-certs>
worked.
Here is the ovpn file generated by a tunnel provider.
setenv USERNAME "user@provider.xx"
client
dev tun
remote host 1194 udp
remote host 1194 udp
remote host 443 tcp
remote host 1194 udp
remote host 1194 udp
remote host 1194 udp
remote host 1194 udp
remote host 1194 udp
remote-cert-tls server
comp-lzo no
auth SHA1
nobind
verb 3
sndbuf 0
rcvbuf 0
socket-flags TCP_NODELAY

<ca>
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
</ca>

<cert>
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
</cert>

<extra-certs>
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
</extra-certs>

<key>
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
</key>

key-direction 1
<tls-auth>
-----BEGIN OpenVPN Static key V1-----
-----END OpenVPN Static key V1-----
</tls-auth>
## -----BEGIN RSA SIGNATURE-----
## DIGEST:SHA1WithRSA
## -----END RSA SIGNATURE-----
## -----BEGIN CERTIFICATE-----
## -----END CERTIFICATE-----
## -----BEGIN CERTIFICATE-----
## -----END CERTIFICATE-----
## -----BEGIN CERTIFICATE-----
## -----END CERTIFICATE-----

A: In my case the following item caused the problem:
float 1

After commenting it out, it worked:
#float 1

A: Nothing here worked for me so I added it to the openvpn config manually.
$ sudo cp ~/me.ovpn /etc/openvpn/me.conf

Then I start OpenVPN with:
$ sudo systemctl start openvpn@me

# Enable/disable on computer start
$ sudo systemctl enable openvpn@me


text:
Q: LockerService in spring '17 There is one critical update in Sprint '17 release, which is Enable Lightning LockerService Security. How will this affect lightning components? We currently don't use lightning components except Process builder in our project. So is it going to affect Process builder functionality as well?

A: Locker service only applies to custom components currently - standard components/applications run in system mode and are not impacted by the LS rollout.

A: Here you can find all the documentation about the impact on your lightning components:
https://developer.salesforce.com/blogs/developer-relations/2016/04/introducing-lockerservice-lightning-components.html
E.g.: Standard markup like <input> will crash if you do not replace it with <lightning:input>
I have not read anything about Process Builder impact (yet).


text:
Q: How do I know that a file backup from a Linux server was successful? Here is the scenario, I have been tasked with backing up production Oracle server running on Linux. According to the process left by the person from whom I took over, I connect to the server using WinSCP and copy the folder named backup to an external disk. I did a backup so how do I know that all the files are backed up? Windows backup tool shows that the backup is completed.
Appreciate your help. Thanks in advance.

A: Restore from backup media to a test system. Spot check by opening a few files, and check number of files and size is reasonable compared to the source volumes. Restore applications, and leave the now in sync with production system to users.

It's a restore system not a backup system. -- Raymond Blum, Google SRE


text:
Q: Get the data-id of the selected option in a datalist Ok, I have the following HTML source:
<form method="post" action="/" id="search">
  <input list="animals" name="animal">
    <datalist id="animals">
      <option label="Alaskan Malamute" data-id="d8c" value="Dog">
      <option label="Siberian Husky" data-id="w30" value="Dog">
      <option label="Aegean" data-id="rxx" value="Cat">
    </datalist>
</form>

And the JS

function doKeyUp(e) {
  if (e.preventDefault) e.preventDefault();

  if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 ) {return;}

  var input = document.getElementById("animal");
  var search_after = input.value.trim();
  var form = document.getElementsByTagName("form")[0];

  var datalist = document.getElementsByTagName('datalist')[0];

  if (search_after.length >= 2) {

    if (e.keyCode == 13 && search_after.length >= 3) {
      var id = "value of data-id";
      // How to obtain and submit the `data-id` of the selected option.
      document.getElementById("search").submit();
    }
  }
}  // dokeyup

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementById("search").onsubmit = function (e) {
    console.log("SUBMIT");
    return false;
  };

  document.addEventListener( "keyup", doKeyUp, true);
});

When the user then selects an option, how do I get the data-id of the selected <option> - which is the actual data I want to submit and process on the server side.
This is a project where I'm trying to write everything by my self, no jQuery this time.
Know I can do console.log(datalist.options[1]);, but can not figure how I obtain the selected index.
Update March 4:
Must ask again, no one who has any tips for me ?
Still not figured this out, and have really run out of ideas...
The last I've tried stopped at, before the form submission:
for (var i=0; i<document.getElementById('animals').options.length; i++) {
    if (document.getElementById('animals').options[i].value == document.getElementsByName("animal")[0].value) {
        var id = document.getElementById('animals').options[i].getAttribute('data-id');
        break;
    }
}

Is it in any way possible to get the selected index of the chosen option - or am I still on the wrong path ?
This above stops at the first element, anyway.

A: Check this answer as jquery solution .. & sorry for late reply .

$(function(){
    $('#p').click(function(){
        console.log($("#animals option[value='" + $('#someid').val() + "']").attr('data-id'));
    });
});

<form method="post" action="/" id="search">
  <input list="animals" name="animal" id="someid">
    <datalist id="animals">
      <option label="Alaskan Malamute" data-id="d8c" value="Dog">
      <option label="Siberian Husky" data-id="w30" value="Dog">
      <option label="Aegean" data-id="rxx" value="Cat">
    </datalist>
    Click
</form>

A: the value of the data-id attribute of the selected < option > in a datalist can be accessed from the DOM datalist object, like this
<input list="animals" id="input-animal" name="animal">
<datalist id="animals">
  <option label="Alaskan Malamute" data-id="d8c" value="Dog">
  <option label="Siberian Husky" data-id="w30" value="Dog">
  <option label="Aegean" data-id="rxx" value="Cat">
</datalist>

 animals.options.namedItem( input-animal.value ).getAttribute('data-id')

namedItem() is a method which returns the  element from the collection with the specified id.

A: Russel Newton's solution using namedItem almost worked for me. Here is an adjusted solution that worked, using the name attribute on the option tags. (Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/namedItem)

var form = document.getElementById('dataForm');
form.addEventListener('submit', validateform);

function validateform() {
  event.preventDefault();
  var selectedOption = dataListId.options.namedItem(inputId.value);
  if (selectedOption) {
      var selectedId = selectedOption.getAttribute('data-id');
      var result = "Country ID: " + selectedId;
      console.log({selectedId});
  } else {
      var result = "No ID available for value: " + inputId.value;
  }
  document.getElementById('resultID').textContent = result;

  // Can also use :
  // inputElement = document.getElementById("inputId");
  // listElement = document.getElementById("dataListId");
}
div.resultID {
  color: #85144b;
  font-weight: bold;
  margin-top: 30px;
  margin-left: 20px;
}
<form id="dataForm">
  <input id="inputId" list="dataListId" value="" placeholder="Choose a country">
  <datalist id="dataListId">
            <option data-id="1" name="Country A">Country A</option>
            <option data-id="36" name="Country B">Country B</option>
            <option data-id="59" name="Country C">Country C</option>
        </datalist>
  <button id="submitButton" type="submit">Submit</button>

</form>

A: https://kodingkantor.blogspot.co.id/2018/03/get-data-id-in-datalist-option.html
console.log($("#locations option[value='" + $('#location1').val() + "']").attr('data-id'));

A: Without jQuery!
When input value has changed, data attributes of input field get merged:

document.querySelector('#animal').addEventListener('input', (e) => {
  Object.assign(e.target.dataset, document.querySelector('#' + e.target.getAttribute('list') + ' option[value="' + e.target.value + '"]').dataset);
  console.log('dataset of input changed: ', e.target.dataset)
});
<input list="animals" id="animal" data-id="xxx">
<datalist id="animals">
  <option value="Alaskan Malamute"  data-id="123" data-alpha="abc">
  <option value="Siberian Husky"    data-id="456" data-alpha="def">
  <option value="Aegean"            data-id="789" data-alpha="ghi">
</datalist>


text:
Q: Responsive Navigation with Angular 8 Material Sidenav? I've seen various implementations (Including this youtube) that implement a responsive navigation for the Angular Material Sidenav using media queries.
For Angular 8 do we still need custom media queries / CDK Media Queries to implement this, or is there a way to do it declaratively with the component?
My goal is to implement a responsive sidenav similar to the one used in the Angular Material Documentation.

A: You can't do it completely with media queries, because the DOM structure between desktop, tablet and mobile are often different.
For example, here is a desktop with a sidebar.
+-----+----------+
|     |          |
|     |          |
|     |          |
|     |          |
+-----+----------+

The DOM structure might be something like this:

When we switch to something like mobile, then the sidebar is often overlapped with the .container so that the user can open or close the sidebar. The sidebar is shown over top of the container and sometimes has a darkened background overlay.
The DOM structure might be something like this:

With flex layout you can modify the order of DOM elements, but it's not possible to change the DOM structure. The only alternative is to render the sidebar twice in the HTML so you show one for desktop and the other for mobile, but itself isn't the best practice.

A: If you read angular schematics you can actually generate responsive NAV bar using Angular Material


text:
Q: Android Studio network speed unknown command I am having some trouble with Android studio, as it is giving me Unknown Command when i enter in Network speed command.
I clicked run app, then app starts up in Emulator, in Terminal i typed telnet localhost 5554
It asked for Auth and i entered it, and i have a list of help...
but network speed wasnt there....
When i enter in network speed 14.4 80 it responded with

KO: unknown command, try 'help'

Does anyone know why the network speed command is missing?
Edit: If i use the extended controls, and change the network type inside cellular, then whatever setting i put, the download speed is 0.1mbps, even the setting is HSDPA.

A: You need to give authorization to get more commands. Your authorization key will be present in ~/.emulator_console_auth_token. You can authorize using the following command:
auth <key>


text:
Q: Firebase Jobdispatcher interval unreliable Google forces me to stop using the AlarmManager because of Excessive Wakeups.
I should now use JobScheduler, but my app should support older devices with API <21.
So I have to use the Firebase JobDispatcher :-(
However, in my opinion, the JobDispatcher is unreliable, unlike AlarmManager.
I set the interval to every 60 secs (1 min).
But the gaps between JobService.onStartJob() are:

1, 10, 6, 1, 16, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 4, 0, 1, 8
  mins.

If I set the interval to 10 mins, the gaps are:

11, 10, 10, 10, 10, 10, 21, 12, 10, 10, 10, 10, 10, 15, 10, 41, 10,
  13, 14, 14, 22, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 19, 10, 10,
  34, 14, 10, 10, 10, 12, 10 mins.

My smartphone (Samsung Galaxy Alpha, Android 5.0.1) is connected to power and not in standby, power safe option is deactivated.
What am I doing wrong?
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));

Job jobWifi = dispatcher.newJobBuilder()
    .setService(ConnectionJobService.class)
    .setTag("tag")
    .setRecurring(true)
    .setLifetime(Lifetime.FOREVER)
    .setTrigger(Trigger.executionWindow(60, 60)) // 600, 600
    .setReplaceCurrent(true)
    .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
    .setExtras(extras)
    .build();


text:
Q: Https in flutter -post do not accept integer I tried a lot to pass the int to the id via post but it didn't work and I used tostrin() but the api refuses to be an id string so what is the solution
http.Response response = await http.post(url,body:{
"id": id.toString(),"customerName":name.Text,"address": address.Text,"isMale": true.toString};

Note: These entries are for clarification, and they are now fake. How can I send an api intger via http? If I convert it to a string, how do I make the API accept it?

A: You can use json.encode() like below (Also I believe you can pass the id as integer)
     body: json.encode(
        {
          'id': id.toString(),
          'customerName':name.Text,
          'address': address.Text,
          'isMale': true.toString,
        },
      ),

flutterdarthttp


text:
Q: SplitView iPad sdk help ? Good morning. I know how to integrate split view in my project.
I started with window based application, and would now like to touch a button and you see a splitview. Thank you very much.

A: What you are asking for is a view controller with a view on at the root that has as it's view or as a child of it's view a uiButton. When pressed that uiButton would call a method that tells the appDelegate to remove the root view controller and create a new one that is a split view controller.


text:
Q: Azure Traffic Manager and its End Points' Poll Status Degraded I have a traffic manager with 6 End Points. Although I can access the application via the traffic manager and the individual end points URLs, I dont know why the status on them is being shown as "Degraded".
All the 6 End Points are showing Degraded and so the traffic manager status is also showing as Degraded. The app is in production and people are using it and haven't complained about the accesibility.
I am not sure why the status us Degraded. These are Https end points and the same has been configured in the "Configure" tab and also in the service definition file.
Any pointers? I have seen a few such queries on the forums, but none of them meet my condition.

A: Check http://blogs.msdn.com/b/kwill/archive/2013/09/06/troubleshooting-scenario-4-windows-azure-traffic-manager-degraded-status.aspx for how to troubleshoot this.  Essentially, your WATM probe path is returning something besides a 200 (ie. a 301 redirect).


text:
Q: IndexOutOfRangeException when trying to create an Object from a text file in C# I'm currently in the middle of trying to take a '|' delimited text file and create objects from the data contained within. Example:
Name|Address|City|State|Zip|Birthday|ID|Etc.
Name2|Address2|City2|State2|Zip2|Birthday2|ID2|Etc.

The newly created object, is then added to a list of said objects and the program moves to the next line of the file by way of a while loop using .Peek() (to make sure I don't go past the end of the file).
However, when it gets to creating the second object (more specifically, the second field of the second object), it throws an Index Out Of Range Exception, and I can't for the life of me figure out why. Thank you whomever might read this!
    StreamReader textIn = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

        List<Student> students = new List<Student>();

        while (textIn.Peek() != -1)
        {
            string row = textIn.ReadLine();
            MessageBox.Show(row);
            string [] fields = row.Split('|');
            Student temp = new Student();

            try
            {
                temp.name = fields[0];
                temp.address = fields[1];
                temp.city = fields[2];
                temp.state = fields[3];
                temp.zipCode = Convert.ToInt32(fields[4]);
                temp.birthdate = fields[5];
                temp.studentID = Convert.ToInt32(fields[6]);
                temp.sGPA = Convert.ToDouble(fields[7]);
            }
            catch
            {
                MessageBox.Show("IndexOutOfRangeException caught");
            }

            students.Add(temp);
        }

        textIn.Close();

A: First you can't ensure if its a IndexOutOfRange Exception with your current catch block.
catch
{
    MessageBox.Show("IndexOutOfRangeException caught");
}

It can be anything, may be exception during parsing to double. You may modify your catch block to:
catch(IndexOutOfRangeException ex)
{
    MessageBox.Show(ex.Message);
}

Also if you are going to access fields[7] then its better if you can check against the length of array to ensure that you got atleast 8 elements in your array.
 if(fileds.Length >=8)
       {
        temp.name = fields[0];
        ....

To catch FormatException which can occur during double parsing you may add an extra catch block for:
catch (FormatException ex)
{
    MessageBox.Show(ex.Message);
}

A: In the given data if you have atleast eight columns for every row, you wont be getting index of of range exception but parsing of item at 4, 6, 7 would fail as they are not numbers and converting the non number values to int and double raises the exception.
temp.zipCode = Convert.ToInt32(fields[4]);
temp.studentID = Convert.ToInt32(fields[6]);
temp.sGPA = Convert.ToDouble(fields[7]);

You need to change the catch block to know the reason for exception
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

A: *

*Check if you have all 8 fieds in a line.

*Show a message if ther isn't.

*Get the actual exception and show its message to see the real problem description.

*Use Double.TryParse Method  and Int32.TryParse Method to be sure all numeric values are valid

*Also use while (!textIn.EndOfStream) instead.

 try
 {
    int tempInt;
    double tempDouble;
    if (fields.Length = 8)//#1
    {
        temp.name = fields[0];
        temp.address = fields[1];
        temp.city = fields[2];
        temp.state = fields[3];
        if (!int.TryParse(fields[4], out tempInt))    //#4
            temp.zipCode = tempInt;
        else
        {
           //..invalid value in field
        }
        temp.birthdate = fields[5];
        if (!int.TryParse(fields[6], out tempInt))    //#4
            temp.studentID = tempInt;
        else
        {
           //..invalid value in field
        }
        if (!int.TryParse(fields[7], out tempDouble)) //#4
            temp.sGPA = tempDouble;
        else
        {
           //..invalid value in field
        }
    }
    else //#2
    {
        MessageBox.Show("Invalid number of fields");
    }
}
catch (Exception ex)   //#3
{
    MessageBox.Show(ex.Message);
}

A: Maybe ReadAllLines will work a bit better if the data is on each line:
            List<Student> students = new List<Student>();
            using (FileStream textIn = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                foreach (string line in File.ReadAllLines(path))
                {
                    MessageBox.Show(line);
                    string[] fields = line.Split('|');
                    Student temp = new Student();
                    try
                    {
                        temp.name = fields[0];
                        temp.address = fields[1];
                        temp.city = fields[2];
                        temp.state = fields[3];
                        temp.zipCode = Convert.ToInt32(fields[4]);
                        temp.birthdate = fields[5];
                        temp.studentID = Convert.ToInt32(fields[6]);
                        temp.sGPA = Convert.ToDouble(fields[7]);
                    }
                    catch
                    {
                        MessageBox.Show(string.Format("IndexOutOfRangeException caught, Split Result:", string.Join(", ", fields.ToArray())));
                    }
                    students.Add(temp);
                }
            }


text:
Q: System.Linq.Expressions exception thrown when using FirstOrDefault in .Net Core 2.1 I am receiving ~300+ exceptions that are spammed in my server output labeled:
Exception thrown: 'System.ArgumentException' in System.Linq.Expressions.dll

The query I am using is as follows:
Account account = _accountContext.Account.
     Include(i => i.Currency).
     Include(i => i.Unlocks).
     Include(i => i.Settings).
     Include(i => i.Friends).
     FirstOrDefault(a => a.FacebookUserID == facebookUserID);

Eventually the exceptions stop generating, it shows a large query in the output window, and everything continues as normal.
If I change the query to the following I do not experience the exception:
IQueryable<Account> account = _accountContext.Account.
     Include(i => i.Currency).
     Include(i => i.Unlocks).
     Include(i => i.Settings).
     Include(i => i.Friends).
     Where(a => a.FacebookUserID == facebookUserID);

However, if I call anything such as First, FirstOrDefault, Single, etc on the IQueryable<Account> variable the exceptions start up again and then stop after ~300.
These exceptions are stalling user logins upwards of 30 seconds or more. The duration of exceptions grows with the amount of data being returned from the database.
I use the Account object by passing it around the server to perform varying maintenance tasks on it and then eventually sending the object client-side where I have it being deserialized into the client-side version of the Account class.
Does anyone know what could be causing these internal exceptions and how I might be able to eliminate or mitigate them?
Here is my output log:

Below is the exception message:
The AccountStatistics isn't listed in the query above because there are about 20 some includes and I shorthanded the include list for brevity.
Field 'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Project.Models.Account,System.Collections.Generic.IEnumerable`1[Project.Models.AccountStatistics]].Inner' is not defined for type 'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Project.Models.Account,Project.Models.AccountStatistics]'

There is no inner exception.
I double checked my database and I have an entry for the user and all of their fields are filled with valid data.
Account Class (Edited for brevity)
public class Account
    {
        [Key]
        public int ID { get; set; }
        public DateTime CreationDate { get; set; }

        public AccountCurrency Currency { get; set; }
        public AccountProgression Progression { get; set; }
        public AccountSettings Settings { get; set; }
        public AccountStatistics Statistics { get; set; }

        public ICollection<AccountFriendEntry> Friends { get; set; }
        public ICollection<AccountUnlockedGameEntry> Unlocks{ get; set; }
    }

Account Statistics class
public class AccountStatistics
{
    [Key]
    public int AccountID { get; set; }
    public int LoginCount { get; set; }
    public DateTime LastLoginTime { get; set; }
    public DateTime LastActivityTime { get; set; }
}

Edit
Keys for the Account Statistics table

   migrationBuilder.CreateTable(
            name: "AccountStatistics",
            columns: table => new
            {
                AccountID = table.Column<int>(nullable: false),
                LoginCount = table.Column<int>(nullable: false),
                LastLoginTime = table.Column<DateTime>(nullable: false),
                CreationDate = table.Column<DateTime>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_AccountStatistics", x => x.AccountID);
                table.ForeignKey(
                    name: "FK_AccountStatistics_Accounts_AccountID",
                    column: x => x.AccountID,
                    principalTable: "Accounts",
                    principalColumn: "ID",
                    onDelete: ReferentialAction.Cascade);
            });

Edit 9001
After doing some testing I've realized the exception only occurs when chaining includes.
This will cause an exception:
Account account = _accountContext.Account.
     Include(i => i.Currency).
     Include(i => i.Unlocks).
     Include(i => i.Settings).
     Include(i => i.Friends).
     FirstOrDefault(a => a.FacebookUserID == facebookUserID);

This will NOT cause an exception:
Account account = _accountContext.Account.
     Include(i => i.Currency).
     FirstOrDefault(a => a.FacebookUserID == facebookUserID);

It does not matter if its currency and unlock, friends and currency, settings, and statistics. Any combination of includes (2 or more) causes the exception to happen.
Edit 9002
Here are my results of the following query:
var acct = _accountContext.Account
     .Where(a => a.FacebookUserID == facebookUserID)
     .Select(x => new { Account = x, x.Currency, x.Settings }).ToList();

Exception:
System.ArgumentException: 'Field 'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Project.Models.Account,System.Collections.Generic.IEnumerable`1[Project.Models.AccountSettings]].Inner' is not defined for type 'Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Project.Models.Account,Project.Models.AccountSettings]''

I feel like this is treating AccountSettings as a collection when it's a single field reference.
Edit Final:
I never found a fix for this issue. I re-created all the tables and such in another environment and it works just fine. Not a very ideal solution to blow away all tables, classes, and migrations, but it's the only thing that fixed the issue.

A: @Sean Malone's answer did the trick for me.
Checking the option "Enable Just My Code" in Visual Studio, Menu Tools => Options => Debugging => General
https://learn.microsoft.com/fr-fr/visualstudio/debugger/just-my-code?view=vs-2019

A: I have the same problem. It's a bug related to Debugging (see https://github.com/aspnet/EntityFrameworkCore/issues/12548) and  will only be fixed in version 3.0.

A: Just wanted to add my 2 cents here.
It appears we have to live with this until 3.0 but, disabling all exceptions from other code is not a good idea. You may miss something important during debugging.
I'm on .NET Core 2.2.7 but, this still comes up from time to time.
Using Visual Studio 2019 (I assume 2017 too) you can disable this exception just for System.Linq.Expressions.
The way to do it is as follows :

*

*Open Exception Settings window. Debug -> Windows -> Exception Settings (Ctrl+Alt+E)

*There is a search box at the top right of the window, type "System.ArgumentException" in it

*You will see the exception listed in the window, right click on it and select "Edit Conditions" from the menu

*Edit Conditions allows you to set the conditions for the debugger to break when the exception is thrown

*From left to right, select Module Name, select Not Equals and type "System.Linq.Expressions.dll" in the edit box at the right

*Click OK and close the window

The same problem will not bother you again, but you will be able to catch the same exception from other places. I find this quite helpful during debugging.
Cheers.

A: I was getting this issue when debugging whilst my colleagues weren't. After much head scratching we discovered I was the only one with the Debugging > General > Enable Just My Code setting unticked.
Ticking it hide the thousands of Exception thrown: 'System.ArgumentException' in System.Linq.Expressions.dll errors in the Output window, the code went back to normal speed and I could happily live on with my head buried in the sand.


text:
Q: filter textView i`m building an iPhone app , in the app i upload images to a server, i get the result from this code
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"%@", returnString);

and it shows up like this
=======
http://www.mylink.com/30268.jpg
121084
application/octet-stream
.jpg
./30268.jpg
=======
what i need is to insert just the url "http://www.mylink.com/30268.jpg" into a text label
i searched for a way but with no luck
any ideas ?
thanks in advance

A: It looks like the parts of the string are separated by line breaks, so you could try [[returnString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]objectAtIndex:0]


text:
Q: Delta function multiplied by an exponential function I do not know if this is an ill-posed question but ...
is $\delta(t)e^{-\gamma t}$ equal to $\delta(t)$?
Thanks,
biologist

A: If you mean what I think you mean, then:
$$\int_{\Bbb R} f(t)\delta(t)\,dt = f(0)$$
and
$$\int_{\Bbb R} f(t)\delta(t)e^{-\gamma t}\,dt=f(0)e^{-\gamma\cdot0}=f(0).$$
which works because your "extra" function evaluates to $1$ at the support of $\delta$. So they form identical kernels to integrate against, and that seems like probably what you want to know.

A: Unfortunately, this is a little bit ill-posed. $e^{-\gamma t}$ does not play well with tempered distributions. The delta distribution is a tempered distribution, meaning that it is in the dual space to the Schwartz functions (functions that are smooth and decay exponentially). Examples of such functions are the functions of the form $\exp(-t^{2n})$ where $n$ is a natural number. So you can't be sure that it makes sense to integrate the delta distribution against $\exp(-\gamma t)$. However if you could, then you would be correct.


text:
Q: Body window scrolling area with native scrollbar I have an CSS overflow issue which seems not be an issue but I can't see the solution.
Here we go:
I want the body to be scrollable within a window so it has a frame and the window should be scrollable even the mouse is over that frame and the scrollbar should has the native position of it. At the moment in my solution the scrollbar is beside the window inside the frame but it should be outside the frame where it is generally.
//Edit I want the window to be fixed in that area it is in my example. So the window doesn't scroll but the content is scrollable.
I thought I just can reach that by giving the body a margin but it won't work that way.
It should look like this:

Thanks for helping.
Take a look at my code here:
https://codepen.io/knorke/pen/bGMBgqO
HTML:

* {
    margin:0;
    padding:0;
    box-sizing: border-box;
}
h1 {
  margin-bottom:40px;
}
p {
  margin-bottom:20px;
}
html {
    background: red;
    height:100vh;
    width:100%;
    overflow:auto;
}
body {
    background: #fff;
    border-radius: 50px;
    height: calc(100% - 200px);
    width: calc(100% - 80px);
    overflow-y: scroll;
    padding: 40px;
    margin:100px 40px;
}

Hello World!

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.

A: Try this:

* {
    margin:0;
    padding:0;
    box-sizing: border-box;
}
h1 {
  margin-bottom:40px;
}
p {
  margin-bottom:20px;
}
html {
    background: red;
    width:100%;
    overflow:auto;
}
body {
    background: #fff;
    border-radius: 50px;
    width: calc(100% - 80px);
    padding: 40px;
    margin:100px 40px;
}

Hello World!

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.


text:
Q: Vue JS filter results based on checkbox array I've built a Vue JS search component to search and filter a list of properties for a property website. The search component is listed on every page, so it makes sense for me to use a URL search query which takes me to the main properties page and then use something like this.$route.query.search to get the value from my query and store in a variable.
The property data is coming from a JSON file which essentially looks like this:
{
  "data": [
    {
      "id": 12,
      "sold": false,
      "isFeatured": true,
      "slug": "green-park-talbot-green-cf72-8rb",
      "address": "Green Park, Talbot Green CF72 8RB",
      "county": "Rhondda Cynon Taf",
      "price": "695000",
      "features": ["Modern fitted kitchen", "Integrated appliances", "Front and rear gardens"],
      "type": "Semi-Detached",
      "bedrooms": "3"
    }
}

My search query would be something like this:
/properties/?search=Address%20Here&type=Apartment&bedrooms=2&county=Maesteg

Which then would filter each thing.
How this works is quite simple, inside my data object I have my variables which get each query and store them as follows:
data () {
    return {
      searchAddress: this.$route.query.search,
      searchType: this.$route.query.type,
      searchBedrooms: this.$route.query.bedrooms,
      searchCounty: this.$route.query.county
    }
}

And then I have a filter inside the computed area called filteredProperties which filters down the properties inside the v-for which isn't necessary to show here:
computed: {
    filteredProperties: function(){
      return this.properties.filter((property) => {
        return property.address.match(this.searchAddress) && property.type.match(this.searchType) && property.bedrooms.match(this.searchBedrooms) && property.county.match(this.searchCounty)
      });
    }
  }

Now this works absolutely fine and works correctly... however I now need to modify this to instead of having <select> dropdowns which is how you would currently pick the number of bedrooms, or the property type etc, I now need to replace the property type <select> dropdown with checkboxes so that the user can select multiple property types and essentially add that as an array into the URL.
I'm not quite sure how to modify this part of my filter to be able to look for multiple property types:
property.type.match(this.searchType)

Many thanks
UPDATE
I've recently tried updating my computed filter with the following:
computed: {
    filteredProperties: function(){
      return this.properties.filter((property) => {

        return property.address.match(this.searchAddress) &&
        this.searchAddress.some(function(val){
          return property.search.match(val)
        }) &&

        property.type.match(this.searchType) &&
        this.searchType.some(function(val){
          return property.type.match(val)
        }) &&

        property.bedrooms.match(this.searchBedrooms) &&
        this.searchBedrooms.some(function(val){
          return property.bedrooms.match(val)
        }) &&

        property.county.match(this.searchCounty) &&
        this.searchCounty.some(function(val){
          return property.county.match(val)
        })

      });
    }
  }

I need the search to work with and without a URL query.
Also tried an if/else statement:
computed: {
    filteredProperties: function(){
      return this.properties.filter((property) => {
        return property.address.match(this.searchAddress) &&

        if (this.searchType.length > 1) {
          this.searchType.some(function(val){
            return property.type.match(val)
          })
        } else {
          property.type.match(this.searchType)
        } &&

        property.bedrooms.match(this.searchBedrooms) &&
        property.county.match(this.searchCounty)
      });
    }
  }

UPDATE
I got it working by doing the following:
computed: {
    filteredProperties: function(){
      return this.properties.filter((property) => {

        let searchTypeMatch;

        if (typeof this.searchType === "object") {
          searchTypeMatch = this.searchType.some(function(val){
            return property.type.match(val)
          })
        } else {
          searchTypeMatch = property.type.match(this.searchType)
        }

      return property.address.match(this.searchAddress) &&
        searchTypeMatch &&
        property.bedrooms.match(this.searchBedrooms) &&
        property.county.match(this.searchCounty)
      });
    }
  }

A: You will have to use JSON for the query parameters in order to serialize/deserialize the arrays.
data () {
    return {
      searchAddress: this.$route.query.search ? JSON.parse(this.$route.query.search) : [],
      searchType: this.$route.query.type ? JSON.parse(this.$route.query.type) : [],
      searchBedrooms: this.$route.query.bedrooms ? JSON.parse(this.$route.query.bedrooms) : [],
      searchCounty: this.$route.query.county ? JSON.parse(this.$route.query.county) : []
    }
}
computed: {
    filteredProperties: function()
    {
      return this.properties.filter((property) =>
      {
        return (this.searchAddress.length ? this.searchAddress.some((address) =>
        {
          return property.address.match(address);
        }) : true) && (this.searchType.length ? this.searchType.some((type) =>
        {
          return property.type.match(type);
        }) : true) && (this.searchBedrooms.length ? this.searchBedrooms.some((bedrooms) =>
        {
          return property.bedrooms.match(bedrooms);
        }) : true) && (this.searchCounty.length ? this.searchCounty.some((county) =>
        {
          return property.county.match(county);
        }) : true)
      });
    }
  }

Then you send query params like this
this.$router.push("/search?search=" + JSON.stringify(searchArray)
  + "&type=" + JSON.stringify(typeArray)
  + "&bedrooms=" + JSON.stringify(bedroomsArray)
  + "&county=" + JSON.stringify(countyArray)
);

A: I have not worked with routing in Vue apps but for the following to work you will have to ensure that this.$route.query.search (and the other route properties) is an (are) [](s).
return this.searchAddress.some(function(val) {
    return property.address.match(val)
}) &&
this.searchType.some(function(val){
    return property.type.match(val)
}) && ...

Let me know if this works for you.
RE-EDITED:
Hi, please change the computed property to the following
computed: {
    filteredProperties: function () {
        let self = this
        let routeConstraints = ['search', 'type', 'bedrooms', 'county'].filter(function (val) {
            return self.$route.query[val] !== undefined
        })
        if (routeConstraints.length === 0) {
            return self.properties
        } else {
            return routeConstraints.reduce(function (acc, val) {
                return acc.filter(function (property) {
                    //basically I am checking if there is some value in the query parameter that matches properties.
                    if (self.$route.query[val] !== undefined) {
                        //check if the route parameter is an array (object)
                        if (typeof this.searchType === "object") {
                            self.$route.query[val] = [self.$route.query[val]]
                        }
                    }
                    return self.$route.query[val].some(function (item) {
                        //changed the matching condition to indexOf
                        return property[val].match(item).length > 0
                    })
                })
            }, self.properties)
        }
    }
}

Basically,

*

*I am trying to check what routes values are set from your checkbox selections

*Using it to filter the properties array.

*If none are set then all properties are returned.

Hope this works.


text:
Q: How to use relative paths in MAMP (Wordpress)? I set up my website in MAMP with Wordpress, but when navigating with relative paths the home is not set properly.
while / do refer to localhost:8888/mywebsite, /page-name do not refer to localhost:8888/mywebsite/page-name but to localhost:8888/page-name.
how can I fix it to navigate my website in MAMP using relative paths?


text:
Q: Expression for $\exp\left(x\right) -1$ Found an unexpected expression:
$$e^x -1=xe^{\theta.x}$$
where $\theta \in \left(0,1\right)$.
However, I cannot prove it (the $\theta$ part).
Any ideas?
Thank you.

A: Thank you greatly to everybody for your help. Mean Value Theorem works:
Fix x and consider the function $f(y)=\exp \left(xy\right)$ on the interval $y \in \left(0, 1\right)$. The function $f\left(y\right)$ is differentiable on this interval with respect to $y$. Then, by the MVT, there exists $\theta \in \left(0, 1\right)$ such that $$x \exp \left(x \theta\right)=\exp \left(x\right)-1.$$
Done.


text:
Q: Problem with registration page I am sorry if this is a very trivial question, but I am very new to wordpress and this is the first time I use wp.
I am trying to set a website with wordpress and buddypress. I followed all the steps and the website is up and running in my localhost. Now I would like that a new members can register in the website. When I try to go to registration page server tell me that the page does not exist. I googled for a while, but I did not found any basic tutorial. Then I believe that this is a very trivial question, so I am wondering if something goes wrong during the installation. Who can help me or give me a resource to fix this problem?

A: The problem was the mod_rewrite of Apache. I went in  /etc/apache2/sites-available/000-default  and I changed
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

to
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

the I restarted the apache server and all gone fine.


text:
Q: randomly rough surface by ifft : real output from ifft I'm trying to generate a randomly rough isotropic surface with predefined roughness amplitudes (standard deviation of heights). Suppose I have the absolute values of fourier components of the surface in "H" and H has symmetry with respect to center of the array. Now, I need to define some random phase for the fourier series which are between -pi to pi (due to fftshift).
The question is how I can define these random numbers so that the final complex fourier components become complex conjugate? As in this case, the output of ifft will be real.
So far:
phi =  -pi + (pi+pi)*rand(n); % random phase
[a,b] = pol2cart(phi,H);
  H_complex = complex(a,b); % the complex fourier transform composed of H & phi

  z = ifft2(ifftshift((H_complex)));

A: I found my answer, so maybe useful for someone else as well.
I need to apply conjugate symmetry condition for 2D fourier transform, both in magnitude values and phase components. I applied it as below for a n*m matrix:
"H" is the magnitude:
H(1,1) = 0;
  H(1,m/2+1) = 0;
  H(n/2+1,m/2+1) = 0;
  H(n/2+1,1) = 0;
  H(2:end,2:m/2) = rot90(H(2:end,m/2+2:end),2);
  H(1,2:m/2) = rot90(H(1,m/2+2:end),2);
  H(n/2+2:end,1) = rot90(H(2:n/2,1),2);
  H(n/2+2:end,m/2+1) = rot90(H(2:n/2,m/2+1),2);

Similar operation but with negative sign applies to "phi" (phase):
phi(1,1) = 0;
  phi(1,m/2+1) = 0;
  phi(n/2+1,m/2+1) = 0;
  phi(n/2+1,1) = 0;
  phi(2:end,2:m/2) = -rot90(phi(2:end,m/2+2:end),2);
  phi(1,2:m/2) = -rot90(phi(1,m/2+2:end),2);
  phi(n/2+2:end,1) = -rot90(phi(2:n/2,1),2);
  phi(n/2+2:end,m/2+1) = -rot90(phi(2:n/2,m/2+1),2);

You can refer to this link for a good example of 2D fourier transform on a matrix and how the results should look like:
2D Fourier transform example


text: Q: Number of distinct centroids of triangles formed by 40 equally spaced points on a the perimeter of a square Suppose that we are given 40 points equally spaced around the perimeter of a square, so that four of them are located at the vertices and the remaining points divide each side into ten congruent segments. If P, Q, and R are chosen to be any three of these points which are not collinear, then how many different possible positions are there for the centroid of triangle PQR?


text:
Q: Customize {{#markdown}} behavior in Meteor I love Markdown. The concept is one of the most elegant and useful I've come across in my few years as a programmer. So I was excited to see Meteor implement a Showdown package and let me use it with the {{#markdown}} block helper.
However, when I started using it, my least favorite gotcha of markdown suddenly appeared: Indented Code Blocks.
Writing this:
<template name="home">
    {{#markdown}}
        Hello!!! Welcome to *My Site*!!
    {{/markdown}}
</template>

Results in this:

My Hello!!! Welcome to *My Site*!!

Formatted as CODE!!!!
I hate indented code blocks. They completely screw with attempts to actually use Markdown in a programming environment. Code is wildly indented, and for good reasons. It keeps things organized and makes behavior clear. So the fact that Markdown specifications have for years missed this is flabbergasting to me. Github's fenced code blocks are an infinitely more intelligent way to do this, since it doesn't require repetitive punching of the tab or space key, making it easier to edit, and it's clearer what's happening in the text.
Anyway, </rant>.
I want to customize the markdown being used by meteor. How?? I've looked through Atmosphere and searched markdown, and found nothing applicable. Also, I'm not sure how to use a Showdown extension in the meteor environment.
Any solutions welcome!! All I really want is a markdown implementation that doesn't have indented code blocks. They're stupid.

A: Why not implement your very own markdown helper:
// this is based on showdown package in spark branch
Handlebars.registerHelper('markdown', function (options) {
  return UI.block(function () {
    var self = this;
    return function () {
      var renderer = new marked.Renderer();
      var text = UI.toRawText(self.__content, self /* parentComponent */);
      return HTML.Raw(marked(trimIndentation(text), { renderer: renderer }));
    };
  });
});

where trimIndentation can look more or less like this:
function trimIndentation(text) {
  var regexp = null,
      result = "";
  return text.split('\n').map(function (line) {
    var match = (regexp || /(\s*)(\s*[^\s]+.*)/).exec(line);
    if (match) {
      !regexp && (regexp = new RegExp("(\\s{" + match[1].length + "})(.*)"));
      return match[2];
    }
    return line;
  }).join('\n');
}

In the above example I used the syntax of the new templating engine as well as I used the marked library instead of good old showdown (or should I say pagedown?), but you can of course do the same thing with a setup of your own choice.

A: Markdown has been deprecated it seems. You could replace the native markdown with markdown-it:
Install dependencies, npm install markdown-it markdown-it-attrs .
and setup markdown-it as your new default markdown Spacebar.
var md = require('markdown-it')();
var markdownItAttrs = require('markdown-it-attrs');
md.use(markdownItAttrs);
// md.disable("code")

You can decide what rules you want to disable or edit. In my case i disabled code blocks, but you can check out documentation for your own cases.
And then implement markdown as spacebar:
  Blaze.Template.registerHelper("markdown", new Template('markdown', function () {
    var view = this;
    var content = '';
    if (view.templateContentBlock) {
      content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING);
    }
    return HTML.Raw(md.render(content));
  }));

Be sure to remove markdown (meteor remove markdown) before implementing your version.
You can then call it using {{#markdown}} spacebar.


text:
Q: Conversion From XML to PLIST I have a to convert some 1000 xml files from XML to PLIST format(such as <dict> and <arrays>. Is there already existing tool/application or algorithm available?

A: What about this one?
http://iappcat.com/plist/bin2xml

A: Do you want to convert from within C#? If this is not the case, there is a tool called plutil available since Mac OS X 10.2:
plutil -convert xml1 some_file.plist

plutil can be used to check the syntax of property list files, or convert a plist file from one format to another.

A: Use an XSLT processor. C# has a nice API to do just that, but if you need to automate it on various platforms, use something portable like: xsltproc (which is available virtually everywhere), or SAXON XSLT (for XSL 2.0, but kind of a nuisance to use).


text:
Q: $Ref flag reappears even after deletion We have an Xpage based Web mail-in application. Some emails are coming with $Ref field (response document). We wanted to convert them into normal document by removing $Ref field so that it will no longer a response one. We are able to delete the $ref field but it reappears again after saving the documents from web interface(xpage) and it makes all such documents again response document. This started happening recently and working well earlier. Can you please suggest what is the root cause? How to stop it?
Sub Initialize
    On Error GoTo ErrorHandler
    Dim s As New NotesSession
    Dim db As NotesDatabase
    Dim coll As NotesDocumentCollection
    Dim doc As NotesDocument
    Dim count As Long

    Set db = s.Currentdatabase
    Set coll = db.Unprocesseddocuments
    MessageBox "Count : " & coll.Count
    'Exit Sub
    count = 1
    Set doc = coll.Getfirstdocument()

    While Not doc Is Nothing
        If doc.Hasitem("$Ref") Then
            Call doc.Removeitem("$Ref")
            Call doc.Save(false, false)
        End If
        Print count
        count = count + 1
        Set doc = coll.Getnextdocument(doc)
    Wend
    Exit Sub
ErrorHandler:
    MessageBox "Error " & Error & " at line " & Erl
    Exit Sub
End Sub

A: Try changing your save method to Call doc.Save(true, false).
This will force the document save, and also prevent creating a response.
Also verify that you are running the agent on a server not accessable to active users. Also verify that you are only running your agent once, and that it isn't enabled on multible replicas.

Have you tried using If(doc.isResponse) Then instead of If doc.Hasitem("$Ref") Then
Note: I am looking in the java editor, but assume that the isResponse method is also in LS.

A: Wheather a document is a response is controlled by a property of the used form. As long as you do not assign another form that is a "Document" and not a "Response", you will most probably not be able to remove the "isresponse"- flag. As already told: most probably your xpage saves the "frontend" document after your backend manipulation and resets the state (form validation enabled in xpage properties). But without source code of the xpage one cannot tell.

A: Check the form name. Emails can use either the "Memo" form or the "Reply" form. Emails using the Reply form are response documents. You may also need to change the form to "Memo".


text:
Q: "Undefined index" notice after submitting HTML form So I have a sign up form, and there is some PHP at the top of the code. It gives me this error:
Notice: Undefined index: register in /home/content/04/7195304/html/index.php on line 20

This is line 20:
if ($_POST['register']) {

Here is the submit button:
<input type="submit" class="gobutton" value="Register" name="register"/>

Edit
So here's my form tags:
<form action="index.php" method="POST">

A: You should check it like this:
if ( isset($_POST['register']) ) {}

to avoid getting notice.

A: Is your form using method="GET" instead of method="POST"?
You can also add addition checks to make sure the index exists, like this:
if (isset($_POST['register'])) {
    // do stuff
}

You can also debug the form submission like this:
var_dump($_POST);


text:
Q: Pytorch - Object of type 'method' has no len() So I'm trying to train a time series model using pytorch lightning library.
But after running the following code,
trainer = pl.Trainer(
    max_epochs = N_EPOCHS,
)

trainer.fit(model,data_module)

I'm getting this error,
/usr/local/lib/python3.8/dist-packages/torch/utils/data/sampler.py in __iter__(self)
     64
     65     def __iter__(self) -> Iterator[int]:
---> 66         return iter(range(len(self.data_source)))
     67
     68     def __len__(self) -> int:

TypeError: object of type 'method' has no len()

Also here's my data module initialization,
data_module = StockPriceDataModule(train_sequences, test_sequences, batch_size=BATCH_SIZE)
data_module.setup()

DataModule class
class StockPriceDataModule(pl.LightningDataModule):
    def __init__(self, train_sequences, test_sequences, batch_size = 8):
        super().__init__()
        self.train_sequences = train_sequences
        self.test_sequences = test_sequences
        self.batch_size = batch_size

    def setup(self, stage=None):
        self.train_dataset = StockDataset(self.train_sequences)
        self.test_dataset = StockDataset(self.test_sequences)

    def train_dataloader(self):
        return DataLoader(
            self.train_dataset,
            batch_size = self.batch_size,
            shuffle = False,
            num_workers = 2
        )

    def val_dataloader(self):
        return DataLoader(
            self.test_dataloader,
            batch_size=1,
            shuffle = False,
            num_workers=1,
        )

    def test_dataloader(self):
        return DataLoader(
            self.test_dataloader,
            batch_size=1,
            shuffle = False,
            num_workers=1,
        )

Im kinda beginner. So I was just following this video https://www.youtube.com/watch?v=ODEGJ_kh2aA to learn about time series forecasting with multiple features using LSTM. My code is almost same...
So what am I doing wrong?

A: Might be wrong here but you just need to create a method inside of your data loader class. Something like def len(self): return len(dataloader).
custom data loaders in Pytorch


text:
Q: ruby net/http put method with follow redirect I am working with a Nest thermostat api, thats sends a put request to api.nest.com, which then redirects to firebase, which is a backend as a service that they build their platform on. I can get this redirection to work with curl, but not rubies net/http.if someone could help i would greatly appreciate it.
Working curl output
 $ curl -v -L -X PUT "https://developer-api.nest.com/devices/thermostats/F_z36lno7kg_XJEL96C7wXx63kFCmZ22z?auth=ERASED" -H         "Content-Type: application/json" -d  '{"target_temperature_f": 72 }'
* Hostname was NOT found in DNS cache
*   Trying 184.73.153.254...
* Connected to developer-api.nest.com (184.73.153.254) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: developer-api.nest.com
* Server certificate: Go Daddy Secure Certificate Authority - G2
* Server certificate: Go Daddy Root Certificate Authority - G2
 > PUT /devices/thermostats/F_z36lno7kg_XJEL96C7wXx63kFCmZ22z?auth=ERASED      HTTP/1.1
 > User-Agent: curl/7.37.1
 > Host: developer-api.nest.com
 > Accept: */*
 > Content-Type: application/json
 > Content-Length: 29
 >
* upload completely sent off: 29 out of 29 bytes
 < HTTP/1.1 307 Temporary Redirect
 < Content-Type: application/json; charset=UTF-8
 < Access-Control-Allow-Origin: *
 < Cache-Control: private, no-cache, max-age=0
 < Location: https://firebase-apiserver01-tah01-     iad01.dapi.production.nest.com:9553/devices/thermostats/F_z36lno7kg_XJEL96C7wXx63kFCmZ22z?auth=ERASED
 < Connection: close
 < Content-Length: 0
 <
* Closing connection 0
* Issue another request to this URL: 'https://firebase-apiserver01-tah01-     iad01.dapi.production.nest.com:9553/devices/thermostats/F_z36lno7kg_XJEL96C7wXx63kFCmZ22z?auth=ERASED'
* Hostname was NOT found in DNS cache
*   Trying 54.196.205.148...
* Connected to firebase-apiserver01-tah01-iad01.dapi.production.nest.com     (54.196.205.148) port 9553 (#1)
* TLS 1.2 connection using TLS_DHE_RSA_WITH_AES_128_CBC_SHA
* Server certificate: *.dapi.production.nest.com
* Server certificate: Go Daddy Secure Certificate Authority - G2
* Server certificate: Go Daddy Root Certificate Authority - G2
> PUT /devices/thermostats/F_z36lno7kg_JEL96C7wXx63kFCmZ22z?auth=ERASED HTTP/1.1
> User-Agent: curl/7.37.1
> Host: firebase-apiserver01-tah01-iad01.dapi.production.nest.com:9553
> Accept: */*
> Content-Type: application/json
> Content-Length: 29
>
* upload completely sent off: 29 out of 29 bytes
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8     < Access-Control-Allow-Origin: *
< Cache-Control: private, no-cache, max-age=0
< Connection: close
< Content-Length: 29
<
* Closing connection 1

Non working Ruby implementation
this may look a little strange, i've been desperately hacking at it
the redirect seems to work, but reading the redirected page does not.
def fetch(uri, limit = 10)
    # You should choose better exception.
    raise ArgumentError, 'HTTP redirect too deep' if limit == 0

    uri = URI(uri)

    # Initializes the request by setting the HTTP headers, query and body parameters and the URI path
    req = Net::HTTP::Put.new(uri.path + 'devices/thermostats/F_z36lno7kg_XJEL96C7wXx63kFCmZ22z?auth=ERASED')
    req.set_form_data("set_temperature_f" => 79)
    req['Content-type'] = 'application/json'

    # Makes a HTTP PUT request using SSL
    res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(req)
    end

    puts res['location']

  case res
  when Net::HTTPSuccess     then res
  when Net::HTTPRedirection then fetch(res['location'], limit - 1)
  else
    res.error!
  end

end

irb(main):412:0* fetch('https://developer-api.nest.com/')
https://firebase-apiserver01-tah01iad01.dapi.production.nest.com:9553/devices/thermostats/F_z36lno7kg_XJEL96C7wXx63kFCmZ22z?auth=ERASED

Net::HTTPServerException: 400 "Bad Request"
from /opt/chef/embedded/lib/ruby/1.9.1/net/http.rb:2633:in `error!'
from (irb):407:in `fetch'
from (irb):405:in `fetch'
from (irb):412
from /opt/chef/embedded/bin/irb:12:in `<main>'


text:
Q: Can I use abstract methods to import file-specific formatting of (Python) pandas data? I have a class FileSet with a method _process_series, which contains a bunch of if-elif blocks doing filetag-specific formatting of different pandas.Series:
    elif filetag == "EntityA":
        ps[filetag+"_Id"] = str(ps[filetag+"_Id"]).strip()
        ps[filetag+"_DateOfBirth"] = str(pd.to_datetime(ps[filetag+"_DateOfBirth"]).strftime('%Y-%m-%d')).strip()
        ps[filetag+"_FirstName"] = str(ps[filetag+"_FirstName"]).strip().capitalize()
        ps[filetag+"_LastName"] = str(ps[filetag+"_LastName"]).strip().capitalize()
        ps[filetag+"_Age"] = relativedelta(datetime.today(), datetime.strptime(ps[filetag+"_DateOfBirth"], "%Y-%m-%d")).years
        return ps

I'd like to define an abstract format method in the class and keep these blocks of formatting in separate modules that are imported when _process_series is called for a given filetag.  Forgive the pseudo-code, but something like:
for tag in filetag:
    from my_formatters import tag+'_formatter' as fmt
    ps = self.format(pandas_series, fmt)
    return ps

And the module would contain the formatting block:
# my_formatters.EntityA_formatter
    ps[filetag+"_Id"] = str(ps[filetag+"_Id"]).strip()
    ps[filetag+"_DateOfBirth"] = str(pd.to_datetime(ps[filetag+"_DateOfBirth"]).strftime('%Y-%m-%d')).strip()
    ps[filetag+"_FirstName"] = str(ps[filetag+"_FirstName"]).strip().capitalize()
    ps[filetag+"_LastName"] = str(ps[filetag+"_LastName"]).strip().capitalize()
    ps[filetag+"_Age"] = relativedelta(datetime.today(), datetime.strptime(ps[filetag+"_DateOfBirth"], "%Y-%m-%d")).years
    return ps

A: You can create a function in it's own .py file and import it. If you create the same function in each file you can then call it.
here is f1.py:
def gimme():
    return 'format 1'

here is f2.py:
def gimme():
    return 'format 2'

Then you main file:
module_names = ['f1','f2']

for module_name in module_names:
    import_test = __import__(module_name)
    result = import_test.gimme()
    result = import_test.gimme()
    print(result)

Which gives the output:
format 1
format 2

A: Why not use globals with asterisk:
from my_formatters import *

for tag in filetag:
    fmt = globals()[tag + '_formatter']
    ps = self.format(pandas_series, fmt)
    return ps

I converted your pseudocode to real code.
globals documentation:

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

A: Your psuedocode could be made into real code like so:
import my_formatters

for tag in filetag:
    fmt = getattr(my_formatters, tag + '_formatter')
    ps = self.format(pandas_series, fmt)
    return ps