text:
Q: App script failing to bring data from another spreadsheet This program tries to bring all the data in one spreadsheet and paste it into another spreadsheet.
Firstly, it gets all files inside a folder (all of which will be spreadsheets), then it gets the values of a certain range and stores them into an array; after that, it goes to another spreadsheet and tries to set the values of the array into the first row with no data; finally, it moves the file where the data was stored in the first place.
var uploadG = DriveApp.getFolderById('')
var moveToG = DriveApp.getFolderById('')

function obtainAndImportData(uploadFolder){
  var internalFiles = uploadFolder.getFiles()
  while (internalFiles.hasNext()){
    var file = internalFiles.next()
    var fileID = file.getId()
    var copySheet = SpreadsheetApp.openById(fileID).getSheets()[0] // reads file by file and gets their first spreadsheet

    var Cvals = copySheet.getRange("C1:C").getValues()
    var lastToValue = Cvals.filter(String).length-2 // gets last row with data

    var Csheet = pasteSheet.getRange("C1:C").getValues()
    var lastSheetToValue = Csheet.filter(String).length  // gets last row with data

    var allRows = []
    for (i = 0;i = lastToValue;i++){
      allRows[i] = copySheet.getRange(`B${i+3}:P${i+3}`).getValues()
    } // gets row and then stores it into an array

    var rangeToUnify = pasteSheet.getRange(`B${lastSheetToValue+1}:P${lastSheetToValue + lastToValue + 1}`)
    rangeToUnify.setValues(allRows)  //inserts data from old spreadsheet into this new one

    file.moveto(moveToG) // moves file
  }
}

I think it should work fine, but the program just never completes its execution. Never inserts the data, and never moves files, but it doesn't throw any error either.
Note: The files this program is reading start as .xslx files, which are saved as Google Spreadsheets once they're uploaded to Google Drive. (maybe that is the problem, but I don't really know how to solve it)

A: I believe this is a little closer to what you were shooting for
function obtainAndImportData(uploadFolder) {
  var uploadG = DriveApp.getFolderById('')
  var moveToG = DriveApp.getFolderById('')
  var internalFiles = uploadFolder.getFiles()
  while (internalFiles.hasNext()) {
    var file = internalFiles.next()
    var fileID = file.getId()
    var copySheet = SpreadsheetApp.getActive().getSheets()[0];
    var Cvals = copySheet.getRange("C1:C" + copySheet.getLastRow()).getValues()
    var ldr = Cvals.length;
    var Csheet = pasteSheet.getRange("C1:C" + pasteSheet.getLastRow()).getValues()
    var lstv = Csheet.length;
    var allRows = []
    for (i = 0; i = ldr; i++) {
      allRows.push(copySheet.getRange(`B${i + 3}:P${i + 3}`).getValues()[0]);
    }
    pasteSheet.getRange(lstv + 1,2,allRows.length,allRows[0].length).setValues(allRows);
    file.moveto(moveToG) // moves file
  }
}

A: Modification points:

*

