text:
Q: Load Testing in VS 2010 I am performing a webtest containing 3 pages once of which is a Silverlight page and a Controller page (every page is invoked from controller page and again the control is given back to Controller page).
When the 1st link id clicked it generates one ID that has to be carried forward in every transaction till the completion of the transaction.
The 1st page is a Silverlight page it interacts thorough WCF services to do the transaction.while submitting A request through Silver light the WCF service generates a ID but since the data from the service is returned in XML form, the entire output of the wcfservice if treated as a string data of which is hardcoded which is found at the time of recording.
So, After coming back from the 1st page (silverlight) to the Controller page it is always coming with the same ID which is stored as a string in the service in the recorded test. Since I am not getting the PROPER ID I am not able to move forward to other pages.
Actually, according to me system is not detecting the data returned from a WCF web service as a dynamic one and instead treating it as a hardcoded string.
How to resolve it, please help.
Some errors of Load test are written below:
Extraction Rule Error   ExtractValues event 139 No hidden fields were found in the response.
Exception   WebTestException    84  There is no context parameter with the name '$HIDDEN1.ConfiguratorTracker$hdnWorkFlowGuid' in the WebTestContext

A: Make sure you've created an Extraction Rule that is based on the Text Response and not a hidden field.  You might want to take a look at a RegEx Extraction Rule.


text:
Q: Cannot connect to .sock file
'Error: connect ENOENT unix:/run/php-fpm/php-fpm.sock\n    at Object.exports._errnoException (util.js:860:11)\n    at exports._exceptionWithHostPort (util.js:883:20)\n    at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)'

When I am connecting to my server, which requests PHP file from second server then error happens.
Sock file exists but PHP server fails to connect to it using net.Stream.
How can I fix this problem?
var connection = new net.Stream();
...
connection.connect(options.fastcgiHost);

redpajama_set_name: RedPajamaStackExchange


text:
Q: changing the marker size in python seaborn lmplot I am trying to change the size of the lmplot markers in seaborn. I have tried passing 's' or 'size' as arguments and neither of them work.
lm = sns.lmplot(x="totalX",y="NormI", hue="Data Type", data=df, palette="Set1", legend_out=False, S=20)

I have tried "s", "markersize", "size" I get no effect. I want to make the data points larger on the plot. Any help is much appreciated.

A: You want to use scatter_kws={"s": 100}
As in:
lm = sns.lmplot(x = "totalX", y = "NormI", hue = "Data Type", data = df, palette="Set1", legend_out=False, scatter_kws={"s": 100})

You can amend the integer value (currently 100) to change the size of the markers.
I don't know what your hue or palette data are, but this should work nonetheless.

A: I know this question specifies lmplot but thought I would add an answer for how to do this with a seaborn scatterplot.
df = sns.load_dataset("anscombe")
sp = sns.scatterplot(x="x", y="y", hue="dataset", data=df)

And to change the size of the points you use the s parameter
sp = sns.scatterplot(x="x", y="y", hue="dataset", data=df, s=100)