*When I saw your script, in your for loop, you are using for (i = 0; i = lastToValue; i++) {. In this case, the loop is not finished.

*

*I thought that this might be the reason for your issue of but the program just never completes its execution. Never inserts the data, and never moves files, but it doesn't throw any error either. is due to this.

*In this case, it is required to be modified to for (i = 0; i < lastToValue; i++) {. But, when allRows[i] = copySheet.getRange(B${i + 3}:P${i + 3}).getValues() is used in a loop, the process cost will become high. Ref

*Also, when rangeToUnify.setValues(allRows) is used in a loop. the process cost becomes high.

*In order to retrieve the values from the sheet, you are using copySheet.getRange("C1:C").getValues() and pasteSheet.getRange("C1:C").getValues(). In this case, all rows over the data range are retrieved. In this case, the process cost becomes high.

*And, even when the above script was modified, I think that an error occurs at rangeToUnify.setValues(allRows). Because the number of rows are different between the range and the values.

*And, file.moveto(moveToG) should be file.moveTo(moveToG).

When these points are reflected in your script, how about the following modification?
Modified script:
Before you use this script, please set the variables of pasteSheet, uploadFolder and moveToG.
function obtainAndImportData() {
  var pasteSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("###"); // Please set your "pasteSheet".
  var uploadFolder = DriveApp.getFolderById('###'); // Please set your folder.
  var moveToG = DriveApp.getFolderById('###'); // Please set your folder.

  // Ref: https://stackoverflow.com/a/44563639
  Object.prototype.get1stNonEmptyRowFromBottom = function (columnNumber, offsetRow = 1) {
    const search = this.getRange(offsetRow, columnNumber, this.getMaxRows()).createTextFinder(".").useRegularExpression(true).findPrevious();
    return search ? search.getRow() : offsetRow;
  };

  var internalFiles = uploadFolder.getFilesByType(MimeType.GOOGLE_SHEETS);
  var values = [];
  while (internalFiles.hasNext()) {
    var file = internalFiles.next();
    var copySheet = SpreadsheetApp.open(file).getSheets()[0];
    var srcValues = copySheet.getRange("B3:P" + copySheet.get1stNonEmptyRowFromBottom(3)).getValues();
    values = [...values, ...srcValues];
    file.moveTo(moveToG);
  }
  pasteSheet.getRange(pasteSheet.get1stNonEmptyRowFromBottom(3) + 1, 2, values.length, values[0].length).setValues(values);
}

*

*When this script is run, the Spreadsheet is retrieved from "uploadFolder" folder. And, the values are retrieved from "B3:P" of the 1st tab for each Spreadsheet, and those values are appended from the column "B" of "pasteSheet" sheet.

Note:

*

*In this modification, from your showing script, the last row is retrieved from the column "C". But, if you want to use the last row of the data range, I think that you can also use getLastRow().

References:

*

*Loops and iteration

*Benchmark: Reading and Writing Spreadsheet using Google Apps Script

*moveTo(destination)


text:
Q: Telerik RadCalendar - Specialdays : How to display Date of the Special Day I am not familiar with RadCalendar component. Pleas bear with me if my question is a basic functionality.
My purpose is to display selected days with different BackColor values, according to the selection of the client. Basically only changing the ItemStyle for the selected days are acceptable for me, but I couldn't find how to do it?
So I tried a differen approach as follows:
I created SpecialDays in my Calendar
<telerik:RadCalendar AutoPostBack="true" ID="calendar1" runat="server"  Width="400px" Height="300px" FirstDayOfWeek="Monday">
            <SpecialDays>
                <telerik:RadCalendarDay TemplateID="temp1"></telerik:RadCalendarDay>
            </SpecialDays>
            <SpecialDays>
                <telerik:RadCalendarDay TemplateID="temp2"></telerik:RadCalendarDay>
            </SpecialDays>
            <SpecialDays>
                <telerik:RadCalendarDay TemplateID="temp3"></telerik:RadCalendarDay>
            </SpecialDays>
            <CalendarDayTemplates>
                <telerik:DayTemplate ID="temp1" runat="server">
                    <Content>
                       <asp:Label ID="lblTemp1" runat="server"></asp:Label>
                    </Content>
                </telerik:DayTemplate>
                <telerik:DayTemplate ID="temp2" runat="server">
                        <Content>
                            <asp:Label ID="lblTemp2" runat="server"></asp:Label>
                        </Content>
                </telerik:DayTemplate>
                <telerik:DayTemplate ID="temp3" runat="server">
                        <Content>
                            <asp:Label ID="lblTemp3" runat="server"></asp:Label>
                        </Content>
                </telerik:DayTemplate>
            </CalendarDayTemplates>
        </telerik:RadCalendar>

And in code behind, I am assiging the selected days to the desired template when the client press the button of choice as SetAstemp1, SetAstemp2 or SetAstemp3:
protected void BtnSetAsTemp1_Click(object sender, EventArgs e)
    {
        int daysCount = calendar1.SelectedDates.Count;

        for (int i = 0; i < daysCount; i++)
        {
            RadCalendarDay day = new RadCalendarDay();
            day.TemplateID = "temp1";
            day.Date = calendar1.SelectedDates[i].Date;
            calendar1.SpecialDays.Add(day);

        }
    }

But with this approach, I cannot use the embedded skin in RadCalendar control. When the selected day is assigned to a special day, the date of the cell is not displayed.
And I have to show the date in Content tag of the related SpecialDay. But I could not find a way to access the lblTemp1 control defined in the Content.
Could you please point me to the right direction if my approach is not right?
Or any suggestions to display the date in the lblTemp1.Text is appreciated.
Thank you!

A: Impulse, I think that the simplest method is to set the backcolors for selected dates hooking the DayRender event of the Telerik calendar. I found this online example that might be useful to you.

A: RadCalendarDay holiday = new RadCalendarDay();
holiday.Date = Datetime.Now;//Your date which you want
holiday.IsSelectable = false;
holiday.IsDisabled = true;
holiday.ToolTip = "NOT AVAILABLE";
TableItemStyle style = new TableItemStyle();
style.BackColor = Color.HotPink;
holiday.ItemStyle.CopyFrom(style);
calendar1.SpecialDays.Add(holiday);

redpajama_set_name: RedPajamaStackExchange


text:
Q: PDFKit annotation url crash with non-nullable property that can be null We are proud to use PDFKit in our app, but with some documents, a crash appeared, and is related to Links Handling.
We found one PDF document that provoque the weird crash : https://www.tinaja.com/glib/pdflink.pdf
The problem is that we fetch the URL of the annotations Links in the pdf, and the object PDFActionUrl have a url: URL property that is non-nullable.
But fact shows that is CAN be null, and provoke a crash when it is !
Proof of concept in Playgrounds:
import PDFKit

guard let pdfUrl = Bundle.main.url(forResource: "pdflink", withExtension: "pdf") else {
    fatalError("no pdf url")
}

guard let pdf = PDFDocument(url: pdfUrl) else {
    fatalError("no pdf document")
}

guard let firstPage = pdf.page(at: 0) else {
    fatalError("no page")
}

firstPage.annotations[0].action // URL Action - (null)
firstPage.annotations[1].action // URL Action - (null)

guard let action = firstPage.annotations[0].action as? PDFActionURL else {
    fatalError("no action")
}

// PDFActionURL.url is non-nullable URL type
action.url // error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Does anyone know how we can check the value, and prevent the crash ?

A: For your information, I have opened a bug report at Apple, and found a workaround, ugly, but working for now:
if let urlAction = annotation.action as? PDFActionURL {
  if urlAction.description.contains("URL Action - (null)") {
    throw Errors.unsupportedPdfAction
  }
  type = .url(url: urlAction.url)
}


text:
Q: Discord.py. Как можно сделать embed подобным embed'у на картинке?
В целом даже если это нельзя реализовать в коде, я вообще не могу понять как сделать такой черный фон и засунуть картинку в начало. Пытался через css редактировать,но функции редактирования фона там не нашел.

A: Чтобы такое сделать тебе нужно добавить к тексту в начале и конце вот это ```
Надеюсь помог )


text:
Q: chrome-driver 83 compatibility with Ubuntu I'm running Ubuntu 18.04.1 LTS and used stable versions of Google Chrome v81 and compatible chrome-driver v81 for a long time successfully.
After reinstalling google-chrome-stable up to 83.0.4103.61 and updating chrome-driver up to 83.0.4103.39. According to the official page they are fully compatible.
But after these updates I'm getting error unable to connect to renderer.
My capabilities remains the same:
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: [
        '--headless',
        '--disable-gpu',
        '--no-sandbox',
        '--remote-debugging-port=9222',
        '--ignore-certificate-errors',
        '--allow-insecure-localhost'
      ]
    }
  }

And full error message is the following:
[11:07:05] E/launcher - session not created
from disconnected: unable to connect to renderer
  (Session info: headless chrome=83.0.4103.61)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: '******', ip: '******', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-38-generic', java.version: '10.0.2'
Driver info: driver.version: unknown
remote stacktrace: #0 0x5633488fb579 <unknown>

My webdriver-manager status:
[11:24:59] I/status - selenium standalone version available: 3.141.59 [last]
[11:24:59] I/status - chromedriver version available: 83.0.4103.39 [last]
[11:24:59] I/status - geckodriver version available: v0.26.0 [last]
[11:24:59] I/status - android-sdk is not present
[11:24:59] I/status - appium is not present

Does anybody faced the same issue and knowing how to solve it or rollback to v81 correctly? Any suggestions will be appreciated.
P.S. 1) the same config works well locally on the latest MacOS 2) I didn't succeed to launch chromium-browser v81 with driver v81, probably did the rollback in a wrong way.

A: The issue is resolved. The problem was that I was using argument --remote-debugging-port=9222. But someday google-chrome process got stuck deadly and occupied the port. So, when the chromedriver starts the google-chrome it can't get access to busy port for debugging purposes and simply exits with no errors. That's why the chromedriver can't get access to google-chrome and sends unable to connect to renderer error.
The solution is:

*

*kill frozen processes that occupy ports

*use debugging-port when you really need it

*using direct connection to the chromedriver reduces "layers" so the overall stability was improved


text:
Q: How to reproduce a plot with fitted value graph and lowess smooth graph superimpose? I have a binary response variable (y) and continuous explanatory variable (age).
I utilised logistic regression to analyse them. I have a plot of y against age. What I want to do now is superimpose the fitted value plot and lowess plot on it.
So how do I do that?
This is what I have come up with so far:
plot(y~age)
GLM <- glm(y~age, family=binomial)
curve(plogis(-7.502+0.077*x), min(age), max(age), add=T, lwd=2, col="blue", type="l")
lines(lowess(age, GLM$fitted, f=0.9), col="green")

Is this right/ the best way?

A: You could try the visreg package it is able to draw your plot very easily and it doesn't require a lot of coding either. First load the visreg package:
require('visreg')

Then create your model:
model <- glm(y~age, family="binomial")

And final plot your model, it will show your curve including the confidence interval.
visreg(model,scale="response",partial=FALSE,xlab="Age",ylab="P(y)", line=list(col="black"), ylim=c(0,1))

If you also want to add your points, just run the following:
points(y~age,pch=21,col="black", bg="red", cex=1)

It will look something like this


text:
Q: Using React Native's Geolocation watchPosition and redux to store coordinates, coordinates not getting frequently and accurately I am building react native app to show user movements on the map for that I am using react-native-map and when ever user clicks start trip button, I am recording coordinates from navigator.geolocation.wathposition api and saving coordinates in redux state, but it triggers around 10 -15 secs and some times more, I have tried distanceFileter values [1,5,10] but no change, because of that the polyline on the map is not drawing properly. I am new to react-native and programming, please suggest where I am going wrong. Watch position component placed under drawer-navigation.
my package.json :
"dependencies": {
"create-react-class": "^15.6.3",
"haversine": "^1.1.0",
"native-base": "^2.4.5",
"react": "16.3.1",
"react-native": "^0.55.4",
"react-native-maps": "^0.21.0",
"react-native-modal": "^6.1.0",
"react-native-vector-icons": "^4.6.0",
"react-navigation": "^2.3.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0"
}

and my watch position component as follows:
class GetCoords extends Component {
constructor(props) {
super(props);
 this.state = {
   shadowOffsetWidth: 1,
   shadowRadius: 4,
   watchId: '',
   isTripStarted: false,
  };
}

componentWillUnmount() {
   stopWatchPosition();
}

startWatchPosition = () => {
if (this.state.watchId === '' || this.state.watchId === null) {
  let watchId = navigator.geolocation.watchPosition(this.getCoordinates, this.geo_error,
    {
      enableHighAccuracy: true,
      maximumAge: 0,
      timeout: 5000,
      // useSignificantChanges: true,
      distanceFileter: 10,
    });

  this.setState({ watchId, isTripStarted: true })
}
this.props.navigation.navigate("Map", { title: "location tracking started" });

 }

stopWatchPosition = () => {
  if (this.state.watchId >= 0 && this.state.watchId !== '') {
  navigator.geolocation.clearWatch(this.state.watchId);
  this.setState({ watchId: '', isTripStarted: false });
}
}

getCoordinates = (position) => {

 let curLocation = {
  latitude: position.coords.latitude,
  longitude: position.coords.longitude,
  latitudeDelta: 0.0122,
  longitudeDelta: Dimensions.get("window").width /
  Dimensions.get("window").height * 0.0122,
}
this.props.locationChanged(curLocation) // saving coordinates in redux state
draw a polyline in the map screen;
}

geo_error = (err) => {
console.log("GeoLocationError:: ", err);
alert("Sorry, problem in getting position.");
}

 render() {
return (
  <Container>
    <AppHeader title="Home" />

    <Content padder>
      <Card>
        <CardItem>
          <Body>
             <Button vertical  onPress={this.startWatchPosition}>
                <Text>Start Trip</Text>
             </Button>

              <Button vertical  onPress={this.stopWatchPosition}>
                <Text>Stop Trip</Text>
             </Button>
          </Body>
        </CardItem>
      </Card>

    </Content>
  </Container>
 );
}

Map Screen component as follow:
class Map extends Component {
constructor(props) {
super(props);
}
 render() {
 if (this.props.mapLoading) {
  return (<Spinner />);

 }
 return (
  <Container>
    <AppHeader title="Map" />
     <View style={{ flex: 1 }}>
      <MapView
        style={styles.map}
        showsUserLocation
        showsMyLocationButton
        initialRegion={this.props.currLocation}
        region={this.props.currLocation}
      >
        <MapView.Polyline
          coordinates={this.props.markers.map((marker) => marker.coordinate)}
          strokeWidth={3}
        />
       </MapView>
    </View>
    </Container>
    );
  }
}

A: Try
startWatchPosition = () => {
    if (!this.watchId) {
      this.watchId = navigator.geolocation.watchPosition(


text:
Q: Feature selection for the text mining? Before performing the task of text mining, we need to select the features for characterizing each given document. Are there any systematic guidance on choosing the document features? How does the length of the document affect the feature selection process for the documents?

A: There are a lot of ways for doing feature selection.  I'll give you my "system" that works in my domain (insurance).
The first thing I usually try is calculating TF-IDF and taking the top 5-20% depending on how many features there are.  To be honest, I don't worry too much about document length at this stage (or more specifically - the difference in lengths between documents) - I feel the TF portion of TF-IDF accounts for that, and IDF essentially creates a "corpus specific" stopword list.  But I'm also not comparing Tweets to say War and Peace either.
I then take these features and use Naive Bayes to classify - I consider this to be my "baseline", but it's often good enough - especially since I frequently only need to quantify text for combination with more traditional structured data.
Hope this enough to get you started.

A: It really depends on the data and the problem you are trying to solve. Tf-Idf is very common but one might also consider if a binary weighting scheme is better.
What algorithm to choose  for your particular task can be difficult to say ad-hoc but SVM's are very popular. The text mining project i did so far was with tf-idf score and linear support vector machine, with no feature selection.

A: There's a python library for feature selection
TextFeatureSelection.  This library provides discriminatory power in the form of score for each word token, bigram, trigram etc.
Those who are aware of feature selection methods in machine learning, it is based on filter method and provides ML engineers required tools to improve the classification accuracy in their NLP and deep learning models. It has 4 methods namely Chi-square, Mutual information, Proportional difference and Information gain to help select words as features before being fed into machine learning classifiers.
from TextFeatureSelection import TextFeatureSelection

#Multiclass classification problem
input_doc_list=['i am very happy','i just had an awesome weekend','this is a very difficult terrain to trek. i wish i stayed back at home.','i just had lunch','Do you want chips?']
target=['Positive','Positive','Negative','Neutral','Neutral']
fsOBJ=TextFeatureSelection(target=target,input_doc_list=input_doc_list)
result_df=fsOBJ.getScore()
print(result_df)

#Binary classification
input_doc_list=['i am content with this location','i am having the time of my life','you cannot learn machine learning without linear algebra','i want to go to mars']
target=[1,1,0,1]
fsOBJ=TextFeatureSelection(target=target,input_doc_list=input_doc_list)
result_df=fsOBJ.getScore()
print(result_df)

A: Approaches to feature selection have been developed since the 1960-es. It's a tricky problem to approach when looking for the optimal feature subset to select.
In the 1968-paper, Huges demonstrated that the performance of a classifier can peak and thereafter decline - on an independent test set - when adding still more features [G.F.Hughes. On the mean accuracy of statistical pattern recognizers, IEEE Trans. Inf. Theory, 14 (55-63) 1968]. This test-performance peaking is counter intuitive as one would expect that adding even more features to a classifier should not decline its performance. Acknowledge that all 'good' features are retained when adding still more (possibly noisy) features. The larger the training set size is, in terms of observations or 'cases', the later will a possible 'peak' occur.
Peaking is synonymous with overfitting of your text classifier.
Your question: "How does the length of the document affect the feature selection process for the documents?"
Text length, and therefore training set size certainly influences the location of a possible peak, when pruning redundant features. The larger the training set size the less risk of overgeneralization (and hence peaking).
Your question: "Are there any systematic guidance on choosing the document features?" I recommend that you dig into the subject 'feature selection' in the scientific literature, for example [M. Kudo, J. Sklansky, Comparison of algorithms that select features for pattern classifiers, Pattern Recognition, 33(1), 25-41, 2000]. One strategy that stands out for feature selection is floating search by Pudil. It's more work to implement than a simple wrapper, but 'floating search' does often yield superior results.


text:
Q: Raster Biserial Correlation Is there any way to perform a biserial correlation or a point-biserial correlation between a heatmap and a binary raster, by using QGIS, r or python, considering that both have the same extent, resolution and CRS?

A: I figured out a method. By using R, I get the values from both, the dichotomous raster and the continuous one. So, it was possible to calculate a point-biserial correlation though the function biserial.cor. However, as I am not an expert in R, I hope you guys can tell me if something does not look right.
library(raster)
library(ltm)

pointb.correlation <- function(cnt_lyr_vector, dct_lyr_vector, output_dir)
{
  cat('\nPerforming point-biserial correlation ...\n\n')
  f_result <- list()

  for (i in 1:length(names(dct_lyr_vector))) {

    dct_lyr <- dct_lyr_vector[[i]]
    dct_lyr_name <- names(dct_lyr_vector[[i]])

    cat('Getting values from dichotomous layer', dct_lyr_name, '...\n')
    dct_lyr_values <- extract(dct_lyr, extent(dct_lyr))

    cat('Replacing missing values from', dct_lyr_name, '...\n\n')
    dct_lyr_values[is.na(dct_lyr_values)] <- 0

    cat('Getting correlation between', dct_lyr_name, 'and:', '\n\n')
    result <- list()

    for (j in 1:length(names(cnt_lyr_vector))) {

      start_time <-Sys.time()

      cnt_lyr <- cnt_lyr_vector[[j]]
      cnt_lyr_name <- names(cnt_lyr_vector[[j]])

      cat('->', cnt_lyr_name, '\n')

      cat('Getting values from category', cnt_lyr_name, '...\n')
      cnt_lyr_values <- extract(cnt_lyr, extent(cnt_lyr))

      cat('Replacing missing values from', cnt_lyr_name, '...\n')
      cnt_lyr_values[is.na(cnt_lyr_values)] <- 0

      cat('Doing the math, be patient :)', '\n')
      r_key <- paste(dct_lyr_name, cnt_lyr_name, sep = ".")
      result[[r_key]] <- biserial.cor(cnt_lyr_values, dct_lyr_values, use = c("complete.obs"), level = 1)

      end_time <-Sys.time()
      time_taken <- end_time - start_time
      cat('Time taken: ', time_taken,  '\n\n')
    }
    filename <- file.path(output_dir, dct_lyr_name)
    write.table(unlist(result), filename, row.names = TRUE, col.names=FALSE, sep = ",", eol = "\n")

    f_result <- append(f_result, result)
  }
  return(f_result)
}

exec <- function(dichotomous_lyr_dir, continuous_lyr_dir, output_dir)
{
  cnt_vector <- grep(".tif$", list.files(file.path(continuous_lyr_dir), all.files = F), ignore.case = TRUE, value = TRUE)
  cnt_vector_full_path <- file.path(continuous_lyr_dir, cnt_vector)
  cnt_stack <- raster::stack(cnt_vector_full_path)

  dct_vector <- grep(".tif$", list.files(file.path(dichotomous_lyr_dir), all.files = F), ignore.case = TRUE, value = TRUE)
  dct_vector_full_path <- file.path(dichotomous_lyr_dir, dct_vector)
  dct_stack <- raster::stack(dct_vector_full_path)

  corr_matrix <- pointb.correlation(cnt_stack, dct_stack, output_dir)

  return(corr_matrix)
}

dct_lyr_folder <- ''
cnt_folder <- ''
results_folder <- ''
matrix <- exec(dct_lyr_folder, cnt_folder, results_folder)


text:
Q: How can we clear the value of paramter in dialogflow using nodejs API NODEJS
dialogContext = {
    name: "[intent-name]-dialog-context",
    parameters {
        "height": ""
    }
}

I have to deal with negative flow. Suppose this is the conversation
BOT : What is your height?
USER : 4ft 12 inch
BOT:You said your height is 4ft 12 inch.Please Confirm
In this case  "height" is parameter and if User respond as YES we should proceed to next question but if user says NO then I need to clear the value of parameter "height" and bot will repeat the same question. Using above code, I tried to clear the height. But It's not working.


text:
Q: Mediawiki API: get recent changes with categories of each page, or only those recentchanges entries which are in a certain category I want to retrieve from Mediawiki  the list of recent changes in a certain category. I am trying to use the recentchanges API; I would either need to be able to limit the results to that category, or for each recentchanges entry get the list of categories that page is in.

A: There is no way to get the list of changes in a specific category. To get the categories of each page, use the recentchanges API module as a generator: action=query&generator=recentchanges&prop=categories


text:
Q: I want to know the natural expression for contrasting I want to elucidate the characteristics of one object, contrasting to another object at the end of the sentence. However, I am not sure whether these expressions natural or not. Please let me know what are the natural sentences in the followings.
Microwave is an energy-efficient tool for heating the material -

*

*distinct from dry oven.

*different from dry oven

*other than dry oven.

*contrasting to dry oven.

Or I will terribly appreciate you if you let me know other expressions which could deliver the same meaning in the more fluent form.

A: Unfortunately, you cannot use this structure here as follows. This is because in such case you will be comparing "the material" with the "dry oven". There are few ways to fix this:

*

*The dry oven is distinct from the microwave in that the latter is an energy-efficient tool for heating the material.

*Unlike the dry oven, the microwave is an energy-efficient tool for heating the material.

*In contrast to the dry oven, the microwave is an energy-efficient tool for heating the material.

*The microwave differs from the dry oven in that the former is an energy-efficient tool for heating the material.

In respect to your comment:

*

*A microwave is an energy-efficient tool for heating the material, whereas a dry oven isn't.

*The microwave is an energy-efficient tool for heating the material, unlike the dry oven.


text:
Q: Shell: insert variable into a command I'm trying to find a way the use a variable in this command to replace -10 with n_days var:
   n_days= -10
   date_prefix=$(date -d '-10 day' +%Y/%m/%d)

I tried this way but it didn't work:
   date_prefix=$(date -d '${n_days} day' +%Y/%m/%d)

A: Two things:

*

*Declare your variable properly (there is a space in your example)

*Use double quotes in place of single quotes to allow the variable to be interpolated

So:
n_days=-10
date_prefix=$(date -d "$n_days day" +%Y/%m/%d)


text:
Q: changing stylesheet dynamically I'm trying to change the style of my QLabel using a dynamic property since we can target this property in QSS like this:
QLabel[foo = "warning"]{ color: red; }
QLabel[foo = "success"]{ color: green; }

the stye of my label does update when I use the QApplication::setStyleSheet() but does not seems to work when I change the value of the property.
label = new QLabel( this );
label->setText( "some text" );
label->setProperty( "foo", "warning");

// after some event
label->setProperty( "foo", "success" );
// the label's color should be green now

did I missed something, or the style change can just not work this way ?.

A: Wherever we are changing the property we need to add the following code to trigger an update
label->setProperty("foo", "success");
label->style()->unpolish(label);
label->style()->polish(label);
label->update();

http://qt-project.org/wiki/DynamicPropertiesAndStylesheets

A: Had the same problem in PyQT today. None of the suggestions found on SO worked, but what did work in the end is to use the cascading nature of stylesheets. In my application, I had an application-wide stylesheet that would style buttons differently when they are checked:
QToolButton {
    background-color: #12313F;
    background: #12313F;
    color: #DEE8EC;
    spacing: 0px;
    border: none
}

QToolButton[checked="true"] {
    background-color: #5B8AA1;
    background: #5B8AA1;
}

This is set to be the main stylesheet, this is python but hopefully it gets the idea across (I'm reading the stylesheet as a string from style.css):
mainwindow.setStyleSheet(
    pkg_resources.resource_stream(__name__, 'style.css').read())

In my code the checked property of the QAction children of the toolbar might change, and then I want the toolbar to update and that button to be highlighted.
To accomplish this (took lots of trial and error), I override the stylesheet of my toolbar object, which is a child of the main window. It turns out I don't even have to set anything, an empty string is enough:
toolbar.setStyleSheet("")

Et Voila, the toolbar renders correctly. QT 4.8. YMMV in C++ but hopefully it works.


text:
Q: Error message 887c499c-ef3d-40c5-0fc9-dbcbaed12ad2 WHen I create a MySite host and then I recieved a error message with correlation ID: 887c499c-ef3d-40c5-0fc9-dbcbaed12ad2
I tried googling by no answer came up. What should I do?

A: The correlation id is unique to your request/operation to your SharePoint farm this will always be unique, so googling for it will never give anything usefull.
Read Get the Real SharePoint Error using the ULS Logs for how to get the real error message


text:
Q: Pandas: Calling df.loc[] from an index consisting of pd.datetime Say I have a df as follows:
a=pd.DataFrame([[1,3]]*3,columns=['a','b'],index=['5/4/2017','5/6/2017','5/8/2017'])
a.index=pd.to_datetime(a.index,format='%m/%d/%Y')

The type of of the df.index is now
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>

When we try to call a row of data based on the index of type pd.datetime, it is possible to call the value based on a string format of date instead of inputting a datetime object. In the above case, if I want to call a row of data on 5/4/2017, I can simply input the string format of the date to .loc as follows:
print(a.loc['5/4/2017'])

And we do not need to input the datetime object
print(a.loc[pd.datetime(2017,5,4)]

My question is, when calling the data from .loc based on string format of date, how does pandas know if my date string format follows m-d-y or d-m-y or other combinations? In this above case, I used a.loc['5/4/2017'] and it succeeds in returning the value. Why wouldn't it think it might mean April 5 which is not within this index?

A: Here's my best shot:
Pandas has an internal function called pandas._guess_datetime_format. This is what gets called when passing the 'infer_datetime_format' argument to pandas.to_datetime. It takes a string and runs through a list of "guess" formats and returns its best guess on how to convert that string to a datetime object.
Referencing a datetime index with a string may use a similar approach.
I did some testing to see what would happen in the case you described - where a dataframe contains both the date 2017-04-05 and 2017-05-04.
In this case, the following:
df.loc['5/4/2017']

Returned the Data for May 4th, 2017
df.loc['4/5/2017']

Returned the data for April 5th, 2017.
Attempting to reference 4/5/2017 in your original matrix gave an "is not in the [index]" error.
Based on this, my conclusion is that pandas._guess_datetime_format defaults to a "%m/%d/%Y" format in cases where it cannot be distinguished from "%d/%m/%Y". This is the standard date format in the US.


text:
Q: How to generate infinitly enemies in XNA? I was developing a game using XNA frame work and here is my code
I just want to generate infinite number of enemies
here is my code please help
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace fight_in_the_sky
{
/// <summary>
/// This is the main type for your game
/// </summary>
///
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spritebatch;
    Texture2D  anim, background1, background2, enemy;
    Rectangle rect0, rect2, rectdst, srcrect, rect3, rect4, srcrect2, enemy_rect;
    float elapsed;
    float delay = 40f;
    int frames = 0;
    Random random = new Random();
    public Vector2 velocity;
    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.PreferredBackBufferWidth = 800;
        graphics.PreferredBackBufferHeight = 600;
        IsMouseVisible = true;
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        rectdst = new Rectangle(0, 250, 115, 69);
        rect3 = new Rectangle(0,0,1280,720);
        rect4 = new Rectangle(1280, 0, 1280, 720);
        enemy_rect = new Rectangle(random.Next(800-94,800-47),random.Next(600-122,600-61),376/8,61);
        velocity.X = 3f;
        velocity.Y = 3f;
        base.Initialize();
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spritebatch = new SpriteBatch(GraphicsDevice);
        background1= Content.Load<Texture2D>("starfield006");
        background2= Content.Load<Texture2D>("starfield005");
        anim=Content.Load<Texture2D>("shipAnimation");
        enemy =Content.Load<Texture2D>("mineAnimation");
        rect0 = new Rectangle(0, 0, 800, 600);
        rect2 = new Rectangle(0, 250,200, 100);

        // TODO: use this.Content to load your game content here
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        // if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        // this.Exit();
        // TODO: Add your update logic here
        elapsed += (float)gameTime.ElapsedGameTime.Milliseconds;
        if (Keyboard.GetState().IsKeyDown(Keys.Left))
        {
            rectdst.X -= 12;
            if (rectdst.X < 0) { rectdst.X = 0; }
        }
        if (Keyboard.GetState().IsKeyDown(Keys.Right))
        {
            rectdst.X += 12;
            if (rectdst.X > 700) { rectdst.X = 700; }
        }
        if (Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            rectdst.Y -= 12;
            if (rectdst.Y < 0) { rectdst.Y = 0; }
        }
        if (Keyboard.GetState().IsKeyDown(Keys.Down))
        { rectdst.Y += 10; if (rectdst.Y > 550) { rectdst.Y = 550; } }
        base.Update(gameTime);
        if (elapsed >= delay)
        {
            if (frames >= 7)
            { frames = 0; }
            else { frames++; }
            elapsed = 0;
        }
        srcrect = new Rectangle(115 * frames, 0, 115, 69);
        srcrect2 = new Rectangle(47*frames,0,47,61);
        if (rect3.X + background1.Width <= 0)
            rect3.X = rect4.X + background2.Width;
        if (rect4.X + background2.Width <= 0)
            rect4.X = rect3.X + background1.Width;
        rect3.X -= 5;
        rect4.X -= 5;
        enemy_rect.X +=(int) velocity.X;
        enemy_rect.Y += (int)velocity.Y;
        if (enemy_rect.Y >= 600 - 61 || enemy_rect.Y <= 0) velocity.Y = -velocity.Y;
        if (enemy_rect.X >= 800 - 47) velocity.X = -velocity.X;

    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        spritebatch.Begin();
        spritebatch.Draw(background1,rect3, Color.Azure);
        spritebatch.Draw(background2,rect4, Color.Azure);
        spritebatch.Draw(anim, rectdst, srcrect, Color.White);
        spritebatch.Draw(enemy, enemy_rect, srcrect2, Color.White);
        spritebatch.End();
        base.Draw(gameTime);
    }
}

}
and here is a shot of my current output
http://imgur.com/7y43S7O

A: Infinite is unpractical to build into a game, because sooner or later you would either run out of RAM or your screen would be too full to call it a game. Anyway, I can give you a basic idea to work with.
If you want your enemy count to keep increasing you can use a list and add an enemy every time you want one to appear
List<Enemy> enemies = new List<Enemy>;

In Update:
if(spawnTimer > spawnInterval && enemies.Count()<enemyLimit){
   enemies.add(new Enemy([rectangle of spawn location and image size]);
   spawnTimer = 0;
}
for(int i=0; i<enemies.Count();i++){
   if(enemies[i].defeated){
   enemies.Remove(enemies[i]);
}
spawnTimer+=gameTime.ElapsedGameTime.TotalSeconds;

in Draw:
   for(int i=0; i<enemies.Count();i++){
       spritebatch.Draw(enemy, enemies[i].Rect, srcrect2, Color.White);
    }

class Enemy{
   public Rectangle Rect{get;set;}
   public bool defeated{get;set;}
   public int Health{get;set;}

   public Enemy(Rectangle rect){
      Rect = rect;
      Health = 100;
      defeated = false;
   }

}


text:
Q: Fade out splashscreen, fade in webview in android Am currently using the code below to switch between my splashscreen and my webview. It works fine except that the switch is abrupt and not really elegant. What I want to know is how to make the splash screen fade away when content is loaded and the webview fadein instead?
here is my working code;
@Override
            public void onPageFinished(WebView view, String url) {
            //hide loading image
            findViewById(R.id.imageLoading1).setVisibility(View.GONE);
            //show webview
            findViewById(R.id.webview).setVisibility(View.VISIBLE);
        }

Thank you.

A: Use this :
private ImageView splash;

splash = (ImageView) findViewById(R.id.SplashId);
        webview = (WebView) findViewById(R.id.WebviewId);

        webview.setVisibility(View.GONE);
        splash.setVisibility(View.VISIBLE);

        final Animation fadeIn = new AlphaAnimation(0, 1);
        fadeIn.setInterpolator(new DecelerateInterpolator());
        fadeIn.setDuration(1000);
        final Animation fadeOut = new AlphaAnimation(1, 0);
        fadeOut.setInterpolator(new AccelerateInterpolator());
        fadeOut.setStartOffset(1000);
        fadeOut.setDuration(1000);
        final AnimationSet animation = new AnimationSet(false);
        animation.addAnimation(fadeIn);
        animation.addAnimation(fadeOut);

    webview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {

        splash.setAnimation(fadeOut);
        splash.postDelayed(new Runnable() {
                @Override
                public void run() {
                    splash.setVisibility(View.GONE);
                    webview.setVisibility(View.VISIBLE);
                    webview.setAnimation(fadeIn);
                }
            }, 1600);
        }

});

Gone Splash [FadeOut] And then, Visible WebView [FadeIn] by Animation.
Enjoy :)


text:
Q: Windows EC2 User Data Not Executing The problem:
We need to execute a Powershell script using Userdata on a Windows AWS EC2 instance so that we can join and unjoin our domain's activity directory. The EC2 Userdata log shows the instance being stuck at:
Ec2HandleUserData :  is currently executing. To end it kill the process with id:

We have tried adding lines of code documented here but no luck. Can anyone see what is being done wrong? Note we have commented out logging because we don't currently have CloudWatch setup. Script we are using is below and thank you for your help!
<powershell>
$file = $env:SystemRoot + "\Temp\" + (Get-Date).ToString("MM-dd-yy-hh-mm")
New-Item $file -ItemType file
# Script parameters
[string]$SecretAD = "prod/AD"
#class Logger {
#   #----------------------------------------------
#   [string] hidden  $cwlGroup
#   [string] hidden  $cwlStream
#   [string] hidden  $sequenceToken
#   #----------------------------------------------
#   # Log Initialization
#   #----------------------------------------------
#   Logger([string] $Action) {
#       $this.cwlGroup = "/ps/boot/configuration/"
#       $this.cwlStream = "{0}/{1}/{2}" -f $env:COMPUTERNAME, $Action,
#       (Get-Date -UFormat "%Y-%m-%d_%H.%M.%S")
#       $this.sequenceToken = ""
#       #------------------------------------------
#       if ( !(Get-CWLLogGroup -LogGroupNamePrefix $this.cwlGroup) ) {
#           New-CWLLogGroup -LogGroupName $this.cwlGroup
#           Write-CWLRetentionPolicy -LogGroupName $this.cwlGroup -RetentionInDays 3
#       }
#       if ( !(Get-CWLLogStream -LogGroupName $this.cwlGroup -LogStreamNamePrefix $this.cwlStream) ) {
#           New-CWLLogStream -LogGroupName $this.cwlGroup -LogStreamName $this.cwlStream
#       }
#   }
#   #----------------------------------------
#   [void] WriteLine([string] $msg) {
#       #$logEntry = New-Object -TypeName "Amazon.CloudWatchLogs.Model.InputLogEvent"
#       #-----------------------------------------------------------
#       #$logEntry.Message = $msg
#       #$logEntry.Timestamp = (Get-Date).ToUniversalTime()
#       if ("" -eq $this.sequenceToken) {
#           # First write into empty log...
#           $this.sequenceToken = Write-CWLLogEvent -LogGroupName $this.cwlGroup `
#               -LogStreamName $this.cwlStream `
#               -LogEvent #$logEntry
#       }
#       else {
#           # Subsequent write into the log...
#           $this.sequenceToken = Write-CWLLogEvent -LogGroupName $this.cwlGroup `
#               -LogStreamName $this.cwlStream `
#               -SequenceToken $this.sequenceToken `
#               -LogEvent #$logEntry
#       }
#   }
#}
#[Logger]#$log = [Logger]::new("UserData")
#$log.WriteLine("------------------------------")
#$log.WriteLine("Log Started - V4.0")
$RunUser = 'TrustedInstaller'

Write-Output "I set the run user"

#$log.WriteLine("PowerShell session user: $RunUser")
class SDManager {
    #-------------------------------------------------------------------
    #[Logger] hidden $SDLog
    [string] hidden $GPScrShd_0_0 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0"
    [string] hidden $GPMScrShd_0_0 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0"
    #-------------------------------------------------------------------
    SDManager([string]$RegFilePath, [string]$SecretName) {
        #$this.SDLog = #$log
        #----------------------------------------------------------------
        [string] $SecretLine = '[string]$SecretAD    = "' + $SecretName + '"'
        #--------------- Local Variables -------------
        [string] $GPRootPath = "C:\Windows\System32\GroupPolicy"
        [string] $GPMcnPath = "C:\Windows\System32\GroupPolicy\Machine"
        [string] $GPScrPath = "C:\Windows\System32\GroupPolicy\Machine\Scripts"
        [string] $GPSShdPath = "C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown"
        [string] $ScriptFile = [System.IO.Path]::Combine($GPSShdPath, "Shutdown-UnJoin.ps1")
        #region Shutdown script (scheduled through Local Policy)
        $ScriptBody =
        @(
            'param([string]$cntrl = "NotSet")',
            $SecretLine,
            '[string]$MachineName = $env:COMPUTERNAME',
            '#class Logger {    ',
            '#    #----------------------------------------------    ',
            '#    [string] hidden  $cwlGroup    ',
            '#    [string] hidden  $cwlStream    ',
            '#    [string] hidden  $sequenceToken    ',
            '#    #----------------------------------------------    ',
            '#    # Log Initialization    ',
            '#    #----------------------------------------------    ',
            '#    Logger([string] $Action) {    ',
            '#        $this.cwlGroup = "/ps/boot/configuration/"    ',
            '#        $this.cwlStream = "{0}/{1}/{2}" -f $env:COMPUTERNAME, $Action,    ',
            '#                                           (Get-Date -UFormat "%Y-%m-%d_%H.%M.%S")    ',
            '#        $this.sequenceToken = ""    ',
            '#        #------------------------------------------    ',
            '#        if ( !(Get-CWLLogGroup -LogGroupNamePrefix $this.cwlGroup) ) {    ',
            '#            New-CWLLogGroup -LogGroupName $this.cwlGroup    ',
            '#            Write-CWLRetentionPolicy -LogGroupName $this.cwlGroup -RetentionInDays 3    ',
            '#        }    ',
            '#        if ( !(Get-CWLLogStream -LogGroupName $this.cwlGroup -LogStreamNamePrefix $this.cwlStream) ) {    ',
            '#            New-CWLLogStream -LogGroupName $this.cwlGroup -LogStreamName $this.cwlStream    ',
            '#        }    ',
            '#    }    ',
            '#    #----------------------------------------    ',
            '#    [void] WriteLine([string] $msg) {    ',
            '#        #$logEntry = New-Object -TypeName "Amazon.CloudWatchLogs.Model.InputLogEvent"    ',
            '#        #-----------------------------------------------------------    ',
            '#        #$logEntry.Message = $msg    ',
            '#        #$logEntry.Timestamp = (Get-Date).ToUniversalTime()    ',
            '#        if ("" -eq $this.sequenceToken) {    ',
            '#            # First write into empty log...    ',
            '#            $this.sequenceToken = Write-CWLLogEvent -LogGroupName $this.cwlGroup `',
            '#                -LogStreamName $this.cwlStream `',
            '#                -LogEvent #$logEntry    ',
            '#        }    ',
            '#        else {    ',
            '#            # Subsequent write into the log...    ',
            '#            $this.sequenceToken = Write-CWLLogEvent -LogGroupName $this.cwlGroup `',
            '#                -LogStreamName $this.cwlStream `',
            '#                -SequenceToken $this.sequenceToken `',
            '#                -LogEvent #$logEntry    ',
            '#        }    ',
            '#    }    ',
            '#}    ',
            '#[Logger]#$log = [Logger]::new("UnJoin")',
            '#$log.WriteLine("-----------------------------------------")',
            '#$log.WriteLine("Log Started")',
            'if ($cntrl -ne "run") ',
            '    { ',
            '    #$log.WriteLine("Script param <" + $cntrl + "> not set to <run> - script terminated") ',
            '    return',
            '    }',
            '$compSys = Get-WmiObject -Class Win32_ComputerSystem',
            'if ( -Not ($compSys.PartOfDomain))',
            '    {',
            '    #$log.WriteLine("Not member of a domain - terminating script")',
            '    return',
            '    }',
            '$RSAT = (Get-WindowsFeature RSAT-AD-PowerShell)',
            'if ( $RSAT -eq $null -or (-Not $RSAT.Installed) )',
            '    {',
            '    #$log.WriteLine("<RSAT-AD-PowerShell> feature not found - terminating script")',
            '    return',
            '    }',
            '#$log.WriteLine("Removing machine <" +$MachineName + "> from Domain <" + $compSys.Domain + ">")',
            '#$log.WriteLine("Reading Secret <" + $SecretAD + ">")',
            #'Import-Module AWSPowerShell',
            #'try { $SecretObj = (Get-SECSecretValue -SecretId $SecretAD) }',
            #'catch ',
            #'    { ',
            #'    #$log.WriteLine("Could not load secret <" + $SecretAD + "> - terminating execution")',
            #'    return ',
            #'    }',
            #'[PSCustomObject]$Secret = ($SecretObj.SecretString  | ConvertFrom-Json)',
            '$password   = "<password>"',
            '$username   = "<username>"',
            '$credential = New-Object System.Management.Automation.PSCredential($username,$password)',
            'import-module ActiveDirectory',
            '$DCHostName = (Get-ADDomainController -Discover).HostName',
            '#$log.WriteLine("Using Account <" + $username + ">")',
            '#$log.WriteLine("Using Domain Controller <" + $DCHostName + ">")',
            'Remove-Computer -WorkgroupName "WORKGROUP" -UnjoinDomainCredential $credential -Force -Confirm:$false ',
            'Remove-ADComputer -Identity $MachineName -Credential $credential -Server "$DCHostName" -Confirm:$false ',
            '#$log.WriteLine("Machine <" +$MachineName + "> removed from Domain <" + $compSys.Domain + ">")'
        )
        #$this.SDLog.WriteLine("Constracting artifacts required for domain UnJoin")
        #----------------------------------------------------------------
    Write-Output "I created SDManager class"

        try {
            if (!(Test-Path -Path $GPRootPath -pathType container))
            { New-Item -ItemType directory -Path $GPRootPath }
            if (!(Test-Path -Path $GPMcnPath -pathType container))
            { New-Item -ItemType directory -Path $GPMcnPath }
            if (!(Test-Path -Path $GPScrPath -pathType container))
            { New-Item -ItemType directory -Path $GPScrPath }
            if (!(Test-Path -Path $GPSShdPath -pathType container))
            { New-Item -ItemType directory -Path $GPSShdPath }
        }
        catch {
            #$this.SDLog.WriteLine("Failure creating UnJoin script directory!" )
            #$this.SDLog.WriteLine($_)
            Write-Output  "hello"
        }
        #----------------------------------------
        try {
            Set-Content $ScriptFile -Value $ScriptBody
        }
        catch {
            #$this.SDLog.WriteLine("Failure saving UnJoin script!" )
            #$this.SDLog.WriteLine($_)
            Write-Output  "hello"
        }
        #----------------------------------------

# UPDATE WINDOWS REGISTRY AND CREATE A SHUTDOWN TASK

        $RegistryScript =
        @(
            'Windows Registry Editor Version 5.00',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts]',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown]',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0]',
            '"GPO-ID"="LocalGPO"',
            '"SOM-ID"="Local"',
            '"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"',
            '"DisplayName"="Local Group Policy"',
            '"GPOName"="Local Group Policy"',
            '"PSScriptOrder"=dword:00000001',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0]',
            '"Script"="Shutdown-UnJoin.ps1"',
            '"Parameters"=""',
            '"IsPowershell"=dword:00000001',
            '"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup]',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts]',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown]',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0]',
            '"GPO-ID"="LocalGPO"',
            '"SOM-ID"="Local"',
            '"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"',
            '"DisplayName"="Local Group Policy"',
            '"GPOName"="Local Group Policy"',
            '"PSScriptOrder"=dword:00000001',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0]',
            '"Script"="Shutdown-UnJoin.ps1"',
            '"Parameters"=""',
            '"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00',
            '[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup]'
        )
        Write-Output "I created the registry script."

        try {
            [string] $RegistryFile = [System.IO.Path]::Combine($RegFilePath, "OnShutdown.reg")
            Set-Content $RegistryFile -Value $RegistryScript
            &regedit.exe /S "$RegistryFile"
        }
        catch {
            #$this.SDLog.WriteLine("Failure creating policy entry in Registry!" )
            #$this.SDLog.WriteLine($_)
            Write-Output "hello"
        }
    }

#DISABLE UNJOIN AND ENABLE JOIN FOR THE FIRST RUN

    #----------------------------------------
    [void] DisableUnJoin() {
        try {
            Set-ItemProperty -Path $this.GPScrShd_0_0  -Name "Parameters" -Value "ignore"
            Set-ItemProperty -Path $this.GPMScrShd_0_0 -Name "Parameters" -Value "ignore"
            &gpupdate /Target:computer /Wait:0
        }
        catch {
            #$this.SDLog.WriteLine("Failure in <DisableUnjoin> function!" )
            #$this.SDLog.WriteLine($_)
            Write-Output  "hello"
        }
    }
    #----------------------------------------
    [void] EnableUnJoin() {
        try {
            Set-ItemProperty -Path $this.GPScrShd_0_0  -Name "Parameters" -Value "run"
            Set-ItemProperty -Path $this.GPMScrShd_0_0 -Name "Parameters" -Value "run"
            &gpupdate /Target:computer /Wait:0
        }
        catch {
            #$this.SDLog.WriteLine("Failure in <EnableUnjoin> function!" )
            #$this.SDLog.WriteLine($_)
            Write-Output "hello"
        }
    }
}
Write-Output "I created the the join and unjoin functions"
# GET SECRETS

#[SDManager]$sdm = [SDManager]::new(#$log, "C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts", $SecretAD)
##$log.WriteLine("Loading Secret <" + $SecretAD + ">")
#Import-Module AWSPowerShell
#try { $SecretObj = (Get-SECSecretValue -SecretId $SecretAD) }
#catch {
#   #$log.WriteLine("Could not load secret <" + $SecretAD + "> - terminating execution")
#   return
#}
#[PSCustomObject]$Secret = ($SecretObj.SecretString  | ConvertFrom-Json)
##$log.WriteLine("Domain (from Secret): <" + $domain + ">")