text:
Q: Upload Files in Yii2 (word, pdf, excel)? Hy, i can't upload files in yii2.
When i try to upload files, it is not uploaded on server, also can't past validation.
print_r($_FILES, true) - is empty.
In debuger don't have errors.
Here is my code:
Model:
class Model extends \yii\db\ActiveRecord
{
 public $files;
 public function rules()
 {
 return [
 [['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'doc, docx',
 'maxFiles' => 4],
 }
}

    public function uploadFiles(){
        if($this->validate()){
            foreach($this->files as $file){
                $path = 'upload/docs/' . $file->baseName . '.' . $file->extension;
                $file->saveAs($path);
                @unlink($path);
            }
            return true;
        }else{
            return false;
        }
    }

Controller:
public function actionCreate()
    {
        $model = new Model();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            $model->files = UploadedFile::getInstances($model, 'files');
            $model->uploadFiles();

            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);

View:
_form.php
<?php $form = ActiveForm::begin([
        'options' => ['enctype' => 'multipart/form-data'],
]); ?>

<?php echo $form->field($model, 'files[]')->fileInput(['multiple' => true]) ?>


text:
Q: IE caches and references old images for h:graphicImage I have an web application that uses JSF for form submission. I have a user select an image from a list followed by filling out and submitting a form. I then use the selected image and form input to annotate the image with the information. I then process a pdf file using the annotated images and email it to the user. After processing, I give the user the option to navigate back to the image selection page, or use the same images and go back to the form. Here is the jsf/html for the form that allows the user to navigate to their new page:
<h:form id="form" method="post">

        <h:commandButton value="images" action="#{artwork.backToArt}"/>

        <h:commandButton value="Form" action="#{artwork.backToForm}"/>

        <h:commandButton value="Upload" action="#{artwork.backToUpload}"/>

</h:form>

It seems that IE caches the annotated images and keeps those images on display regardless of my method calls.
Here are my methods:
public String backToArt()
{
    log.info("========= Setting back to art page ==========");
    this.backToForm();
    this.selectedValue = "";
    this.resizedArt = "";
    this.backArt = "";
    return "loginSuccess.xhtml";
}

public String backToUpload()
{   log.info("========= Setting back to upload ==========");
    this.backToForm();
    this.selectedValue = "";
    this.resizedArt = "";
    this.backArt = "";
    return "CSVSubmit.xhtml";
}

public String backToForm()
{
    log.info("============ Reseting all variables ==========");

    String temp = null;
    if (this.selectedValue != null)
    {
        temp = this.selectedValue;
        temp=temp.substring(temp.lastIndexOf(Dir.getDir("\\")) + 1, temp.length() - 4);
        this.selectedValue = temp;
    }

    log.info("Setting input variables");
    //set all previous values to blank
    //this.jobNum = "";
    this.quantity = null;
    this.headLine = null;
    this.codeNum = null;
    this.pass = null;
    this.expir = null;
    this.website = null;

    log.info("Setting front art to old image");
    //setting previous images to non-text
    if (temp.length() > 0)
    {
        temp = this.resizedArt;
        temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
        this.resizedArt=temp;

        log.info("Setting back art to old image");
        temp = this.backArt;
        temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
        this.backArt = temp;

        log.info("Deleting old text images");
        //start to delete text images
        File folderOne = new File(Env.textDestOne);
        this.deleteFiles(folderOne);
        File folderTwo = new File(Env.textDestTwo);
        this.deleteFiles(folderTwo);

    }

    log.info("============ Reset Complete ==========");
    return "FormSubmission.xhtml";
}

These methods reset the input variables and the images selected as well as deletes my annotated images depending on which button is pressed on that page. Looking at my logging, the methods are called and are processed, but no updating occurs for the images. When I process my pdf, the correct images and input are outputed, but what is viewed still shows old values. This means that my values are being stored properly and my methods are being called correctly. When I go to cancel and reprocess using Google Chrome, the images are updated properly.
Using all of this information, I have concluded that IE must be caching my images and not updating them with the correct values. I'm not sure how to override this, but I need to somehow clear the cache so that the images are updated to the correct values.
Edit: I noticed that when I refresh the page hitting F5, the pictures would update. Not sure what this means.


text:
Q: How do I force a rails ActiveRecord string column to only accept strings? I have a Post class with a title:string field
post = Post.create!
#=> Post created
post.title = "foo"
post.save!
# success
post.title = 1
post.save!
# succeeds, but I want it to throw a type mismatch exception

How do I get the last save! to throw a type mismatch?

A: This really runs against the grain of what Ruby is all about. If it's a string column, the database layer will take care of rendering that value as a string and saving it.
The concept of a type is different in Ruby than in other languages. Generally if an object supports to_s then it's considered to be string-enough to use, the basic tenet of Duck Typing.
If you pass in something that can't be rendered as a string you will get an exception. For example:
post.title = Post.find(5)

If you're looking to ensure your fields are not numerical, you should add a validation that enforces a particular format.

A: A new gem has been created to help validate types in rails and an explanatory blog post exists to answer more of the "why" it was created in the first place.
With this library your code would simple be:
class Post < ActiveRecord::Base
  validates_type :title, :string
end

This will throw an exception when an integer is assigned to title instead of quietly casting the title to a string and saving it.

A: Ruby is a duck-typed language and doesn't have type mismatches. If an object responds to to_s, Rails will call to_s on it and put it into a string field.
It sounds like what you really want is to validate the format of the value you're putting into the field (is the string "2" a valid value?), which is what validates_format_of is for. For example, if you want to ensure that the value has at least one non-digit character, you could do this:
class Post < ActiveRecord::Base
  validates_format_of :title, with: /\D/
end

Of course, you very well may want to customize that regex a bit more.
If you really can't stand duck-typing and want to make sure nothing but a true String goes into that column, you can override title=:
class Post < ActiveRecord::Base
  def title=(value)
    throw "`title' must be a String" unless value.is_a?(String)
    super
  end
end

Note that this won't be invoked when you do e.g. post[:title] = ... or post.write_attribute(:title, ...) but it should cover 95% of situations.

A: To answer the exact question, if you want to make sure that only objects of class String are saved to the field, you should add the following custom validation.
  validate :must_be_string

  def must_be_string
    errors.add(:base, 'The field must be String') unless title.class == String
  end

A: You can define a custom validator.
validates :title, type: String

and then:
class TypeValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors.add attribute, (options[:message] || "is not of class #{options[:with]}") unless
      value.class == options[:with]
  end
end


text:
Q: About how the alternative is selected on variant construction with a single argument? While reading the standard for the definition of the constructor [variant.ctor]:
template<class T> constexpr variant(T&& t) noexcept(see below);

I fall on an obscure limitation:

Let Tj be a type that is determined as follows: build an imaginary function FUN(Ti) for each alternative type Ti for which
  Ti x[] = {std::forward<T>(t)}; is well-formed for some invented variable x ...he overload FUN(Tj) selected by overload resolution for the expression FUN(std::forward<T>(t)) defines the alternative Tj which is the type of the contained value after construction.

I would like to understand what is the intent behind this limitation:

for which Ti x[] = {std::forward<T>(t)}; is well-formed?

Without this restriction, overload resolution would have eliminated all overloads for which the parameter can not be initialized by copy initinialization.
As far as I have dug, Ti x[] = {std::forward<T>(t)} should fall on [dcl.init.aggr]/2:

Otherwise, the element is copy-initialized from the corresponding initializer-clause or is initialized with the brace-or-equal-initializer of the corresponding designated-initializer-clause. If that initializer is of the form assignment-expression or = assignment-expression and a narrowing conversion ([dcl.init.list]) is required to convert the expression, the program is ill-formed.

So I see this limitation remove from the set of overloaded imaginary functions those that would involve a narrowing conversion when called. But maybe there is more? Am I wrong? Why an array initialization in the limitation, why not Ti x = {std::forward<T>(t)}? What is the intent behind "Ti x[] = {std::forward<T>(t)}; is well-formed"?

A: This wording is added by P0608R3 A sane variant converting constructor. The paper summarizes the change very well in the Proposed resolution section:

This paper proposes to constrain the variant converting constructor
  and the converting assignment operator to prevent narrowing
  conversions and conversions to bool. This section explains what
  exactly this change brings.

Therefore, the only intent of this change is to prevent narrowing conversions.
Why is an array used?  A drafting note in the Wording section answers your question:

[ Drafting note: The above uses Ti x[] = {std::forward<T>(t)}; rather than
  Ti {std::forward<T>(t)} to test whether the
  conversion sequence from T to Ti contains a narrowing
  conversion because whether
  Ti {std::forward<T>(t)} is well-formed may
  subject to whether Ti has an initializer_list
  constructor or whether Ti is an aggregate. Here is an
  example: https://godbolt.org/z/Ck5w-L – end note ]


text:
Q: Why are deleted branches not removed on the remote after pushing? I am using git-flow and what it does is that it deletes my feature/abc branch whenever I do :
git flow feature abc finish

It deletes the feature/abc branch after merging it with develop branch. After that I push my develop branch.
git push origin develop

Now, on the remote I am able to see the feature/abc branch, but not locally. So, does that means it deleted from local repo and that delete didn't got carried to remote ?
In my understanding :

*

*Since git is distributed, so the whole repo exists on all machines.

*So, if I do a change in my local repo and push it to a remote.

*Then, all my changes should be pushed to the remote, including the delete.

Conflict:

*

*How can local and remote git repo be different after a push.

=> Assume I am the sole developer on the code.
Update
My question is that I deleted the branch locally post merge. then I pushed the branch to which I merged, then why didn't that reflect on the remote ?
Since, GIT is DVCS and should be identical on push / pull. [ Considering I am the only dev ]
I didn't asked to create it either. It made the branch made my changes, merged it back then deleted the branch and pushed my updated develop branch. So, if it automatically detects the creation of those branches then why not the deletion ?

A:
Since, GIT is DVCS and should be identical on push / pull.

No, that's not really true. It is distributed so each repository within the net more or less contains the same data, but only more or less. When you use push and pull, you explicitely specify what is being pushed.
git push remote branch only pushes the the branch pointer branch to the remote repository and transfers all commits the remote repository needs to construct it, but not more. This means that only the commit the branch points to and all parents are actually pushed until the remote repository finds a common parent that it already has (in the worst case, this is the special zero-commit, i.e. the empty parent).
In the same way git pull remote branch only fetches the changes required to construct the remote branch remote/branch locally.
To really get all commits, you can use git fetch, and to push all local branches you can use git push --all. But again, it only fetches/pushes the commits necessary to construct the branches (or tags), not everything the repository has.
Now, when you push branches to the remote repository it will update only those branches you actually pushed, so when you deleted a local remote and push with --all, then only your local branches are pushed, and that does not include the deleted one. So your local Git does no longer know which branches you locally deleted (because they were merged) and as such cannot give that information to the remote repository automatically. What it can do however is tell the remote repository every branch it locally has so the remote can figure out which was deleted. You do this by using the option --prune. Note however that this removes all branches that do not exist locally, so it might make problems when working with multiple users that push different branches but don't pull the other ones (I actually never tested that though).
The best thing is obviously to remove locally deleted branches directly:
git push remote :branch


text:
Q: How to pass objects that are not of a primitive type (string, int, double, etc) in Java with private access modifier I am trying to build a complete program from the partial code of a book. The difficulty is when a variable's modifier is set to private, I can't access it from the main method of my BankTest class after instantiating an object. Am confused on how to pass the Dollar Object as I can't set it to a primitive type like double or float.
Is there a way to set the Dollar object with amount = 100, so that when I run the BankTest class, I could get it to print the getAmount = 100 ? I want to maintain the Dollar object as the parameter of a method if possible ?
final class BankTest {

    public static void main(String args[]) {
       BankAccount ba = new BankAccount();
       Dollar d = new Dollar(100);
       //d.setAmount(100.00);  "IF class Dollar method is PUBLIC"
       //ba.deposit(d);   "How to set the value of Dollar Object ??
       System.out.println("Balance available: " + d.getAmount());
    }

}

final class BankAccount {
     private Dollar balance;
     private boolean receipt;

public void deposit(Dollar amount, boolean receipt) {
  balance.add(amount);
 // if receipt == true, print receipt
}

public void deposit(Dollar amount) {
// validate and chain to base method
 deposit(amount, true);
}
}

final class Dollar {
    private double amount = 0;

    public Dollar(double _amount) {
        setAmount(_amount);
 }

 private void setAmount(double amt) {  //can only be called by within Dollar class

 // make sure amt is a valid currency amount
   amount= amt;
}

double getAmount() {
    return amount;
 }

public void add(Dollar amt) {
 // validate amt
 amount+= amt.getAmount();
 }
}

A: It seems Dollar was created to not be modified, but I wonder why the attribute is not final and why it can be modified by adding another Dollar object...
The idea is you have to create a new instance of Dollar every time you need a new value. Something similar happens with String and any primitive wrapper class (Integer, Float...).
As you are taking the code from a book you can decide how to deal with it: you can make the setter public or you can live with the current status and create a new object when needed.
You can already add an amount, so I think I'd modify the setter to public

A: Simply make setAmount public.
And also add a getter. eg getAmout() that returns the current dollar value.
Setters and getters are meant to be public, else they are pointless.
You could also pass the dollar value in the constructor.


text:
Q: Calculate Max and min dates i'm trying to calculate the max ( and min )  of a date.
My situation is the following.
I've create a date table like this:
Date =
ADDCOLUMNS (
CALENDAR (DATE(2008;1;1); DATE(2020;12;31));
"DateAsInteger"; FORMAT ( [Date]; "YYYYMMDD" );
"Year"; YEAR ( [Date] );
"Monthnumber"; FORMAT ( [Date]; "MM" );"Daynumber"; FORMAT ( [Date]; "DD" );
"YearMonthnumber"; FORMAT ( [Date]; "YYYY/MM" );
"YearMonthShort"; FORMAT ( [Date]; "YYYY/mmm" );
"MonthNameShort"; FORMAT ( [Date]; "mmm" );
"MonthNameLong"; FORMAT ( [Date]; "mmmm" );
"DayOfWeekNumber"; WEEKDAY ( [Date] );
"DayOfWeek"; FORMAT ( [Date]; "dddd" );
"DayOfWeekShort"; FORMAT ( [Date]; "ddd" );
"Quarter"; "Q" & FORMAT ( [Date]; "Q" );
"YearQuarter"; FORMAT ( [Date]; "YYYY" ) & "/Q" & FORMAT ( [Date]; "Q" );
"WeekNum"; WEEKNUM ( [Date] )
)

I have a table  "Table 1" like  this :
ID  ForeignKey  Date
1   A           01/01/2005
2   A           05/04/2008
3   A           31/12/2019
4   B           15/3/2017
5   B           16/05/2018
6   B           15/04/2019
7   C           05/06/2006
8   C           04/12/2015
9   C           15/04/2019

 And another table "Table 2" like this

ID2 Price
A   100
B   500
C   650

The "Date" table  is related to "Table1" by date and Table 1 is related to  "Table 2" by Table1.ForeignKey = Table2.ID2.
In my report i have a date slicer which is set for example to filter dates between Jan 1 2008 and June 30 2018.
My goal is  to calculate the max and min date for each one of table 2 in the selected period like this:
ID2 Price   MinDate         MaxDate
A   100     05/04/2008      05/04/2008
B   500     15/3/2017       16/05/2018
C   650     04/12/2015      04/12/2015

All i am able to achieve by doing somethig like this
MaxDate= CALCULATE ( LASTDATE ( Table1[Date] ); FILTER (
ALLSELECTED('Date') ;
'Date'[Date] <= Max('Date'[Date])
))

is the max and min dates in  the whole calendar (01/01/2008 - 12/31/2020) , which is not what i'm trying to do .
How can I do this?
Thanks in advance.

A: With the relationships you describe, simply use measures:
MinDate = CALCULATE ( MIN ( 'Table 1'[Date] ) )

and
MaxDate = CALCULATE ( MAX ( 'Table 1'[Date] ) )

And set your slicer on 'Date'[Date]
See https://pwrbi.com/so_55373837/ for example PBIX file


text:
Q: Query only changing last record value in sql server I have table in sql-server wiith XML datatype. I want to change the value of one of the attribute. The table looks like:
id--------version-------XMLdata
1---------2--------------<Package version="1"> .... </Package>
2---------2--------------<Package version="1"> .... </Package>
3---------2--------------<Package version="1"> .... </Package>
and so on

I am trying to update the version inside the XMLdata to 2, like:
id--------version-------XMLdata
1---------2--------------<Package version="2"> .... </Package>
2---------2--------------<Package version="2"> .... </Package>
3---------2--------------<Package version="2"> .... </Package>
and so on

I am running a query like:
UPDATE Tbl
SET XMLDATA.modify('replace value of (/Package[1]/@version)[1] with "2"')
WHERE version=2

But in the output I see only the last record getting version changed to 2.
Individual record also I am able to update with:
UPDATE Tbl
SET XMLDATA.modify('replace value of (/Package[1]/@version)[1] with "2"')
WHERE id=1

But not all records together. I don't understand what is the reason behind this.
I tried to create the copy of Table called Tbl2 and there the query is updating all the record version inside the XML data.
What could be the possible dependency which is stopping the query to change the version attribute value?

A: .modify() is very limited, it allows only one change per call, but this should work as expected. Try this out:
DECLARE @tbl TABLE (id INT,[version] INT, XMLdata XML);
INSERT INTO @tbl VALUES
 (1,2,'<Package version="1"> .... </Package>')
,(2,2,'<Package version="1"> .... </Package>')
,(3,2,'<Package version="1"> .... </Package>');

UPDATE @tbl SET XMLdata.modify('replace value of (/Package/@version)[1] with 2')
WHERE [version]=2;

SELECT * FROM @tbl;

You could use sql:column("version") instead of 2 without a WHERE to set all XML-version attributes in sync with the version column of the table in one call:
UPDATE @tbl SET XMLdata.modify('replace value of (/Package/@version)[1] with sql:column("version")');


text:
Q: Exact Target Create Subscriber issue (using SOAP API) When I try to create a subscriber using SOAP API, I get this error:
Status Message: Access violation for account id (xxxxxxx). Error Code: 12020 Ordinal: 0
I also included the ChannelMemberID in the code. In the link, the error code 12020 is listed as
OYBAccessError
Can somebody explain what this means and how to resolve it?
Thank you.
Sai.

A: Its kind of a weird issue.  I've asked around, and this happens when the ChannelMemberID set on a Subscriber and the MemberID it listed was not a child of the MemberID of the user making the API request.  So, I would double check that ChannelMemberID, and perhaps try leaving it blank.


text:
Q: Input Pipeline for LSTM with Timeseries Data Using a Large Dataset with Multiple .csv in Tensorflow Currently I can train a LSTM network using one csv file based on this tutorial: https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/
This code generate sliding windows where the last n_steps of the features are saved to predict the actual target (similar to this: Keras LSTM - feed sequence data with Tensorflow dataset API from the generator):
#%% Import
import pandas as pd
import tensorflow as tf
from tensorflow.python.keras.models import Sequential, model_from_json
from tensorflow.python.keras.layers import LSTM
from tensorflow.python.keras.layers import Dense

# for path
import pathlib
import os

#%% Define functions
# Function to split multivariate input data into samples according to the number of timesteps (n_steps) used for the prediction ("sliding window")
def split_sequences(sequences, n_steps):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find end of this pattern
        end_ix = i + n_steps
        # check if beyond maximum index of input data
        if end_ix > len(sequences):
            break
        # gather input and output parts of the data in corresponding format (depending on n_steps)
        seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]
        X.append(seq_x)
        y.append(seq_y)
        #Append: Adds its argument as a single element to the end of a list. The length of the list increases by one.
    return array(X), array(y)

# Set source files
csv_train_path = os.path.join(dir_of_file, 'SimulationData', 'SimulationTrainData', 'SimulationTrainData001.csv')

# Load data
df_train = pd.read_csv(csv_train_path, header=0, parse_dates=[0], index_col=0)

#%% Select features and target
features_targets_considered = ['Fz1', 'Fz2', 'Fz3', 'Fz4', 'Fz5', 'Fz_res']
n_features = len(features_targets_considered)-1 # substract the target

features_targets_train = df_train[features_targets_considered]

# "Convert" to array
train_values = features_targets_train.values

# Set number of previous timesteps, which are considered to predict
n_steps = 100

# Convert into input (400x5) and output (1) values
X, y = split_sequences(train_values, n_steps)
X_test, y_test = split_sequences(test_values, n_steps)

#%% Define model
model = Sequential()
model.add(LSTM(200, activation='relu', return_sequences=True, input_shape=(n_steps, n_features)))
model.add(LSTM(200, activation='relu', return_sequences=True))
model.add(LSTM(200, activation='relu'))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse', metrics=['mae'])

#%% Fit model
history = model.fit(X, y, epochs=200, verbose=1)

I now want to expand this example to efficiently train the network with different csv files. In the data folder I have the files 'SimulationTrainData001.csv', 'SimulationTrainData002.csv', ..., 'SimulationTrainData300.csv' (about 14 GB).
To achieve this, I tried to adopt the code of this input pipeline example: https://www.tensorflow.org/guide/data#consuming_sets_of_files, which works to a certain extend. I can show the training files in the folder with this change:
# Set source folders
csv_train_path = os.path.join(dir_of_file, 'SimulationData', 'SimulationTrainData')
csv_train_path = pathlib.Path(csv_train_path)

#%% Show five example files from training folder
list_ds = tf.data.Dataset.list_files(str(csv_train_path/'*'))

for f in list_ds.take(5):
  print(f.numpy())

One problem is, that in the example the files are pictures of flowers and not time series values and I do not know at which point I can use the split_sequences(sequences, n_steps) function to create the sliding windows to provide the necessary data format to train the LSTM network.
Also, as far as I know, it would be better for the training process, if the generated windows of the different files would be shuffled. I could use the split_sequences(sequences, n_steps) function on every csv file (to generate X_test , y_test) and join the result in one big variable or file and shuffle the windows, but I do not think this is an efficient way and it also had to be redone if n_steps will be changed.
If somebody could suggest a (established) method or example to preprocess my data, I would be very thankful.

A: You can use the TimeSeriesGenerator after consuming those sets of files.
Here is the reference link.
As per the documentation:
'''
This class takes in a sequence of data-points gathered at equal intervals, along with time-series parameters such as stride, length of history, etc., to produce batches for training/validation.
'''
Provided examples for  both univariate & multiple variate scenario
Univariate Example:

from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM
import numpy as np
import tensorflow as tf

# define dataset
series = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# reshape to [10, 1]
n_features = 1
series = series.reshape((len(series), n_features))

# define generator
n_input = 2
generator = TimeseriesGenerator(series, series, length=n_input, batch_size=8)

# create model
model = Sequential()
model.add(LSTM(100, activation='relu', input_shape=(n_input, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')

# fit model
model.fit_generator(generator, steps_per_epoch=1, epochs=500, verbose=1)

#sample prediction
inputs = np.array([9, 10]).reshape((1, n_input, n_features))
result = model.predict(inputs, verbose=0)
print(result)

Multi-variate Example
from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM
import numpy as np
import tensorflow as tf

# define dataset
in_seq1 = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
in_seq2 = np.array([15, 25, 35, 45, 55, 65, 75, 85, 95, 105])
# reshape series
in_seq1 = in_seq1.reshape((len(in_seq1), 1))
in_seq2 = in_seq2.reshape((len(in_seq2), 1))
# horizontally stack columns
dataset = np.hstack((in_seq1, in_seq2))
# define generator
n_features = dataset.shape[1]
n_input = 2
generator = TimeseriesGenerator(dataset, dataset, length=n_input, batch_size=8)
# define model
model = Sequential()
model.add(LSTM(100, activation='relu', input_shape=(n_input, n_features)))
model.add(Dense(2))
model.compile(optimizer='adam', loss='mse')
# fit model
model.fit_generator(generator, steps_per_epoch=1, epochs=500, verbose=1)

# make a one step prediction out of sample
inputs = np.array([[90, 95], [100, 105]]).reshape((1, n_input, n_features))
result = model.predict(inputs, verbose=1)
print(result)

Note: All of these were simulated using Google Colaboratory


text:
Q: Sharepoint 2010 user not found error I am getting this error when I try to do the following:

*

*accessing a library settings

*accessing a workflow settings

*accessing a list settings

*accessing a task settings

p.s.

*

*I'm using SharePoint 2010 on Windows Server 2008 64-bit

*I am using an Administrator account.

*I recently installed the Active Directory on the server

Regrds

A: Check the workflows. Browse to the site, and Edit in SharePoint Designer. If you click on the workflows, there may be one there that was created by a user that no longer exists, or a local user that is not in AD. Save and republish each of them, and you will probably be allright. Bumped into this when our SP admin got married, and her account changed.
A long term solution would be to have a functional account that is not tied to an individual be the login that publishes all of the workflows. Each workflow runs as the user that publishes it, so any account changes can break a workflow.


text:
Q: Caspol: Calling a method from an assembly on a network share I have compiled an assembly using the Microsoft Strong Name key convention and marked it to be "AllowPartiallyTrusted".
I am testing the application against this assembly from two different machines.
One is running windows 2003 server and the other machine is on windows XP Professional.
I am able to invoke the methods on the assembly from the Win 2003 server, but when it comes to the XP machine, it fails.
I have tried to set the INTRANET ZONES TO FULL TRUST, but that hasn't worked for the XP.
One difference between the XP and the 2003 server is that the XP is 32 bit and has frameworks 1 -4.0 installed on it. The 2003 has just the 3.5 SP1 installed on it.
I am an administrator on the XP machine, but not on the 2003 machine where it works.
This is driving me nuts.

A: The Windows permissions shouldn't matter - it's a Code Access Security issue. It's difficult to diagnose the problem without knowing more about the errors you're encountering. The AllowPartiallyTrustedCallersAttribute (APTCA) is meant to allow partially trusted code to call fully trusted code, but the .NET 4.0 security model has changed the way APTCA works. See this blog post for details, but in .NET 4.0 APTCA assemblies are marked SecurityTransparent, and cannot call SecurityCritical assemblies, which is the default protection level for .NET assemblies.
So, if your APTCA assembly in .NET 4.0 is doing anything privileged, like calling SecurityCritical code or asserting permissions, then it will fail. You should consider making it SecuritySafeCritical so that it can be called by SecurityTransparent code and call SecurityCritical code. Of course, you'll want to make sure that it can't be exploited by untrusted libraries, just like APTCA code.


text:
Q: Boundary conditions for vector wave equations Assume the time-harmonic case of Maxwell's equations, one can obtain the following vector wave equations:
$$
\nabla\times(\frac{1}{\epsilon_r}\nabla\times\mathrm{H})-k_0^2\mu_r\mathrm{H}=\nabla\times(\frac{1}{\epsilon_r}\mathrm{J})
$$
What will be the expression of homogeneous boundary conditions for it? In the book "Finite Element Method in Electromagnetics" by Jianming Jin, page 183, he imposed homogeneous Dirichlet and Robin conditions such that
$$
\hat{n}\times\mathrm{H}=0
$$
on $S_1$ with
$$
\frac{1}{\epsilon_r}\hat{n}\times(\nabla\times\mathrm{H})+\gamma_h\hat{n}\times(\hat{n}\times\mathrm{H})=0
$$
on $S_2$, where $\hat{n}$ is the surface unit normal. I thought of $\hat{n}\times\mathrm{H}$ as expressing the continuity condition, but what about the second boundary condition? Can someone explain to me the physical meaning of it? I just cannot see how it makes sense. Thank you!


text:
Q: Qt ODBC Microsot SQL Server 2014 issue which happens once a month I have developed for windows server 2016, a server application written in C++ with Qt/ODBC/MS Sql Server 2014 which works well. Users log into the application with their login/password. The server application make requests to MS SQL server thanks to ODBC driver.
But about once a month, the login functionnality stops to work and it seems that the application cannot access to the database anymore.
The login process uses this peace of code :
SQLServerConnexion::SQLServerConnexion(const std::string &dbname)
{
 dbname_ = QString(dbname.c_str());
 database_ = QSqlDatabase::addDatabase("QODBC", generatedUUID().c_str());
 database_.setDatabaseName(dbname_);

 if (database_.open()) {
    qDebug() << dbname_ << "opened";
 }
 else {
    qDebug() << "Cannot open " << dbname_;
 }
}

dbname follows the following pattern "DB_NAME; MARS_Connection=YES;"
When I restart the application, users can log into the application.
I don't understand why this issue happens about once a month. Have you got some ideas to solve that issue ?


text:
Q: How to automatically export dashboard in databricks jobs I have a notebook in databricks that I put into a job to run every day at specific time, and I've also created dashboard from this notebook, how can I have the dashboard results exported automatically every time the job runs? I'm aware of the Jobs API, but I can't figure out the right command to do this. Right now I'm using the python package databricks-api (https://pypi.org/project/databricks-api/) to connect to databricks. My ultimate goal is to automate the process of running the notebook, create dashboard, and then save the results.

A: Did you figure it out? I have the same question. This won't be the full answer, but to export just the notebook use the API as demonstrated at at these two links:
1
2
This curl command will export a notebook as HTML. What it doesn't do is clearly present the dashboard cleanly, without code, as is so easily done via the Databricks UI:
curl -n -H "Content-Type: application/json" -X GET -d @- https://<mysite>.cloud.databricks.com/api/2.0/workspace/export <<JSON
{
  "path": "/Users/my@login.com/notebook_001",
  "format": "HTML"
}
JSON

or to download an html file manually:
curl -n -o example.html "https://<yoursite>.cloud.databricks.com/api/2.0/workspace/export?format=HTML&direct_download=true&path=/Users/you@yourlogin.com/notebookname_001"

You're probably well beyond this, but it assumes a .netrc and token per this article.
[I would be happy to have edits showing how this process could be changed to export the HTML without code, or better yet in the dashboard view. I too have been over the Jobs API and do not see how it's relevant to an already-run notebook which does not require an online cluster to view the dashboard.]


text:
Q: JDOM setText() Not Working I have a method that parses for a specific String and is supposed to change that String using JDOM's setText() method. But when I look at the document after the program finishes, the String is never changed:
public void findVirtue(String word, Element a) throws JDOMException,
        IOException, TransformerFactoryConfigurationError,
        TransformerException {
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(xml);
    Pattern p = Pattern.compile("(?i)\\bvirtue('?s)?\\b",
            Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(word);
    List<String> virtue = new ArrayList<String>();
    // Need to Increment a counter

    while (m.find()) {
        virtue.add(m.group());
        log("FOUND : " + m.group());
        log("REPLACEMENT : " + m.replaceAll("Ryan"));
        a.getChild("LINE").setText(m.replaceAll("Ryan"));
        XMLOutputter newDoc = new XMLOutputter();
        newDoc.setFormat(Format.getPrettyFormat());
        newDoc.output(document, new FileWriter(
                "C:\\Users\\Ryan\\workspace\\Tragic\\result" + xml.getName()));
        //counter();
    }
}

Now I know it is not a problem with the regex since I am able to log the output to another file. But when I use:
a.getChild("LINE").setText(m.replaceAll("Ryan"));

It never works. Can someone please tell me what I am doing wrong?

A: I see the problem. You are updating  a.getChild("LINE") element, but writing document to the file.
How to solve this?
Update document object child, something like document.getChild("LINE") (or) write element to file like newDoc.output(a,......)


text:
Q: joint density of mixed RVs: A random vector and its cardinality Suppose $X$ and $Y$ are two continuous random vectors and $ m = |Y|$ is a discrete random variable that denotes the size of the continuous random vector $Y$, i.e. the number of its columns (the cardinality) is random.
$$p(\mathbf{Y}|\mathbf{X}) = \sum_{i=0}^{\infty}p(\mathbf{Y},i|\mathbf{X})\delta(i-|\mathbf{Y}|) = p(\mathbf{Y},|\mathbf{Y}||\mathbf{X}) = p(\mathbf{Y},m|\mathbf{X})$$
I need to know what probability principle or theorem is used to finish the proof above.


text:
Q: Which radio button is selected in lightning How do I know in the JS controller which radio button option is selected. I tried the below code for which I see "undefined" in console log

    <input type="radio" aura:id = "nameRadioAuraId" id="nameRadioId" name="options" checked = "Checked" onclick="{!c.handleRadioClick}" />

        First/Last Name

    <input type="radio" aura:id = "tokenRadioAuraId" value = "tkn" id="tokenRadioId" name="options" onclick="{!c.handleRadioClick}"/>

        Token

//controller.js
var selectedRadioOption = component.find("tokenRadioAuraId");
console.log("val1 = "+selectedRadioOption);
console.log("val1 = "+selectedRadioOption.get("v.selected"));

I tried. v.value, v.selected, v.checked none of them seem to be working. Can some point me in the right direction? Thanks!

A: I have had to use the following:
var opts = document.querySelector('input[name="options"]:checked').value;

for my radios

A: Try with event.target.value in controller
handleRadioClick:function(cmp,event,helper){
    console.log("val1 = "+event.target.value);
}

By using button click you may use Id to get value
   buttonclick : function(component,event,helper){
        var selectedRadioOption = document.getElementById("tokenRadioId").value;
        console.log(selectedRadioOption);
    }

Or you can get value from button click using
In component you may use
 <ui:inputRadio aura:id = "tokenRadioAuraId" value = "tkn" name="options" click="{!c.handleRadioClick}"/>

In controller
 buttonclick : function(component,event,helper){
        var selectedRadioOption = component.find("tokenRadioAuraId");
        console.log(selectedRadioOption.get("v.value"));
    }

A: I ended up doing a "value" attribute that I update in the JS Controller whenever an input radio is selected:
<aura:attribute name="value" type="String" access="global"/>

<input type="radio" name="options" id="nameRadioId" onchange="{!c.updateValue}"/>

And in the JS Controller I just use event.currentTarget.id.

If for whatever reason you can't/don't want to use the id, you can make use of a data-attribute:
<input type="radio" data-value="Whatever value I want" name="options" id="nameRadioId" onchange="{!c.updateValue}"/>

And then get it in your JS Controller with event.currentTarget.dataset.value.
Then whenever you need to know which radio option is selected, just use the "value" attribute of your component.

A: I found that you get the 'value' directly from event.currentTarget and not through the dataset. You can also get the id and name if required.
My function is:
onWhatToUse: function(cmp, evt) {
    var selected = evt.currentTarget.value;
    cmp.set("v.whatToUse", selected);
    //console.log (evt.currentTarget.id);
    //console.log (evt.currentTarget.name);
 }//onWhatToUse

I wanted the buttons horizontal and used this structure:
<fieldset class="slds-form-element">
                <legend class="slds-form-element__legend slds-form-element__label">Which Location To Use:</legend>

                        <input type="radio" id="rco" name="locations" checked="true" value="company"  onchange="{!c.onWhatToUse}" />

                            Use Company

                        <input type="radio" id="ryou" name="locations" value="you" onchange="{!c.onWhatToUse}"/>

                            Use Your Location

                        <input type="radio" id="rhq" name="locations" value="headquarters"  onchange="{!c.onWhatToUse}"/>

                            Use Headquarters

            </fieldset>

I have an attribute to hold the state:
<aura:attribute name="whatToUse" type="String"/>


text:
Q: Optimizing stochastic loss functions informed by bayesian inference Recently, I've been working on a design that uses Bayesian parameter estimation in conjunction with black box optimization. I haven't seen/read much about this approach so I'm not sure if it's principled or misguided.
Say that I'm interested in choosing the best $\theta$ such that $p(y|x,\theta)$ maximizes a reward or minimizes loss where $\theta$ could represent one (or more latent parameters.)
The general flow is use:

*

*Use Bayesian software (PyMC3, Stan, etc) to estimate $p(y|x,\theta)$.

*Using the posterior chain derived, design a loss function, such that instead of using point estimates (like the mean), draw parameter values randomly from the posterior chain.

*Use any optimization algorithm (Bayesian optimization, genetic algorithm, etc.) such that given the sampled reward function from step 2.

In my experience, this design has worked well. Rather than optimizing $\theta$ to maximize a reward signal / minimize a loss function based on a point estimate, the stochastic nature of using posterior chain parameter samples enables the optimization algorithm to get a sense for the variance around the optimal value.
I'm curious, has anyone done this sort of design (Bayesian inference -> sampled loss function parameters -> optimization algorithm?) Are there any reasons why this might not be a good idea?
Edit in response to request for clarification:
Recently, I've worked on replicating results from a Google 2017 paper where they used carryover and saturation effects in a media mix model. In plain English, they learn for any given marketing channel, they infer the amount of spend that results in saturation (ie excess spend results in diminishing returns) and they model the time component (marketing spend today might reach peak consumer influence in x days.) The authors choose a bayesian inference design, however, a frequentist one likely could have been used instead.
I give the above context because the reward function is not directly observed, it's latent and inferred through statistical inference. Simply using the mean saturation and carryover effect parameters is certainly one approach; it would create a discrete reward signal; but in my option this marginalizes a lot of the information gained via bayesian inference (the posterior samples.)
So my solution was to draw from the saturation and carryover posterior chain in each optimization iteration to get a more holistic view of the parameter space when optimizing.


text:
Q: Replace objects in json with their sum using JQ Trying to solve the problem, but even don't know how to start.
I have json like this
[
  {
    "Count": "226",
    "Action": "1",
    "Status": "1",
    "Client": "26"
  },
  {
    "Count": "224",
    "Action": "1",
    "Status": "2",
    "Client": "26"
  },
  {
    "Count": "3",
    "Action": "1",
    "Status": "6",
    "Client": "26"
  },
  {
    "Count": "233",
    "Action": "2",
    "Status": "1",
    "Client": "26"
  },
  {
    "Count": "7",
    "Action": "2",
    "Status": "2",
    "Client": "26"
  }
]

And I need to get sum of counters for distinct Action where Status > 1. Result should replace summarized elements.
Example of result:
[
  {
    "Count": "226",
    "Action": "1",
    "Status": "1",
    "Client": "26"
  },
  {
    "Count": "227",
    "Action": "1",
    "Status": "2",
    "Client": "26"
  },
  {
    "Count": "233",
    "Action": "2",
    "Status": "1",
    "Client": "26"
  },
  {
    "Count": "7",
    "Action": "2",
    "Status": "2",
    "Client": "26"
  }
]

As you can see, field Count in element with "Action": "1" and "Status": "2" was increased on value of object with "Action": "1" and "Status": "6"
I don't know how to do it. Any help or advice would be appreciated.

A: This solution aggregates into the first items within each duplicate list (which is not obvious from your sample data, see the comments).
group_by groups the items to aggregate, which is determined by a .Status greater 1 and the content of .Action. Then, with map each grouped list's first (.[0]) item's .Count field is calculated by adding up all .Count fields' values. The output within each group is the first (.[0]) element.
jq '
  group_by([(.Status | tonumber > 1), .Action])
  | map(.[0].Count = (map(.Count | tonumber) | add | tostring) | .[0])
'

[
  {
    "Count": "226",
    "Action": "1",
    "Status": "1",
    "Client": "26"
  },
  {
    "Count": "233",
    "Action": "2",
    "Status": "1",
    "Client": "26"
  },
  {
    "Count": "227",
    "Action": "1",
    "Status": "2",
    "Client": "26"
  },
  {
    "Count": "7",
    "Action": "2",
    "Status": "2",
    "Client": "26"
  }
]

Demo
As .Status and .Count are strings, not numbers, it was necessary to convert them back and forth using tonumber and tostring. You may want to, especially if you have more calculations to process, first convert them into numbers, then do all the (now simpler) processing, and finally convert them back (if necessary).
jq '
  map((.Status, .Count) |= tonumber)
  | group_by([(.Status > 1), .Action])
  | map(.[0].Count = (map(.Count) | add) | .[0])
  | map((.Status, .Count) |= tostring)
'

Demo


text:
Q: How to draw a vertical line in a .NET chart I would like to draw a vertical line along x=0. I've tried the code below, but instead of all the points being drawn with x=0, they are drawn with x values of 1, 2, 3, 4, 5, respectively. I am able to draw a vertical line at what appears to be any x value other than 0.
The code below also sort of works if I change the x value of any of the points to something other than 0. Is this some sort of bug with the Chart in .NET? Is there a way to draw a vertical line along x=0?
chart1.Series["Series1"].ChartType =
    System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine;
chart1.Series["Series1"].Points.AddXY(0, 0);
chart1.Series["Series1"].Points.AddXY(0, 2.5);
chart1.Series["Series1"].Points.AddXY(0, 5);
chart1.Series["Series1"].Points.AddXY(0, 10);
chart1.Series["Series1"].Points.AddXY(0, 20);

A: Chart displays incorrectly when all x values are zero


text:
Q: How to get JAR from Maven for Android How can we get jar files/library files from Maven repo. Maven provides AAR file.
I know using Android Studio is best but I am facing some issues with my system, so for some time I have to use eclipse.
I want to get jar file/library project for this project
https://github.com/dmytrodanylyk/android-process-button/
Please suggest me some solution.

A: You can download the source from here and export in to your project and if you want you can create jar easily.

A: The code you're trying to get is an Android library, and requires some resource to work. You need to download the res folder too from here and you need to add it to your project res folder.


text:
Q: Selectively ignore debug breaks for specific files in VS2005 Every time I run a project in debug mode, I get 4 consecutive breaks at the start that I have to hit continue for each time. They are in the same file at the same point.
It would be great if I could say to simply ignore these since they don't impact functionality.
The obviously better route would be to try to resolve it so it doesn't cause a break/continue prompt but I think that's more effort that it's worth at the moment.
It would be great if the solution related only to my specific environment so I wouldn't have to undo/do it each time I pull/push a build.

A: Try to use break point condition or break point filer.


text:
Q: How can I display a set of data from 2 database tables? Winforms I created a Winforms app and a database with 2 tables in Visual Studio:

*

*Member - holds details like first name

*Membership - holds a membership type basic, VIP.

I want to display membership type from the Membership table and the FirstName from the Member table.
I have added the foreign key for the membership table to Member. Now I try to create the view as below. While this works, when I show results of the view , it creates all the requested data 3 times:
MemberID   FirstName   Type
-------------------------------
    1      Tommy       Basic
    2      Sammy       VIP
    3      Alley       Basic
    1      Tommy       Basic
    2      Sammy       VIP
    3      Alley       Basic
    1      Tommy       Basic
    2      Sammy       VIP
    3      Alley       Basic

The code for the view:
CREATE VIEW [dbo].[Memberdetails]
AS
    SELECT Member.MemberId, Member.FirstName, Membership.Type
    FROM [Member], [Membership]

Not sure how to fix it just to display it once.

A: You need add field MembershipId to Member table.
You can use where clause
CREATE VIEW [dbo].[Memberdetails]
AS
   SELECT Member.MemberId, Member.FirstName, Membership.Type
   FROM [Member], [Membership]
   WHERE [MemberShip].[Id] = [Member].[MembershipId]

Or use join clause
CREATE VIEW [dbo].[Memberdetails]
AS
   SELECT Member.MemberId, Member.FirstName, Membership.Type
   FROM [Member]
   JOIN [Membership] ON [Membership].[Id] = [Member].[MembershipId]


text:
Q: Axioms of Choice in constructive mathematics There is a widely accepted opinion that the Axiom of Countable Choice (further, ACC)
$$ \forall n\in \mathbb{N} . \exists x \in X . \varphi [n, x] \implies \exists f: \mathbb{N} \longrightarrow X . \forall n \in \mathbb{N} . \varphi [n, f(n)] $$
is justified constructively due to certain interpretations of intuitionistic logic (for example, BHK). For example, this question already highlights interpretation of ACC. My question is more of a "practical" one: the best I hope for is to see an example of algorithm extraction from a constructive theorem which used ACC.
ACC means that if for any natural $n$ and any $x$ of any set $X$ there is a proof that $\varphi [n, x]$ holds, then there exists a function that produces $x$'s such that $\varphi [n, x]$ holds for any given $n$ as input. The catch is, a constructive proof already means a certain procedure of finding $x$ with the property $\varphi [n, x]$.
There have been, however, doubts in accepting ACC (or dependent choice) in constructive mathematics (see, for example, 1, 2, 3, 4, 5, 6). Since the question whether to accept ACC (or dependent choice) is rather methamatematical, I'd like to discuss its meaning in terms of algorithms (or computer programs).
Roughly speaking, if you "put" a proof on paper and everything is constructive, and say you used ACC, does it mean that it somehow hinders programming this proof?
The things I learned from the literature are:
(1) Some important constructive results rely on ACC or even dependent choice. It concerns the Fundamental Theorem of Algebra, existence of bases of Hilbert spaces, existence of square roots of complex numbers, some facts about complete metric spaces. For example, Bridges, Richman and Schuster showed that the Bishop's lemma used at least a certain weaker form of ACC:
Lemma. Let $A$ be a non-empty located complete subset of a metric space $X$ and $x$ some point in $X$. Then, there exists a point $a \in A$ such that $\rho(x, a) > 0 \implies \rho(x, A) > 0$.
(2) There is a distinction between general Cauchy sequences and the so called modulated Cauchy sequences. The former have the form:
$$ \forall n \in \mathbb{N}. \exists N \in \mathbb{N}. \forall k,m \ge N. |x_k - x_m | \le \frac{1}{n} $$
whereas the letter have the so called convergence modulus $\mathcal{N}: \mathbb{N} \rightarrow \mathbb{N}$:
$$ \forall n \in \mathbb{N}. \forall k,m \ge \mathcal{N}(n). |x_k - x_m | \le \frac{1}{n} $$
It is easy to see that both are equivalent as long as ACC holds. In particular, Cauchy and Dedekind reals are isomorphic. Consequently, Cauchy reals are Cauchy complete. It not the case if ACC does not hold as was pointed out by Lubarsky. However, every modulated Cauchy sequence of modulated Cauchy reals converges to a modulated Cauchy real.
(3) ACC was given various interpretations. For example, non-deterministic algorithm, black-box etc. Some even claimed that ACC is in some sense responsible for "discontinuities" in computation.
(4) There does not seem to be a proof assistant which allows program extraction under ACC. In Coq, one can define ACC in the Type universe, but in Prop it has to be an axiom and Coq cannot crack it open to extract a program. I am aware only of results on "computational" content of ACC which use bar induction/recursion, fan theorem, Gödel numbering etc.
(5) In some formal systems, ACC and even stronger axioms of choice can be proven. For example, in Martin-Löf's type theory. Another example is this system of Ye which is even weaker than Bishop's constructive mathematics. Theorem 11, item 16 has a form similar to a choice axiom. Consequently, Ye, Lemma 27 is the Bishop's lemma.

Now, my question is
What exactly is ACC and what exactly is an extracted program from ACC? Are there any practical examples? What does it mean for a "realized" ACC to be a "black box" program?
Particular question: why does one need ACC to prove the Bishop's lemma? Take, for example, construction in Lemma 27 of Ye.
He explicitly constructs a Cauchy sequence, which is even modulated in an evident way, and shows the implication. Where exactly is an ambiguity of choices?

Remark: variations of this question may already be found here and SE (for example, my own questions 1 and 2), but I still do not fully understand how to interpret ACC constructively.

A: The following is a proof in Coq, or am I missing something?
Goal forall (X : Set) (phi : nat -> X -> Prop),
    (forall (n : nat), {x : X | phi n x})
    -> {f : nat -> X | forall n, phi n (f n)}.
Proof.
  intros X phi all.

  exists (fun n => proj1_sig (all n)).
  intros n.
  destruct (all n).
  simpl.
  auto.
Qed.


text:
Q: AccessTokens returned for Active Directory are different between sample projects I've been experimenting with Azure Active Directory access for Java using two sample projects:
1) https://github.com/AzureAD/azure-activedirectory-library-for-java which builds a stand-alone war using OAuth tokens for security, and
2) https://github.com/Microsoft/azure-spring-boot/tree/master/azure-spring-boot-samples/azure-active-directory-spring-boot-backend-sample for spring-boot embeded containers
I've come across quite a difference in the way the APIs can be used, that I can't understand.
In both cases, I get an OAuth token for AD by logging in with my Azure credentials.
In the Http response, I get an authorizationCode of the form:

AQABAAIAAAD.....

Then using the following URL as an authContext:
https://login.microsoftonline.com/{tenantId}
I get a AuthenticationResult by making the following call:
Future<AuthenticationResult> future = authContext.acquireTokenByAuthorizationCode(authorizationCode, redirectUri, credential, null);

in the Adal4j project (1), the AuthenticationResult's AccessToken is of the form:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6I...

Which I can use as a Bearer token in an HTTP call to retrieve the user's profile picture via https://graph.windows.net/myorganization/me/thumbnailPhoto?api-version=1.6
whereas in the SpringBoot AD example, the AccessToken returned from exactly the same call is of the form:

AQABAAAAAADXzZ3ifr-GRbDT....

and If I use that in exactly the same way to try to retrieve the user's profile pic, I get a 401 Unauthorized response
What's the reason for the difference in the form and use of these AccessTokens?

A:
What's the reason for the difference in the form and use of these AccessTokens?

I assume that you got the access token is authorization_code not the bearer token.
As Rohit Saigal mentioned that you could use JWT.IO or JWT.MS to check that.
If we want to get the access token for Azure AD graph we could use the follow code to do that.
public String index(Model model, OAuth2AuthenticationToken authentication) {
...
DefaultOidcUser user = (DefaultOidcUser)authentication.getPrincipal();
String accessToken = user.getIdToken().getTokenValue();
...
}

Then we could use the access token to access the Azure AD graph api if you have assiged corrosponding permission.


text:
Q: Is there a Django/Pythonic way of keying Django querysets by a particular value of the queryset? I have this view that I am using in Django REST API:
class HSKView(APIView):
    permission_classes = (AllowAny,)

    def get(self, request):
        hsk_levels = HSKLevels.objects.all()
        serializer = HSKSerializer(hsk_levels, many=True)
        return Response({"hsk": serializer.data})

And here's the serializer in case it is needed:
class HSKSerializer(serializers.ModelSerializer):

    class Meta:
        model = HSKLevels
        fields = ["level", "label", "value"]

It gives me the following output:
{
    "hsk": [
        {
            "level": 1,
            "label": "HSK 1",
            "value": "hsk1"
        },
        {
            "level": 2,
            "label": "HSK 2",
            "value": "hsk2"
        },
        {
            "level": 3,
            "label": "HSK 3",
            "value": "hsk3"
        },
        {
            "level": 4,
            "label": "HSK 4",
            "value": "hsk4"
        },
        {
            "level": 5,
            "label": "HSK 5",
            "value": "hsk5"
        },
        {
            "level": 6,
            "label": "HSK 6",
            "value": "hsk6"
        },
        {
            "level": 7,
            "label": "HSK 6+",
            "value": "hsk6plus"
        }
    ]
}

But ideally, I'd like to have a key to each of these items, rather than just something to iterate over, so I'd most likely to prefer it to look like this:
{
    "hsk": {
        1: {
            "level": 1,
            "label": "HSK 1",
            "value": "hsk1"
        },
        2: {
            "level": 2,
            "label": "HSK 2",
            "value": "hsk2"
        },
        3: {
            "level": 3,
            "label": "HSK 3",
            "value": "hsk3"
        },
        4: {
            "level": 4,
            "label": "HSK 4",
            "value": "hsk4"
        },
        5: {
            "level": 5,
            "label": "HSK 5",
            "value": "hsk5"
        },
        6: {
            "level": 6,
            "label": "HSK 6",
            "value": "hsk6"
        },
        7: {
            "level": 7,
            "label": "HSK 6+",
            "value": "hsk6plus"
        }
    }
}

The "level" value is also the primary key.

A: Method-1
Override the to_representation(...) method of the serializer
class HSKSerializer(serializers.ModelSerializer):
    class Meta:
        model = HSKLevels
        fields = ["level", "label", "value"]

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        return {rep["level"]: rep}
Method-2
Iterate serialzer.data
class HSKView(APIView):
    permission_classes = (AllowAny,)

    def get(self, request):
        hsk_levels = HSKLevels.objects.all()
        serializer = HSKSerializer(hsk_levels, many=True)
        return Response({"hsk": {data["level"]: data} for data in serializer.data})


text:
Q: PDF files opening up in browser One of the app that I coded was giving option to download everytime I click on a pdf file. Now it opens up in a browser. I didn't change any code. How can I make it so it only let them download and not open up in browser?

A: I can think of two ways of doing this: You can either simply ZIP the PDF files, which would then force a download, or you could write a script that would serve the requested files as downloadable attachments. Not sure what language is your app written in, but in PHP you could do it like this:
download.php
<?php
if (isset($_GET['file'])) {
    $file = $_GET['file'];
        if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file))  {
            header('Content-type: application/pdf');
            header("Content-Disposition: attachment; filename=\"$file\"");
            readfile($file);
        }
    } else {
    header("HTTP/1.0 404 Not Found");
    echo "
Error 404: File Not Found:
$file
";
}
?>

and then you would link to your pdf files like:
Download the cool PDF.

Found on this forum post.
Hope this helps.

A: Browsers have plugins that can open up your pdf files in browsers themselves when you dont have these plugins they download it. One way you can still achieve it is while sending the file for download dont tell browser the Mime Type of the response hence this way plugin wont know that there is a pdf file to open and would still let u download it.
try sending following header
Content-Disposition: attachment; filename=genome.pdf;
         modification-date="Wed, 12 February 1997 16:29:51 -0500";


text:
Q: Show that $9\mid a^2$ if given that $6\mid a$ Does this prove I made seem correct to show that if $6$ divides $a$ then $9$ divides $a^2$
If $6\mid a$, then $a = 6k$ (k is some integer).
Then $a^2 = 36k^2 = 9(4k^2)$.
Which means that $9\mid a^2$.
perhaps if not is there any other way?

A: You've done just fine! You correctly used what you were given, and used the definition of divisibility (by $6$), to obtain your result.
Good work!

A: What you've done is perfect.
An alternate method of proof for all those people who just love modular arithmetic:
Since $6\mid a$, then $a\equiv 6,\; 3,\; \text{or}\; 0 \pmod{9}$.  Note that $6^2 \equiv 3^2 \equiv 0^2 \equiv 0\pmod{9}$.  Thus, $9\mid a^2.$

A: Your proof is correct. It easily generalizes to the following (yours is special case $\,b=a,\,B=A)$
$$ \begin{eqnarray} && a\mid A\\ &&b\mid B\end{eqnarray}\ \ \Rightarrow\ \ ab\mid AB$$
This has a fundamental converse, namely
$$c\mid AB\ \ \Rightarrow\ \ c = ab, \begin{eqnarray} && a\mid A\\ &&b\mid B\end{eqnarray}\ \ \ {\rm for\ some}\ \ a,b$$
This is equivalent  to the uniqueness of factorizations into primes (atoms), since the special case when $\,c = p\,$ prime is $\ p\mid AB\,\Rightarrow\,p\mid A,\,$ or $\,p\mid B,\,$ which implies said uniqueness by a simple inductive proof.
This leads to an important refinement view of unique factorization - which has the benefit of generalizing nicely to other rings (esp. noncomutative rings, as Paul Cohn showed). For further discussion see here and here.


text:
Q: How can I filter out anomalies / noise from a series of numbers? I'm looking to identify the minimum integer in a series.  However, occasionally there are integers that throw off this simple plan.  How can I ignore integers that are well outside the rest?
Example:
Day    Min    Max    Actual
  1      0    100      1-100
  2    101    200    101-104,106-200
  3    201    300    201-280,300
  4    105    400    105,305-400
  5    301    600    301-304,401-600

I need min/max output to be:
Day    Min    Max     Actual
  1      0    100      1-100
  2    101    200    101-104,106-200
  3    201    280    201-280,300       // filtered out 300
  4    305    400    105,305-400       // filtered out 105
  5    401    600    301-304,401-600   // filtered out 301-303

Can you suggest a strategy to ignore such anomalies?
Given a series like 301-304,401-600, I need to return 401-600.

A: One idea is to find the average distance between consecutive integers, and filter away integers when the distance is too many times that average distance.  This does end up making the final list depend on how you filtered out the outliers.  In python:
maxJumpScale = 5
repeat = True
while ( repeat ):
    repeat = False
    average = sum(numbers)/numbers.size()
    averageDistance = max(1,(max(numbers)-min(numbers))/numbers.size())
    for i in range(1,numbers.size()):
        if ( numbers[i] > numbers[i-1]+maxJumpScale*averageDistance ):
            if ( numbers[i] < average ):
                numbers = numbers[i+1:]
                repeat = True
            if ( numbers[i-1] > average ):
                numbers = numbers[:i-1]
                repeat = True

A: Any filtering problem is essentially working from models of "ordinary" and "exceptional" values. There may be more than one category of "ordinary", likewise more than one category of "exceptional". Furthermore, you must also state your preferences as to whether it's worse to mistake ordinary for exceptional and vice versa. Once you have your models in hand, you compute the probability that any given datum falls into the various categories, and then calculate which assignment (i.e. putting the datum in which category) is most preferable.
There are various heuristics for filtering and I'm sure you can make some up yourself. My advice is to try to do it from first principals.
You haven't said much about the problem domain so I can't really be specific about what you should do. Feel free to add more detail to the problem statement.


text:
Q: Pagination is not working when query searched using search engine. What to do? The below code (search.php) works fine for the first page of pagination only, but when I click on the second page then it shows the following error.

"Notice: Undefined index: search in /opt/lampp/htdocs/testdb/search.php on line 15"**.

I tried to use $_SESSION also but its not working. The query is passing for the first page of pagination only. I am a beginner in coding. Any help or suggestions will be very helpful. Thanks.
<?php

//Database connection
$mysqli = NEW MySQLi('localhost','root','','dbname');

//POST data from the query search page which is to be fetched from Database
$a=$_POST['search'];// this is line 15 of my code for which the error is appearing
//PAGINATION
$rpp = 25;    //records per page
isset($_GET['page']) ? $page = $_GET['page'] : $page = 0;
     if($page > 1) {
           $start = ($page * $rpp) - $rpp;
}
 else {
     $start = 0;
 }
//SQL query
$res =$mysqli->query("SELECT * FROM t1 WHERE col4 like '$a'");
$num = $res->num_rows;
$totalpages = $num / $rpp;
echo $totalpages;     //to check the no. of  total pages and if it is not whole no. then in the for loop at the end of the code add +1 with $totalpages (i.e. for($x = 1; $x <= $totalpages + 1; $x++))

$res = $mysqli->query("SELECT * FROM t1 WHERE col4 like '$a' LIMIT $start, $rpp");

//Fetch data from table "
";
echo "
";
while($rows = $res->fetch_assoc()){
    $a = $rows['col1'];
    $b = $rows['col2'];
    $c = $rows['col3'];
    $d = $rows['col4'];
    echo "
$a	$b	$c	$d
";
}
echo "

";
echo "
";
//make link for next page in pagination

for($x = 1; $x <= $totalpages; $x++)
{
    echo "$x";
}
?>

Search page

<form action='search.php' method='POST'>
<input type='text' name='search'>

<input type='submit' name='submit' value='Submit'>

</form>

PtRNAome_1  nuclear     GCA_000001735.2     Arabidopsis thaliana : nuclear
PtRNAome_2  nuclear     GCA_000001735.2     Arabidopsis thaliana : nuclear
PtRNAome_3  nuclear     GCA_000001735.2     Arabidopsis thaliana : nuclear
PtRNAome_4  nuclear     GCA_000001735.2     Arabidopsis thaliana : nuclear
PtRNAome_5  nuclear     GCA_000001735.2     Arabidopsis thaliana : nuclear


text:
Q: Delete entries from a table based on multi-table conditions Summary: We need to delete entries from a table based on conditions involving the table itself as well as a separate table
I have been able to recreate the issue that we are trying to solve using two sample tables, called table_A and table_B.  Their definitions are as follows:
CREATE TABLE table_A
(
  id  INT UNSIGNED AUTO_INCREMENT,
  name  VARCHAR(64) NOT NULL,
  date  DATE NOT NULL,
  otherFields_A VARCHAR(64) NOT NULL,
  -- many other fields in the table (different from table_B)
  -- but not relevant to the question being asked

  PRIMARY KEY(id)
);

CREATE TABLE table_B
(
  id  INT UNSIGNED AUTO_INCREMENT,
  name  VARCHAR(64) NOT NULL,
  date  DATE NOT NULL,
  otherFields_B VARCHAR(64) NOT NULL,
  -- many other fields in the table (different from table_A)
  -- but not relevant to the question being asked

  PRIMARY KEY(id)
);

The tables are populated as follows:
INSERT INTO table_A(name, date) VALUES('John Doe', '2018-01-01'), ('John Doe', '2018-07-01'), ('John Doe', '2018-12-01'), ('Mary Smith', '2018-08-02'), ('Andy Roberts', '2018-07-02'), ('John Doe', '2018-12-02');

INSERT INTO table_B(name, date) VALUES('Keith Miller', '2018-01-03'), ('Mary Smith', '2018-07-02'), ('John Doe', '2018-07-30');

We want to traverse table_A and delete all entries for which
table_B.name= table_A.name
AND
table_B.date >= table_A.date

A: This should as simple as :
DELETE table_A
FROM table_A
INNER JOIN table_B
    ON table_B.id = table_A.id
    AND table_B.date >= table_A.date

Demo on DB Fiddle
Reference : Multiple-Table in DELETE Syntax


text:
Q: How are tags made in Subversion? I know how to use tags in subversion. I create a tag every time I get to a release milestone.
What I don't quite understand is how they work.
Is a tag just a copy, made from what ever revision I specify? Or is a tag more like a reference, where internally subversion just says GO TO /trunk/project/ Revision 5 or whatever.
The command to create a tag (svn copy) seems to imply that it's a copy, but I've seen other people write that subversion doesn't really copy anything.
Say I dump just the HEAD revision of a repository. I don't care about any history except the tags. Are those tags dumped along with the rest of the Head revision?
Finally, is all this just programming magic that I don't really want to know.

A: The Subversion book is online in a complete and free form:
  http://svnbook.red-bean.com/en/1.4/svn-book.html#svn.branchmerge.tags
And yes, you basically do an svn copy.  Subversion is smart enough to do a copy-on-write style mechanism to save space and minimize transfer time.

A: Right, a tag is just a copy:
svn copy trunk tags/BLAH

When people say SVN doesn't really copy anything, they mean that the repository doesn't need to duplicate the data. It uses something akin to symbolic links to keep track of the copies.

A: The TortoiseSVN help explains it quite nicely:

Subversion does not have special commands for branching or tagging, but uses so-called "cheap copies" instead. Cheap copies are similar to hard links in Unix, which means that instead of making a complete copy in the repository, an internal link is created, pointing to a specific tree/revision. As a result branches and tags are very quick to create, and take up almost no extra space in the repository.
  [...]
  If you modify a working copy created from a branch and commit, then all changes go to the new branch and not the trunk. Only the modifications are stored. The rest remains a cheap copy.

A: Yes, a svn copy (whether you are thinking of it as a tag, a branch, or copying a file in trunk) is all the same.  SVN will internally create a pointer to the source location at that revision.  If you then make changes to the copy (which you are likely to do if it is a branch or a copied file in trunk, but shouldn't do for tags), SVN will only store what was changed, rather than creating a whole new copy.

A: A tag is a reference to the set of revision numbers at the time the tag was taken- it's the same thing as a branch or a copy, internally.

A: an example:
$ svn copy https://jorgesysgr.com/svn/AndNews/branches \
           https://jorgesysgr.com/svn/AndNews/tags/release-1.1 \
           -m "release 1.1 Android News."

More info:: Creating a Simple Tag


text:
Q: Why does my Macbook lock up while my external hard drive spins up? Why does my MacBook lock up while my external USB hard drive spins up? It comes right back after a click or two post spin-up. It's pretty annoying since finder often sniffs the drives but the USB drive is typically asleep since I use it mostly for backups.
Notes:

*

*The clicking I refer to post spin-up is just a couple of head seeks. The external drive is new and I have several others that cause the same temporary freeze of the OS.

*The hard drive works great, it goes to sleep because I have the OS configured to allow it to sleep when unused

*I'd rather not plug and unplug the drive a few times a day (I use it for mostly but not
exclusively backups)

*I don't want the drive spinning all day.. it's usually idle and should be quietly sleeping awaiting work
The issue is I'm sure as Tom suggests that the OS is doing a synchronous I/O touch on every disk... am I expecting to much of a modern OS ?  It's lame that any time I open a Finder window it freezes a ton of things for a few seconds... what happened to multi-tasking?
==Update==
This was fixed in a later release of OSX. The system no longer experiences any freezing nor hiccups. I am still using the same external drive as my primary time-machine destination and haven't seen the freeze nor hiccups in ages. Closing the question.

A: It locks up because it is waiting for a synchronous I/O request to finish, that request takes longer because your hard drive appears to be in not working smoothly, indicated by the clicks you hear.
Three options to remedy the problem:

*

*Find a way to keep the drive from spinning down. A scheduled write, perhaps? Or an option?

*Disconnect the drive and use it only when you need it for a manual back-up.

*Get yourself a new drive, because it doesn't sound safe to put back-ups on such drive...

A: This turned out to be an unnecessary kernel lock in OSX that was addressed sometime in the OS X Yosemite time frame. It no longer happens at all. Thanks for all the theories presented.


text:
Q: WebDriver: Not detecting Link element defined in Form within another Form I am trying to hit a link to attach files to the page. The HTML structure of the page is

                    <form id="pxupload1" name="multipleFileUpload" style="" target="pxupload1_frame" action="/multiupload" method="POST" enctype="multipart/form-data" encoding="multipart/form-data">

                                Attach Files
                                Drag Here
                                <input id="wkFileUpload" class="fileupload" type="file" multiple="" tabindex="-1" name="noteFilename" title="Attach Files" style="background-color: transparent;">

I have already tried .sendkeys(), but the element(id="wkFileUpload") is not visible to Selenium.
Can someone please suggest anything?

A: Unfortunately, you can't do that as of now (September 2013, Selenium 2.35.0), because Selenium doesn't support <input type="file" multiple> elements.
There is a feature enhancement request for this made by the project developers themselves, it's just not yet implemented. You can star it there to move it upwards in the priority list.
The bug mentions that some work has been done on it, but I don't think it will be done any time soon. Your best bet is to use AutoIT (Windows only) or the Robot class (will also work only on setups similar to yours) and type the path "blindly" into the dialog:
driver.findElement(By.id("wkFileUpload")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


text:
Q: Textview cannot be resolved or is not a field - simple SQL database package com.example.checkoilforvectra;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;

TextView imported.
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tv = (TextView)findViewById(R.id.textView1);
[...]

Here I have error - textView1 generates error. In example code I found on polish website author uses textView1 without error.

A: Make sure you have initialized textView1 in activity_main xml file using android:id="@+id/textView1"
It must look like similar to this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" >
<TextView
   android:id="@+id/textView1"
   android:layout_width="match_parent"   />
</LinearLayout>

A: At the "activity_main" you need to have a TextView with the ID textView1, if you don't have one, create it :) , here is an example for a code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="David" />

 </RelativeLayout>


text:
Q: Ios Intercept UIWebview request via NSURLCache and replace the response I'm developing an Epub Reader for Ios, notice that i don't use any epub library and i parse the epub myself.
I needed a method for loading resource from epub into the UIWebView, for example images  or CSS file ... (resource that requested in the html files).
for this purpose i decided to use NSURLCache class and override it's method (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
so i can intercept the request and find the right data from epub then create a NSCachedURLResponse and return it.
so far so good. BUT the the problem is that the data (i.e images) wont show in the webview. look at below code:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    /*
    the request.URL is something like this applewebdata://UUID/OEBPS/Images/cover.jpg ,
    so the getResourcePathFromRequest give me the path OEBPS/Images/cover.jpg,
    so i can find the right data in epub
    */
    NSString *resourcePath = [self getResourcePathFromRequest:request.URL];
    /*
    ResourceResponse is a class contaning data and mimeType,
    i tested this and the data and mimeType are good so this is not the problem
    */
    ResourceResponse *response = [[self getBook] fetch:resourcePath];

    NSURLResponse *urlResponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:response.mMimeType expectedContentLength:[response.mData length] textEncodingName:@"UTF-8"];
    NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlResponse data:response.mData];

    return cachedResponse;
}

at this point everything looks normal, the method getting called, the right data being found and the response object return, but it wont load the image into the webview.
so what is the problem?
tnx in advance.
NOTE: i'm new in ios programming world (coming from android:)

A: I loaded the data with base url (http://localhost) and everything went fine.


text:
Q: Create a class that extends another custom class in Flutter I have created class Blabel that extends StatelessWidget. I want to extend it to Blabel1 , keeping all of its properties and adding some extra properties to it.
Let's say I would like to add textDirection property to the new class. How can I do it?
Here is the code of Blabel class that I have:
class Blabel extends StatelessWidget {
  final String text;
  final TextStyle style;
  Blabel({
    this.text,
    this.style,
  });
  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: style ?? CtrBlblStyle(),
    );
  }
}

A: I think this is something along the line of what you are looking for:
class Blabel1 extends Blabel {
  final TextDirection textDirection; // example of new property
  Blabel1({
    String text,
    TextStyle style,
    this.textDirection,
  }) : super(text: text, style: style);
  @override
  Widget build(BuildContext context) {
    // You can change the build method to change the UI from Blabe
    return Text(
      text,
      style: style ?? CtrBlblStyle(),
    );
  }
}


text:
Q: opscenter REST API when authentication is enabled I enabled authentication on my opscenter node as per this . I've a python script that periodically invokes opscenter actions through the Opscenter REST APIs. From the REST API documentation, it looked like all I had to do was invoke these methods with basic HTTP auth (see this). But these calls always failed with a "user must be logged in" error.
After poking around the javascript that runs when I use the opscenter's web frontend, I figured that I must actually invoke the login method to create a session and use that session to invoke other methods, such as:
session = requests.Session()
login_body = '{"username": "%s", "password": "%s"}' % (opsc_uname, opsc_pwd)
login_resp = session.post("http://{url}/login".format(url=opsc_url), data=login_body).json()
clusterconf = session.get("http://{url}/cluster-configs".format(url=opsc_url)).json()

Is the api documentation (that claims to use basic http auth) wrong? Or am I doing something incorrectly? The opscenter version I'm using is 5.1.1

A: You figured it out correctly, OpsCenter 5.1 uses sessions instead of basic auth. You've been looking at 5.0 docs, that's why it wasn't documented. Here's a correct link.

A: In addition to the documentation link the user "arre" has posted above when you implement that method ensure you dont include the { } curly braces, so for example use
curl -H 'opscenter-session: d6c5e198b9b5ffeab9fd8dea6fb012aa' http://127.0.0.1:8888/permissions/user

Instead of
curl -H 'opscenter-session: {d6c5e198b9b5ffeab9fd8dea6fb012aa}' http://127.0.0.1:8888/permissions/user


text:
Q: Qt QOpenGLWidget wheelEvent strange behaviour I have the following class :
class Curve2DOpenGLWidget : public QOpenGLWidget, protected QOpenGLFunctions_3_3_Core {
Q_OBJECT
public:

    Curve2DOpenGLWidget( QWidget* parent = nullptr );
    ~Curve2DOpenGLWidget();

    void initializeGL() override;
    void resizeGL(int width, int height) override;
    void paintGL() override;
    void NativePaintGL();

protected:
    void mousePressEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;

};

I want to use wheelEvent to zoom in / zoom out in my scene.
Here is the code :
void Curve2DOpenGLWidget::wheelEvent( QWheelEvent* event ) {
    QOpenGLWidget::wheelEvent(event);
    float numStep = (event->angleDelta().y() / 8) / 15;
    m_camera.MoveFront(numStep * 0.1f);
}

It does what I want, but this event is not called when I move the mouse and use mouse wheel at the same time.
This code works on all the other widgets I've implemented (QGraphicsView, etc.). I'm wondering if there is anything special to do on QOpenGLWidget ?
I can't explain this behaviour... If it can help, I'm working on Ubuntu 14.04 LTS

A: I did run into the same problem.
In my case it was a QTimer based render loop which was updating 4 QOpenGLWidgets and the window's title bar (which was actually pretty CPU intensive) at 100 FPS.
It didn't manifest on Windows, but on Linux.
The update events for the qoglwidgets and the mouse move events probably have higher priority in the event loop than the wheel events. The wheel events don't seem to be dropped but are accumulated and arrive together with next event that »gets through«.
Luckily the use case allowed to replace this render loop with an event driven implementation avoiding this issue.

A: See Qt::AA_CompressHighFrequencyEvents and Qt::AA_CompressTabletEvents in http://doc.qt.io/qt-5/qt.html#ApplicationAttribute-enum
These are new attributes in Qt 5.

A: From Qt documentation

Mouse events occur when a mouse button is pressed or released inside a
  widget, or when the mouse cursor is moved.
Mouse move events will occur only when a mouse button is pressed down,
  unless mouse tracking has been enabled with
  QWidget::setMouseTracking().

So you need setMouseTracking(true) in your constructor


text:
Q: $HOME not expanding in cron file even though it is HOME is shown as an environmental variable I got the following error from executing a line in my Vixie Cron file:

/bin/sh: 1: cd: can't cd to $HOME/prg/gridtrader

Which to me means that $HOME is not being expanded even though crontab(5) says it will be and the log from execution shows HOME as being defined.
The cron file looks like so:
GT_DIR      = $HOME/prg/gridtrader
PYTHON_EXE  = $HOME/install/python37/bin/python3
APPLICATION = gridtrader/gridtrader.py
ACCOUNT     = metaperl_yobit

# GRID TRADER
*/5 * * * * cd $GT_DIR && $PYTHON_EXE $APPLICATION --monitor $ACCOUNT

The log message I got is:
X-Cron-Env: <ST=/home/schemelab/prg/surgetrader/src>
X-Cron-Env: <INVOKE=/home/schemelab/install/miniconda3/bin/invoke>
X-Cron-Env: <I=iniset_1>
X-Cron-Env: <AGT=~/prg/adsactly-gridtrader>
X-Cron-Env: <GT_DIR=$HOME/prg/gridtrader>
X-Cron-Env: <PYTHON_EXE=$HOME/install/python37/bin/python3>
X-Cron-Env: <APPLICATION=gridtrader/gridtrader.py>
X-Cron-Env: <ACCOUNT=metaperl_yobit>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/schemelab>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=schemelab>
Date: Tue, 26 Feb 2019 11:25:01 -0500 (EST)

/bin/sh: 1: cd: can't cd to $HOME/prg/gridtrader

As you can see the, from the shell, there is no problem executing this cd command:
schemelab@metta:~$ ls /home/schemelab/prg/gridtrader
LICENSE    SPEC.md            accounts  doc         log          requirements.txt  system.ini         tmp            venv
README.md  StatusReport.docx  batch     gridtrader  persistence  src               system.ini.sample  tradelog.docx
schemelab@metta:~$ cd /home/schemelab/prg/gridtrader
schemelab@metta:~/prg/gridtrader$ ls -ld ~/prg/gridtrader
drwxr-xr-x 13 schemelab schemelab 4096 Feb 18 13:56 /home/schemelab/prg/gridtrader
schemelab@metta:~/prg/gridtrader$

A: You have run into one of cron's most common problems, trying to use it like an arbitrary shell script. Cron is not a shell script and you can't do everything you can do in one, like dereferencing variables or setting arbitrary new variables.
I suggest you replace your values into the cron line and avoid usage of variables:
# GRID TRADER
*/5 * * * * cd $HOME/prg/gridtrader && $HOME/install/python37/bin/python3 gridtrader/gridtrader.py --monitor metaperl_yobit

A: Another approach to the problem of unexpanded cron variable content is eval:
*/5 * * * * eval cd $GT_DIR && eval $PYTHON_EXE $APPLICATION --monitor $ACCOUNT


text:
Q: How to understand this sentence about sights in Cambodia with many clauses?
There is plenty to see in Phnom Penh, the capital of Combodia, starting with a tour of the Silver Pagoda, the National Museum and the market areas where hand-woven silks and antiques will compete for your attention.

For a learner like me, this sentence is difficult to understand.
How can I divide this sentence into simple sentences?

A: You can start with the punctuation. For this sentence, the commas divide the sentence usefully. Consider what each phrase means, and what it relates to.

*

*There is plenty to see in Phnom Penh,

*the capital of [Cambodia],

*starting with a tour of the Silver Pagoda,

*the National Museum and the market areas where hand-woven silks and antiques will compete for your attention.

Phrase 1 is straightforward.
Look at phrase 2. It's a noun phrase. What does it relate to? In this case, it provides more information about Phnom Penh. It's also a parenthetical expression, so you should be able to remove it without changing the meaning of the sentence. Take it out, and see what's left.

There is plenty to see in Phnom Penh, starting with a tour of the Silver Pagoda, the National Museum and the market areas where hand-woven silks and antiques will compete for your attention.

At this point, note that you have a list:

*

*a tour of the Silver Pagoda,

*the National Museum and

*the market areas

This is followed by the word "where". In this case, it relates to the nearest noun (market areas), saying that some things happen in that place.
The rest of the sentence tells you what those things are:

*

*hand-woven silks and antiques will compete for your attention

Putting all this together, the sentence says that:

*

*there is a lot to see in Phnom Penh,

*Phnom Penh is the capital of Cambodia,

*the 'seeing' started with the Silver Pagoda, the National Museum and the market areas, and

*in the market areas, hand-woven silks and antiques will compete for your attention.

A: This sentence can be divided into eight sentences.

*

*There is plenty to see in Phnom Penh.

*The capital of Cambodia is Phnom Penh.

*There is plenty to see in Phnom Penh, starting with a tour of the Silver Pagoda, the National Museum, and the market areas.

*There is plenty to see in Phnom Penh, for example, a tour of the Silver Pagoda.

*There is plenty to see in Phnom Penh, for example, the National Museum.

*There is plenty to see in Phnom Penh, for example, the market areas.

*The market areas have hand-woven silks and antiques.

*Hand-woven silks and antiques will compete for your attention.

A: You're not the only one to have trouble parsing this sentence.  I had trouble with it myself, and had to re-read it several times to figure out what was meant.  Here is what I ended up with:

*

*The main clause: There is plenty to see in Phnom Penh

*

*Parenthetical clause about "Phnom Penh": , the capital of Combodia,
Note that "Cambodia" is misspelled here.

*Dependent clause about "see": , starting with a tour of the Silver Pagoda, the National Museum and the market areas

*

*Restrictive clause about "market areas": where hand-woven silks and antiques will compete for your attention
I would consider the sentence poorly written.  The biggest problem is that a comma is missing after "areas", such that the last clause looks like a non-restrictive clause rather than a restrictive clause.  As written, it's hard to see that where hand-woven silks and antiques will compete for your attention modifies market areas, so I had to go back and puzzle out how to edit the sentence so that it makes sense.
I would also note that a tour of is superfluous, and only adds confusion since it's not obvious where the prepositional phrase ends.
If I had to cram all of that information into one sentence, I'd write it this way:

There is plenty to see in Phnom Penh, the capital of Cambodia, starting with the Silver Pagoda, the National Museum, and the markets, where antiques and hand-woven silks will compete for your attention.


text:
Q: How to change all file extensions with a makefile I am using bash and trying use a makefile to copy all files in a directory with .ppt to .pdf and then add them all into an archive. This is what I have so far
.PHONY: all clean

files = $(wildcard *.ppt)

OBJ = $(patsubst %.pdf, %.ppt, $(wildcard *.ppt))

clean:
        rm -f lectures.tar.gz *.pdf

The only makefiles I've made up to this point have been used to compile a program from 1 or 2 source files. Not sure how to approach this

A: The trick with make is that it starts at the end, with what you want to create, and then walks backwards towards the beginning, to see what things have changed.
So, what's at the end: what do you want to produce?  Based on your example we'll infer you want to create a compressed tar file named lectures.tar.gz.  So, we'll need a target for that:
lectures.tar.gz:

What goes into the tar file?  the PDF files, which you've already discovered how to compute into the OBJ variable, so those things must be listed as prerequisites of lectures.tar.gz:
lectures.tar.gz: $(OBJ)

What is the recipe for that target?  It should create a tar file with that name, containing all the files.  One way is this:
lectures.tar.gz: $(OBJ)
        tar czf lectures.tar.gz $(OBJ)

Another way, more generic using automatic variables, would be:
lectures.tar.gz: $(OBJ)
        tar czf $@ $^

Now, how do you create the OBJ files?  For each one you need to copy it from the .ppt version.  Since you're using GNU make (as evidenced by your use of wildcard etc. functions) you can use a pattern rule for this; the pattern is this:
%.pdf : %.ppt
        cp $< $@

This pattern tells make how to build a file X.pdf from any file X.ppt, with a cp command: in this case the automatic variables $< and $@ are required since you don't know the names.  This is an implicit rule because the names aren't explicitly listed, but implied by the pattern.
Now how do you build the .ppt files?  You don't, because they're source files, so you're done!


text:
Q: Can you still do variable arguments in C the old way? Purely for interest, I am re-learning C after ... I don't know ... 15 - 20 years.
I seem to recall that variable arguments were implemented as simple macros.

*

*Can anyone remember what they were?

Edit: To clarify my question, I know they had the same name as va_list etc. but can you remember the actual macro definition?

*

*Will they still work today?

A: You're thinking of va_list, va_arg, va_start, and va_end from stdarg.h (link to WP article). They still work just fine. :-)

A: Variadic functions are indeed commonly implemented using macros. These are standardised - see this wikipedia article on the subject. The actual macro definitions are dependent on the processor architecture, as they have to play non-portable games with the call stack.

A: Even before the standardisation, methods of doing variable arguments were common.  The C89 standard gave a ... standardized interface based on the existing practices.  Remainders of those practice still exist at place, for instance <varargs.h> was still present in Unix98: http://www.opengroup.org/onlinepubs/007908799/xsh/varargs.h.html (but is no more present in current version)
The implementation of the macros was always very much system dependent (there are stacks growing in both directions, there are even systems using a linked list as stack, position of various things in the stack frame depend on the processor and common convention, on some processors -- says Sparc -- one need first to save the registers, alignment requirements may cause problems,...)
If you want to know what would a simple implementation looks like, here is one, depending on assumptions probably false (they don't try to get any alignment right) and also certainly failing some corner cases even when the assumptions hold:
typedef void* va_list;
#define va_start(va, arg) va = (void*)((&arg)+1)
#define va_arg(va, type)  (va = (void*)(((type*)va) + 1), *((type*)va -1)
#define va_end(va)

A: Variable arguments today are done via the interface described in <stdarg.h> - as to how they were done 15 years ago, I really can't say.

A: Its hard to say if your implementation of them from way back when would still work, however they are pretty much the same as others have pointed out, they just moved into a standard header (standard being the operative word).
What a compiler expands as a built in is up to the compiler, and the flags that you pass to it when invoking it.
Keep in mind that gcc is not the only C compiler, but it (like others) conforms to c89 and c99.