# Verify domain membership

#IF ALREADY MEMBER OF DOMAIN

$compSys = Get-WmiObject -Class Win32_ComputerSystem
#------------------------------------------------------------------------------
if ( ($compSys.PartOfDomain) -and ($compSys.Domain -eq $domain)) {
    #$log.WriteLine("Already member of: <" + $compSys.Domain + "> - Verifying RSAT Status")

    #CHECK IF RSTAT IS INSTALLED

    $RSAT = (Get-WindowsFeature RSAT-AD-PowerShell)
    if ($null -eq $RSAT) {
        #$log.WriteLine("<RSAT-AD-PowerShell> feature not found - terminating script")
        return
    }

    #ENABLE ON SHUT DOWN & INSTALL RSTAT

    #$log.WriteLine("Enable OnShutdown task to un-join Domain")
    $sdm.EnableUnJoin()
    if ( (-Not $RSAT.Installed) -and ($RSAT.InstallState -eq "Available") ) {
        #$log.WriteLine("Installing <RSAT-AD-PowerShell> feature")
        Install-WindowsFeature RSAT-AD-PowerShell
    }
    #$log.WriteLine("Terminating script - ")
    return
}

# IF NOT MEMBER OF DOMAIN THEN JOIN AND RESTART

# Performing Domain Join
#$log.WriteLine("Domain Join required")
#$log.WriteLine("Disable OnShutdown task to avoid reboot loop")
$sdm.DisableUnJoin()
$password = "<password>"
$username = "<username>"
$domain = "<domain>"
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
#$log.WriteLine("Attempting to join domain <" + $domain + ">")
Add-Computer -DomainName $domain -Credential $credential -Restart -Force
#$log.WriteLine("Requesting restart...")

Write-Output "I joined or unjoined the domain friends."
#------------------------------------------------------------------------------
</powershell>
<persist>true</persist>

A: Did you find an answer?  I believe your inline script is too long to be executed in userdata.  You're likely running into the issue here: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-add-user-data.html
When I run into this, I find it best to upload the script to S3, allow the EC2 instance RO access to the S3 bucket via the EC2 instance profile, then pull from the bucket and run the script in the userdata.
HTH!


text:
Q: Is possible to make a  writable by user? have to build a system that when a user write in a box a word that starts with # this is wrapped inside an html element. Inside input-text and textarea html don't work. I had thought with a div, is possible?

A: Not sure exactly what you are looking for, but you can make divs editable like this:

A: Try the following:

Hello, edit me!

Not tested in Opera, works in Firefox 3, Google Chrome, Safari and Internet Explorer 6, 7 and 8.

A: Not sure why a input or textarea won't work; you might consider handling the events fired when a user enters data into a textarea or a input to accomplish your goal.  Or you might look into a wysiwyg editor.

A: Yes, this is possible.
:)
Seriously, you'll need to parse user input and when your parser engine see a "#" symbol, it just wait for the next [space] (for example as a element id delimiter), create a new DOM Element with this id and after that it must update innerHTML of this element by everytime user entered a symbol.


text:
Q: Condense and join data frame I have a data frame that I'm trying to merge with another, and I'm having some issues that I believe trace back to the fact that each observation is an incident rather than a cumulative amount. I have the data frame below where each row is an individual observation, and I'll then use the week and the code to merge it with another data frame based on the same variables week and code.
data frame a has each row as a specific observation, but I need it to become a cumulative observation/row by code/date. I'm completely stumped.
  date       count       code  week
  <date>     <dbl>      <dbl> <dbl>
1 2020-06-07     4      13309    23
2 2020-06-07     5      13309    23
3 2020-07-12     6      18099    28
4 2020-07-12     8      18099    28

needs to become
  date       count       code  week
  <date>     <dbl>      <dbl> <dbl>
1 2020-06-07     9      13309    23
2 2020-07-12    14      18099    28

Then, it will be able to be merged with data frame  b
  date       color     name       code  week
  <date>     <char>   <char>      <dbl> <dbl>
1 2020-06-07 Blue         A      13309    23
1 2020-06-07 Yellow       B      13309    23
1 2020-06-07 Purple       D      13309    23
3 2020-07-12 Yellow       A      18099    28
3 2020-07-12 Blue         E      18099    28

and the end result will be
  date       color     name     code   week    count
  <date>     <char>   <char>   <dbl>  <dbl>    <dbl>
1 2020-06-07 Blue         A    13309     23        9
1 2020-06-07 Yellow       B    13309     23        9
1 2020-06-07 Purple       D    13309     23        9
3 2020-07-12 Yellow       A    18099     28       14
3 2020-07-12 Blue         E    18099     28       14

I originally used the code below to do this, but it completely blew up my data frame. My dimensions went from dim(a) == (209807, 86) to dim(merged) == (1367029, 89). I tried multiple types of joins (right, left, inner, etc.) but all of them still blew up the data frame (varied by a few 100 or so observations, but still resulted in well over a million rows). That's why I'm thinking the issue is due to a being each observation vs a summary observation for a specific code on a specific date.
merged <- right_join(x = b,
                     y = a,
                     by = c("code" = "code",
                       "week" = "week"))

A: a %>%
  group_by(date, code, week) %>%
  summarize(count = sum(count)) %>%
  ungroup() %>%
  left_join(b, ., by = c("date", "code", "week"))
#         date  color name  code week count
# 1 2020-06-07   Blue    A 13309   23     9
# 2 2020-06-07 Yellow    B 13309   23     9
# 3 2020-06-07 Purple    D 13309   23     9
# 4 2020-07-12 Yellow    A 18099   28    14
# 5 2020-07-12   Blue    E 18099   28    14

A: You were close with the call to right_join() but before that, the first thing you should do is to total the first data frame so you have a sum of the counts. You could do it manually with summarize() but an easier way is using a nested data frame and creating a new column that sums the counts.
Let me know if you need clarification?
Next time please post your data in a format that is easier to copy and paste into R.
library(tidyverse)

dfA <- tribble(~date, ~count, ~code, ~week,
               "2020-06-07",     4,      13309,    23,
               "2020-06-07",     5,      13309,    23,
               "2020-07-12",     6,      18099,    28,
               "2020-07-12",     8,      18099,    28)

dfB <- tribble(~date, ~color, ~name, ~code, ~week,
               "2020-06-07", "Blue", "A", 13309, 23,
               "2020-06-07", "Yellow", "B", 13309, 23,
               "2020-06-07", "Purple", "D", 13309, 23,
               "2020-07-12", "Yellow", "A", 18099, 28,
               "2020-07-12", "Blue", "E", 18099, 28)

total_counts <- dfA %>%
  group_by(date, code, week) %>%
  nest() %>%
  mutate(count= map_dbl(data, sum)) %>%
  select(date, count, code, week) %>%
   right_join(dfB) %>%
  select(date, color, name, code, week, count)
#> Joining, by = c("date", "code", "week")

total_counts

#> # A tibble: 5 x 6
#> # Groups:   date, code, week [2]
#>   date       color  name   code  week count
#>   <chr>      <chr>  <chr> <dbl> <dbl> <dbl>
#> 1 2020-06-07 Blue   A     13309    23     9
#> 2 2020-06-07 Yellow B     13309    23     9
#> 3 2020-06-07 Purple D     13309    23     9
#> 4 2020-07-12 Yellow A     18099    28    14
#> 5 2020-07-12 Blue   E     18099    28    14

Created on 2020-10-12 by the reprex package (v0.3.0)

A: Using join by data.table
library(data.table)
setDT(a)[, .(count = sum(count)), .(date, code, week)][b,
      on = .(date, code, week)]
#         date  code week count  color name
#1: 2020-06-07 13309   23     9   Blue    A
#2: 2020-06-07 13309   23     9 Yellow    B
#3: 2020-06-07 13309   23     9 Purple    D
#4: 2020-07-12 18099   28    14 Yellow    A
#5: 2020-07-12 18099   28    14   Blue    E


text:
Q: createBrowserhistory from history npm Url changes but not component React-redux Having same version for react and react-dom
"react": "^18.2.0",
"react-dom": "^18.2.0" and history is latest
"history": "^5.3.0",
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import SignInSide from "./components/mui/signIn/SignInSide";
import store from "./Store/Store";
import { Provider } from "react-redux";
import Dashboard from "./components/mui/Dashboard";
import history from './utils/history';

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <Router history={history}>
        <Routes>
          <Route path="/login" element={<SignInSide />} />
          <Route path="/home" element={<Dashboard />} >
          </Route>
          <Route path="/" element={<App />} />
        </Routes>
      </Router>
    </Provider>
  </React.StrictMode>
);

 function SignInSide(props) {
          const handleSubmit = (event) => {
            event.preventDefault();
            const form = new FormData(event.currentTarget);
            let user = {
              email: form.get('email'),
              password: form.get('password')
            }
            console.log(user);
            props.signIn(user);
          };

      return (....);

Calling handleSubmit from singIn button
 import { createBrowserHistory } from "history";
export function LoginUser(LogInData) {
  let navigate = useNavigate;
  return (dispatch) => {
    dispatch(AuthActions.userSignIn());
    signInWithEmailAndPassword(auth, LogInData.email, LogInData.password)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        dispatch(AuthActions.userSignInSuccess(user));
        setPersistence(auth, browserSessionPersistence)
          .then(() => {
            return signInWithEmailAndPassword(
              auth,
              LogInData.email,
              LogInData.password
            );
          })
          .catch((error) => {
            // Handle Errors here.
            const errorCode = error.code;
            const errorMessage = error.message;
          });
        history.push("/home");
        // console.log(store);
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        dispatch(AuthActions.userSignInFailed(error));
      });
  };
}

Using history.push("/home") this only Url replaced not component loading so please provide the solution with using latest npm version(if any) or suggest ready template ASAP.

A: The react-router-dom@6 BrowserRouter doesn't take a history prop.
BrowserRouter

declare function BrowserRouter(
  props: BrowserRouterProps
): React.ReactElement;

interface BrowserRouterProps {
  basename?: string;
  children?: React.ReactNode;
  window?: Window;
}

If you want to use a custom history object then you should import the HistoryRouter and pass the history prop for the type of history object you are creating for your app.
HistoryRouter

declare function HistoryRouter(
  props: HistoryRouterProps
): React.ReactElement;

interface HistoryRouterProps {
  basename?: string;
  children?: React.ReactNode;
  history: History;
}

Ensure that your entire app is importing and referencing the same single history object instance that is passed to the router.
Create the history object
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;

Import the HistoryRouter and the custom history object.
...
import { HistoryRouter as Router, Route, Routes } from "react-router-dom";
...
import history from './utils/history';

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <Router history={history}>
        <Routes>
          <Route path="/login" element={<SignInSide />} />
          <Route path="/home" element={<Dashboard />} >
          </Route>
          <Route path="/" element={<App />} />
        </Routes>
      </Router>
    </Provider>
  </React.StrictMode>
);

...
import history from './utils/history';

export function loginUser(logInData) {
  return (dispatch) => {
    dispatch(AuthActions.userSignIn());
    signInWithEmailAndPassword(auth, logInData.email, logInData.password)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        dispatch(AuthActions.userSignInSuccess(user));

        setPersistence(auth, browserSessionPersistence)
          .then(() => {
            return signInWithEmailAndPassword(
              auth,
              logInData.email,
              logInData.password
            );
          })
          .catch((error) => {
            // Handle Errors here.
            const errorCode = error.code;
            const errorMessage = error.message;
          });

        history.push("/home");
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        dispatch(AuthActions.userSignInFailed(error));
      });
  };
}


text:
Q: matInput not displaying data and i can't see what am typying in a matInput, until after reloading or refreshing the page When i retrieve data from the server,nothing is displayed inside a matInput control. Also when am typing in a matInput control still i can't see what am typing.

But after reloading or refreshing the page the data is displayed and i can also see what am typing inside a matInput control

 <div class="col-md-12">
                <mat-form-field class="example-full-width">
                    <input matInput placeholder="Tenant Name" [(ngModel)]="tenantDto.name" formControlName="name" readonly>
                </mat-form-field>
                <!-- <input placeholder="Tenant Name" [(ngModel)]="tenantDto.name" formControlName="name" readonly/> -->
            </div>


text:
Q: How to add abstract for selected chapters in my thesis I am trying to add abstract for some selected chapters in my thesis. I am using shareLatex and I selected a template they offer for free (the Cambridge one). The problem is that it has lots of folders in that file and you have to work in each file independently of the other. I am still somehow new to latex in this way and I would like a detail explanation please. For example, in this shareLatex one of the folders is called "Macros" the other are called "Classes" and so on. The thesis.tex has the following
%input macros (i.e. write your own macros file called MacroFile1.tex)
%\include{Macros/MacroFile1}

 \documentclass[oneside,12pt]{Classes/CUEDthesisPSnPDF}

\ifpdf
    \pdfinfo { /Title  (CUED PhD and MPhil Thesis Classes)
               /Creator (TeX)
               /Producer (pdfTeX)
               /Author (######@gmail.com)
               /CreationDate (D:20030101000000)  %format D:YYYYMMDDhhmmss
               /ModDate (D:20030815213532)
               /Subject (Writing a PhD thesis in LaTeX)
               /Keywords (PhD, Thesis)}
    \pdfcatalog { /PageMode (/UseOutlines)
                  /OpenAction (fitbh)  }
\fi

\title{Writing a PhD Thesis\\[1ex]
        in \LaTeXe}

\ifpdf
  \author{\href{mailto:####5@gmail.com}{######}}
  \collegeordept{\href{http://business-school.exeter.ac.uk/research/areas/topics/economics}{Department of Economics}}
  \university{\href{http://www.exeter.ac.uk}{University of Exeter}}
% insert below the file name that contains the crest in-place of 'UnivShield'
  \crest{\includegraphics[width=90mm]{UnivShield}}
\else
  \author{####}
  \collegeordept{######}
  \university{#######}
% insert below the file name that contains the crest in-place of 'UnivShield'
  \crest{\includegraphics[bb = 0 0 292 336, width=30mm]{UnivShield}}
\fi
%
% insert below the file name that contains the crest in-place of 'UnivShield'
% \crest{\IncludeGraphicsW{UnivShield}{40mm}{14 14 73 81}}
%
%\renewcommand{\submittedtext}{change the default text here if needed}
\degree{Doctor of Philosophy}
\degreedate{Yet to be decided}

% turn of those nasty overfull and underfull hboxes
\hbadness=10000
\hfuzz=50pt

% Put all the style files you want in the directory StyleFiles and usepackage like this:
\usepackage{StyleFiles/watermark}

% Comment out the next line to get single spacing
\onehalfspacing

\usepackage{natbib}
\usepackage{mathtools}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage{etex,etoolbox}
\usepackage{amsthm,amssymb}
\usepackage{thmtools}
\usepackage{environ}
\usepackage{thmtools,thm-restate}
% ------------------------------------------------------------------------

\bibliographystyle{agsm}

% ------------------------------------------------------------------------

\newtheorem{theorem}{Theorem}
\newtheorem{lemma}{Lemma}
\newtheorem{proposition}{Proposition}
\newtheorem{claim}{Claim}
\newtheorem{fact}{Fact}
\newtheorem{corollary}{Corollary}
\newtheorem{assumption}{Assumption}
\newtheorem{algoritheorem}{Algoritheorem}
\newtheorem{remark}{Remark}
\newtheorem{definition}{Definition}

\newtheoremstyle{named}{}{}{\itshape}{}{\bfseries}{.}{.5em}{\thmnote{#3's }#1}
\theoremstyle{named}
\newtheorem*{namedtheorem}{Theorem}

% ------------------------------------------------------------------------
\newcommand\equDis{\,{\buildrel d \over =}\,}
\newcommand\AsyDis{\xrightarrow[]{d}}
\newcommand\AsyArrow{\xrightarrow[]{}}

% ------------------------------------------------------------------------

% ------------------------------------------------------------------------
\DeclareMathOperator{\PR}{\mathbb{P}}
\DeclareMathOperator{\RNB}{\mathbb{R}} % Real NUmber Bold
\DeclareMathOperator{\sign}{sign} % sign Operator

% ------------------------------------------------------------------------

\begin{document}

%\language{english}

% A page with the abstract on including title and author etc may be
% required to be handed in separately. If this is not so, then comment
% the below 3 lines (between '\begin{abstractseparte}' and
% 'end{abstractseparate}'), normally like a declaration ... needs some more
% work, mind as environment abstracts creates a new page!
% \begin{abstractseparate}
%   \input{Abstract/abstract}
% \end{abstractseparate}

% Using the watermark package which is in StyleFiles/
% and to remove DRAFT COPY ONLY appearing on the top of all pages comment out below line
%\watermark{DRAFT COPY ONLY}

\maketitle

%set the number of sectioning levels that get number and appear in the contents
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}

\frontmatter % book mode only
\pagenumbering{roman}
\include{Dedication/dedication}
\include{Acknowledgement/acknowledgement}
\include{Abstract/abstract}

\tableofcontents
\listoffigures
\printnomenclature  %% Print the nomenclature
\addcontentsline{toc}{chapter}{Nomenclature}

\mainmatter % book mode only
\include{Introduction/introduction}
\include{Chapter1/chapter1}
\include{Chapter2/chapter2}
\include{Chapter3/chapter3}
\include{Conclusions/conclusions}

\backmatter % book mode only
\appendix
\include{Appendix1/appendix1}
\include{Appendix2/appendix2}

\renewcommand{\bibname}{References} % changes default name Bibliography to References
\bibliography{References/references} % References file

\end{document}

A: Going through the internet, it seems evident that each latex file has its own document class (\documentclass) in latex. In the template, I was using I should have to access a folder called "Classes" and follow "CUEDthesisPSnPDF". In the file "CUEDthesisPSnPDF" I have searched for abstract under this I have written the following environment
\newenvironment{chapabstract}
{
    \begin{center}%
    \vspace*{1.5cm}
      \Large \bfseries Abstract \vspace{-.5em}\vspace{0pt}
    \end{center}
    \list{}{%
    \setlength{\leftmargin}{5mm}% <---------- CHANGE HERE
    \setlength{\rightmargin}{\leftmargin}%
  }%
  \item\relax
}
{\par}
\makeatother

Therefore, in each chapter, I have done the following
\chapter{Hello}
\begin{chapabstract}
     I am good
\end{chapabstract}
\section{ One}


text:
Q: Using System.IO in UWP apps? is it possible/allowed to use System.IO in UWP apps? I thought to know that I'm not supposed to use it since in UWP, files are stored as StorageFile.
Now I want to provide methods to zip files in UWP. I've tried solving it following this thread. To use this solution, I would need to use System.IO. I didn't even test if this solution works because I am confused right now. I've been working on an UWP app for a bit longer than a month now and I'm pretty sure that I'm not supposed to use System.IO in UWP apps.
Am I missing a point here? Can we use System.IO in UWP?

A: There's an entire MSDN page dedicated to this subject: System.IO namespaces for UWP apps.
The System.IO.Compression.ZipArchive
class which this question appears to be about is supported for UWP since Windows 8.


text:
Q: SQL SSRS updating row based on another row I have a problem which I've searched but I don't think I'm using the correct search keywords. Hoping someone help,
I have a table that looks like this,
Name        YEAR
Chicken     2015
Cow         2012
Lion        2014
Lion        **2016**
Tiger       2013
Tiger       2014
Tiger       **2016**

Result
Name        YEAR
Chicken     2015
Cow         2012

I want ALL the corresponding Name set to 'NULL' or preferably lines removed when the YEAR is 2016. So 2 lines of Lion and 3 lines of Tiger are removed because one of them has an YEAR = 2016.
Thank you!

A: You can do this with a subquery.  You don't want to see anything to do with names that have a year of 2016, so you just need this logic written into your where clause.
SELECT Name, Year
FROM table
WHERE Name not in (
    SELECT Name
    FROM table
    WHERE Year = '2016')

For your join situation:
SELECT Name, Year
FROM name_table nt
JOIN year_table yt on yt.id = nt.id
WHERE Name not in (
    SELECT Name
    FROM name_table nt
    JOIN year_table yt on yt.id = nt.id
    WHERE Year = '2016')


text:
Q: Adding an element in between of an array without affecting index traverse I need a effective solution (space + time) for the below problem,
Current Code
#define MAX_CHAR 26

char alphabet[MAX_CHAR] =
{
   'A',
   'B',
   'C',
   'D',
   'E',
   ...
   ...
   'Z'
}

print_first_alphabet_number (Str)
{
   for (i=0; i < MAX_CHAR; i++)
   {
     if (Str[0] == start_letter[i])
     {
        printf ("%d", i);
        return;
     }
   }
    return;
}

Sample IO
Apple -> 0
Door  -> 3
Zoo   -> 25

Modified Code
#define MAX_CHAR 27

char alphabet[MAX_CHAR] =
{
   'A',
   'B',
   '@',
   'C',
   'D',
   'E',
   ...
   ...
   'Z'
}

Expectation
print_first_alphabet_number should be modified to get the same result of sample IO.
Thanks in advance..
Edit
This is not the exact problem, this is just an example..

A: #define MAX_CHAR 27

char alphabet[MAX_CHAR] =
{
   'A',
   'B',
   '@',
   'C',
   'D',
   'E',
   ...
   ...
   'Z'
}

print_first_alphabet_number (Str)
{
   for (i=0; i < MAX_CHAR; i++)
   {
     if (Str[0] == start_letter[i])
     {
        printf ("%d", start_letter[i] - 'A');
        return;
     }
   }
    return;
}

Edit
Or as @nico-schertler suggested, if you just need to print the integer same as the alphabetical order or capital letters, you can achieve this without any character array and loop.
printf ("%d", Str[0] - 'A');

A: It's hard do understand what are you doing, you only want the index of alpha values?
#include <stdio.h>
#include <ctype.h>

#define MAX_CHAR 27

char alphabet[] =
{
   'A',
   'B',
   '@',
   'C',
   'D',
   'E',
   ...
   'Z'
};

void print_first_alphabet_number(char * Str)
{
    unsigned int ret = 0;
    for (unsigned int i=0; i < MAX_CHAR; i++)
    {
        if (Str[0] == alphabet[i])
        {
            printf("%d\n", ret);
            return;
        }
        if(isalpha(alphabet[i])) ret++;
    }
    return;
}

int main()
{
    print_first_alphabet_number("Door");
    return 0;
}

A: Assumption: you cannot distinguish inserted element by value, just by index, so this is the input. On more insertion, an array of inserted offsets should be organized.
#include <stdio.h>

int main()
{
    int idx;
    char abc[] = "AB@CDEFGHIJKLMNOPQRSTUVWXYZ";
    int skip = 2; /* index to be skipped */
    int num_skip = 0;
    int size = sizeof(abc)/sizeof(abc[0]);
    char ch;
    printf( "char [A-Z]: " );
    (void)scanf( "%c", &ch );
    for( idx = 0; idx < size; ++idx )
    {
        if( skip == idx ) { ++num_skip; }
        if( ch == abc[idx] )
        {
            printf( "%d\n", idx - num_skip );
            idx = size;
        }
    }
    return 0;
}


text:
Q: Weird issue with Google App Script when trying to automate timstamp I have been messing around to build a google worksheet with script. So basically, in this file whenever there is input on column 1 and 4, there will be a timestamp shown in the next cell. And when the input is removed, the timestamp is clear. Everything runs fine so far, however as some weird issue happen. If instead of input in column 1 & 4, I paste values to the range, no timestamp appear or if I paste with the timestamp, the pasted timestamp will disappear. I don't know what happened or if you are clear on what I'm trying to ask. Anyway, here the script I'm using:
function onEdit(e) {
  var s = SpreadsheetApp.getActiveSheet();
  var r = e.range;
  var nextCell = r.offset(0, 1);
  if( s.getName() == "Nhap" && (r.getColumn() == 1 || r.getColumn() == 3) ){
    if( nextCell.getValue() === '' && e.value !=null)
    {
       var time = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy HH:mm:ss");
       nextCell.setValue(time);
    }
     else{ nextCell.clearContent()}
   };

}

Thanks

A: e.value undefined when copy/pasting range:
When a range is copied, instead of manually inputting a value on a cell, the value parameter from the corresponding event object (e.value) is undefined. This is a known behaviour and it has been reported several times in Issue Tracker before:

*

*Installable onEdit function doesn't pass correct event.value when pasting cells into spreadsheet.

*Apps Script On Edit New Value is undefined when value is pasted in cell

*for onEdit trigger value is null if there was copy-paste of cell
While this is still under investigation, this doesn't seem to be intended behaviour. While the description for the value parameter says it will only be populated when the edited range is a single cell,

value: New cell value after the edit. Only available if the edited range is a single cell.

This behaviour also happens when the copied/pasted range is a single cell. See this related answer from Diego.
Issue:
Since e.value is undefined when pasting the range, the following condition is never true:
if( nextCell.getValue() === '' && e.value !=null)

So the code goes to:
else{ nextCell.clearContent()}

That is, the timestamp cell is cleared of content.
Solution:
You can avoid this by changing e.value to r.getValue() (see Range.getValue()), which will be populated even when the range is copy/pasted:
if( nextCell.getValue() === '' && r.getValue() !=null)

Another issue:
Also, in your current code, when the timestamp cell is not empty, this condition is always false, so the timestamp cell is cleared:
if( nextCell.getValue() === '' && e.value !=null)

This is disregarding whether the range is pasted or the cell is inputted manually. If you don't want this to happen, remove nextCell.getValue() === '' from your condition.
Edit:
If you want to remove timestamp when cell is emptied, check that cell value is not an empty string ("" !== null):
if (r.getValue() !="")


text:
Q: Reloading multiple application servers on deploy I have a setup where there are several application servers running php-fpm service and they all share a GlusterFS mount for the application code and other assets. In the current deploy process, the files get updated directly on the file server and many times to reflect changes the application service must be reloaded. To achieve that, the deployment script needs to get into every server and issue a reload command but with autoscaling, the number of servers is not the same at every moment.
Overall, I am working on sketching a couple of alternatives to solution this problem:

*

*First one, more artesanal and not perfect, as a proof of concept, would be a cron job that will run every X minutes on the application machines and look for a file that should contain a unique info like it's hostname or IP address. If it matches, it will not take action but if not, it will reload and write itself within the file. On the deployment procedure, the script would clear the file and all servers should get reloaded in the next cron run.

*Second, using a more sophisticated approach like a message queue or notification service where the running applications machine would subscribe to at boot time and wait for an order to reload. Deploy script would then publish a notification to get all servers aware it is time. A similar cron job from the previous method would then notice that and reload the app server.
Would any of that make sense? Is there any simpler or more standard way to trigger a broadcast for the applications servers running at a given moment in the deploy procedure without having to ssh to each and issuing the reload command? Any other advice you can provide or other suggestions?
Thanks!


text:
Q: JQUERY UI sortable для динамичных(новых) элементов Использую  JQUERY UI sortable.
У меня генерируются в html  новые элементы, которые должны обрабатываться этим плагином.
Но они не обрабатываются.
Я знаю, что дело в том, что они - это новые элементы. Обычно я обрабатываю таким образом
$('body').on('click', '.close', function(){ });
и все окей у меня ..
А вот как сделать, чтобы именно плагин реагировал, не пойму.
Вот конфиг плагина в html и там же ссылка на него:

  $(function() {
    $( "#sortable" ).sortable({
 cursor: "move",
 containment:'#sortable',
 revert:'true',
 handle:'.img_preview img'
 //documentation http://jquery.page2page.ru/index.php5/JQuery_UI
 });
  });

Может, кто подскажет, как можно реализовать .. ?

A: Два варианта:

*

*Попробовать $("#sortable").sortable("refresh" ); после добавления новых элементов.

*Обернуть сам sortable в функцию.
function doSort(){
    $("#soratable").sortable({
        ...
    });
}

и вызывать эту функцию doSort() после добавления нового контента.

A: $(function() {
        var sortable_opts = {
            cursor: "move",
            containment:'#sortable',
            revert:'true',
            //handle:'.img_preview img'
            //documentation http://jquery.page2page.ru/index.php5/JQuery_UI
        };
        $("#sortable").sortable(sortable_opts);
        $(document).on("click",'#sortable',function(e){
            e.preventDefault();
            $(this).sortable(sortable_opts);
        });
 });

JsFiddle


text:
Q: When wouldn't I use LASSO for model selection? Assume that you need to build a linear model to make predictions for new observations, and that there is uncertainty about which subset of variables should be included in the model. You are only interested in making predictions, there is no theory available to guide variable selection, and you aren't interested in drawing causal inferences.
In this scenario, when wouldn't you use LASSO? Everything I read makes it sound like the perfect tool in this situation. However, when I have a nice new hammer in my hand, all problems look like nails, so I would like some examples of reasonable scenarios where variable selection and avoiding overfit are important, but when LASSO is either entirely inappropriate, or unlikely to be the best option. There are other threads on why you should use LASSO; I want to know why I shouldn't.


text:
Q: How can I prevent all of my flex-items from resizing when I resize my window? I have tried using the following on my flex-container after clicking on my button to generate the content, but when I resize the windows, it keeps resizing my items. I want them to have a fixed width and height (ideally each item would be a square of 100x100 px)
flex-shrink: 0;
flex-grow: 0;

const sampleContent = ["stuff1", "stuff2", "stuff3", "stuff4", "stuff5"]
const button = document.querySelector(".content");
const rootElement = document.querySelector("#root");
const widthDiv = document.querySelector("#width-value");
const resultContainer = document.querySelector("#root");
const widthValue = window.getComputedStyle(resultContainer, null).getPropertyValue("width");
button.addEventListener("click", () => {
 sampleContent.forEach((content) => {
  const newDiv = document.createElement("div");
  console.log(newDiv);
  newDiv.textContent = content;
  newDiv.classList.add("result");
  rootElement.appendChild(newDiv);
  })
})
widthDiv.textContent = widthValue;
.result-container {
  display: flex;
  width: 60%;
  height: 200px;
  border: 1px black solid;
  flex-wrap: nowrap;
}
.container {
  display: flex;
  justify-content: center;
}
.result {
  width: 100px;
  height: 100px;
  border: 1px dotted pink;
  margin: 1%;
}

  <button class="content">
    Generate Content from API
  </button>

A: An initial setting on flex items is flex-shrink: 1. That means that items can shrink to avoid overflowing the container. Add flex-shrink: 0 to the items and you're all set.

const sampleContent = ["stuff1", "stuff2", "stuff3", "stuff4", "stuff5"]
const button = document.querySelector(".content");
const rootElement = document.querySelector("#root");
const widthDiv = document.querySelector("#width-value");
const resultContainer = document.querySelector("#root");
const widthValue = window.getComputedStyle(resultContainer, null).getPropertyValue("width");
button.addEventListener("click", () => {
  sampleContent.forEach((content) => {
    const newDiv = document.createElement("div");
    console.log(newDiv);
    newDiv.textContent = content;
    newDiv.classList.add("result");
    rootElement.appendChild(newDiv);
  })
})
widthDiv.textContent = widthValue;
.result-container {
  display: flex;
  width: 60%;
  height: 200px;
  border: 1px black solid;
  flex-wrap: nowrap;
}

.container {
  display: flex;
  justify-content: center;
}

.result {
  flex: 0 0 100px;
  /* fg: 0, fs: 0, fb: 100px */
  /* width: 100px; */
  height: 100px;
  border: 1px dotted pink;
  margin: 1%;
}

<button class="content">Generate Content from API</button>


text:
Q: Program that takes two lists containing numbers and outputs the duplicate/similar numbers from both lists I have written a program where a user inputs numbers in two different lists then the program outputs the numbers that are similar between the lists.
example bellow:
List 1: 7 2 0 4
List 2: 4 2 0 0
output: [4 , 2, 0 ]

Currently my code achieves that but for some reason if there is more then one duplicate number it only prints the first duplicate number instead of all instances of duplicate numbers.
List 1: 7 2 0 4
List 2: 4 2 0 0
Output: [4]

see bellow my code.
a = map(int, input('List 1: ').strip().split())  # e.g. "7 2 0 4"
b = map(int, input('List 2: ').strip().split())  # e.g. "4 2 0 0"
c = [el for el in b if el in a]
print('Output:',c) # e.g [4,2,0]

Any help would be appreciated.

A: The problem is that b is a map object which is consumed by the first iteration over its members. map does not create a list, but a generator-like entity that can only be iterated once.
If you call list on the map object, you will get a list that behaves as anticipated in the comprehension that makes c.
Try this:
a = list(map(int, input('List 1: ').strip().split()))  # e.g. "7 2 0 4")
b = list(map(int, input('List 2: ').strip().split()))  # e.g. "4 2 0 0")
c = [el for el in b if el in a]
print('Output:',c) # e.g [4,2,0]

However, we don't even need map, since we can call int in the comprehension itself. This makes much more Pythonic code, so unless you're working in a functional environment where iterators and generators are preferred:
a = input('List 1: ').strip().split()  # e.g. "7 2 0 4")
b = input('List 2: ').strip().split()  # e.g. "4 2 0 0")
c = [int(el) for el in b if el in a]

Your comprehension will give every member of b that is in a, which from your comments looks unintended. If you want only one instance, you can call set on b inside the comprehension.

A: List1 = list(map(int, input('List 1: ').strip().split())) #0,1,2,4,2,0
List2 = list(map(int, input('List 2: ').strip().split())) #0,4,2,5,0,3

print([a for a in List1 if a in List2])

Looking for all common element in both list using list comprehension, duplicates included
o/p---[0, 2, 4, 2, 0]
print([a for a in set(List1) if a in List2])

Remove the duplicate elements {set(List1)} then search for common element
o/p---[0,2,4]
print(set(List1).intersection(set(List2)))

Use SET intersection method to find common elements
o/p---[0,2,4]


text:
Q: Two letter abbreviated weekday name Running $ date produces Mo 15 Nov 2021 18:02:27 CET. Apparently the standard weekday name should have three letters, i.e. Mon in this case, and it is causing some problems with one software I'm using.
Is the behavior of date on my system normal? Should it print Mo or Mon. If the latter, how can I fix this?

edit:
The output of locale is:
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC=de_AT.UTF-8
LC_TIME=de_AT.UTF-8
LC_COLLATE="en_US.UTF-8"
LC_MONETARY=de_AT.UTF-8
LC_MESSAGES="en_US.UTF-8"
LC_PAPER=de_AT.UTF-8
LC_NAME=de_AT.UTF-8
LC_ADDRESS=de_AT.UTF-8
LC_TELEPHONE=de_AT.UTF-8
LC_MEASUREMENT=de_AT.UTF-8
LC_IDENTIFICATION=de_AT.UTF-8
LC_ALL=

And locale -k LC_TIME
abday="So;Mo;Di;Mi;Do;Fr;Sa"
day="Sonntag;Montag;Dienstag;Mittwoch;Donnerstag;Freitag;Samstag"
abmon="Jän;Feb;Mär;Apr;Mai;Jun;Jul;Aug;Sep;Okt;Nov;Dez"
mon="Jänner;Februar;März;April;Mai;Juni;Juli;August;September;Oktober;November;Dezember"
...

Ok, it seems to be some German/Austrian/Netherlands convention to use two letter weekday names.


text:
Q: c# how to write the code for: if data from database is the same as the data that was put in, do this So I have created this command to retrieve data from my database, the question now is how do I write the code that if the data that was put in is the same as the data in the database, it closes this form and opens a new one.
SqlDataAdapter command = new SqlDataAdapter("select * from tblLogin where Gebruikersnaam = @Gebruiker and GeheimeVraag = @GeheimeVraag and Antwoord = @Antwoord", con);
        DataTable dt = new DataTable();
        command.SelectCommand.Parameters.AddWithValue("@Gebruiker", txtGebruikersnaam.Text);
        command.SelectCommand.Parameters.AddWithValue("@GeheimeVraag", ddlGeheimeVraag.Text);
        command.SelectCommand.Parameters.AddWithValue("@Antwoord", txtAntwoord.Text);
        command.Fill(dt);

        if ()
        {
            this.Hide();
            FormLoginWW2 ss = new FormLoginWW2();
            ss.Show();
        }
        else
        {
            MessageBox.Show("Error");
        }

A: You can query and return a scalar value, and evaluate that:
SqlData
SqlCommand command = new SqlCommand("select 1 from tblLogin where Gebruikersnaam = @Gebruiker and GeheimeVraag = @GeheimeVraag and Antwoord = @Antwoord", con);
        command.SelectCommand.Parameters.AddWithValue("@Gebruiker", txtGebruikersnaam.Text);
        command.SelectCommand.Parameters.AddWithValue("@GeheimeVraag", ddlGeheimeVraag.Text);
        command.SelectCommand.Parameters.AddWithValue("@Antwoord", txtAntwoord.Text);

var value = command.ExecuteScalar();

if (Object.Equals(value, 1))
{
   //Success
}
else
{
   //Failure
}

The value of '1' will probably be evaluated as int, not bool, so you can cast in the query if you wanted it to expect a bool...  If it's not 1, meaning no results returned, `DBNull.Value' is returned instead.

A: I believe your query is looking up for a particular row in db table and if it exists you do something. You can do below
if(dt!=null)
{
  if(dt.Rows.Count>0)
  {
    //do your code
  }
}

Update:
One approach is as explained by Brian Mains
Another way of doing this would be like I explained. You can change you query to return first record(I'm assuming it will always be one record, since its a login)
 SqlDataAdapter command = new SqlDataAdapter("select TOP 1 * from tblLogin where Gebruikersnaam = @Gebruiker and GeheimeVraag = @GeheimeVraag and Antwoord = @Antwoord", con);
        DataTable dt = new DataTable();
        command.SelectCommand.Parameters.AddWithValue("@Gebruiker", txtGebruikersnaam.Text);
        command.SelectCommand.Parameters.AddWithValue("@GeheimeVraag", ddlGeheimeVraag.Text);
        command.SelectCommand.Parameters.AddWithValue("@Antwoord", txtAntwoord.Text);
        command.Fill(dt);

 if(dt!=null)
    {
      if(dt.Rows.Count>0)
       {
                this.Hide();
                FormLoginWW2 ss = new FormLoginWW2();
                ss.Show();
            }
     else
            {
                MessageBox.Show("Error");
            }
    }