text:
Q: Unable to navigate to a destination in other graph Using Android Navigation component in our code with SAMF (Single Activity, Multiple Fragments) approach for each functionality. Say each functionality will have own navigation graph intended to navigate between them.
e.g., the graphs are graph_a, graph_b, graph_c with its own fragments and designed to navigate as below:
  graph_a >> graph_b >> graph_c

and it works as expected.
Now, there are scenarios where a Fragment(frag_b) might need to navigate another one in different navigation graph like
  frag_b(graph_b) >> frag_c(graph_a)

I found the optimal solution, in this case, could be navigate using URI and tried below.
  val deepLink = Uri.parse("app://login/user-signup")
  findNavController().navigate(deepLink)

and added the following deeplink for to be called fragment in the respective graph.
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/graph_login_flow"
    app:startDestination="@id/userSignInFragment">
    ...
    <fragment
        android:id="@+id/userSignUpFragment"
        android:name="com.app.login.ui.UserSignUpFragment"
        android:label="EmailSignUpFragment"
        tools:layout="@layout/fragment_user_sign_up">
        <action
            android:id="@+id/action_userSiUpFrag_to_emailVeriFrag"
            app:destination="@id/emailVerificationFragment" />
        <deepLink
            android:id="@+id/deepLink_to_userSignUpFragment"
            app:uri="app://login/user-signup" />
    </fragment>
    <include app:graph="@navigation/graph_home_flow" />
    ...
</navigation>

As per Android documentation, can navigate to any destination regardless of graphs but my attempt results in the following error.
Is there any better approach?
java.lang.IllegalArgumentException: navigation destination with deepLink app://login/user-signup is unknown to this NavController
    at androidx.navigation.NavController.navigate(NavController.java:916)
    at androidx.navigation.NavController.navigate(NavController.java:894)
    at androidx.navigation.NavController.navigate(NavController.java:880)
    at com.app.home.profile.ProfileFragment.onViewCreated(ProfileFragment.kt:82)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:298)
    at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1232)
    at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2390)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2125)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2081)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1977)


text:
Q: Launch javascript code in a browser I am doing an add-in for Outlook (C#) I created a button in the Ribbon. When I click on the button I want to automatically open a browser with url and then launch a javascript javascript:Goto(); in the code behind. Is this possible?

A: If the javascript is just a part of the page opened, yes, that is possible. You can open the URL with Process.Start. It will open the default browser (so from there you have little control over the execution):
Process.Start(@"http://somewebsite.sample");

Another option is the use of the WebBrowser control in c#. You can execute custom javascript in it too. You can use WebBrowser.InvokeScript for that. You need to place that on a Form inside your application.
this.webBrowser.Navigate("http://somewebsite.sample")
this.webBrowser.InvokeScript("SomeGotoMethod", new object[] { "somevariable" });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change date format in multiple text files in powershell? Hello I have around 5000 text files (TXT) in one directory.Files are comma delimited. What I'm trying to do is to change date format (it is stored in first column of each file) from  M/d/yyyy to MM/dd/yyyy. There is around 1 milion lines in those 5000 files so I hope there is some efficient way to do it.I read somewhere that for handling such a big number of data a StreamWriter command is a way to go, but I'm not sure if it can be used in my case.
Thank you for any suggestion.
I'm using this script for deleting second and last row of multiple text files using StreamWriter. It is very fast and efficient. I hope that with some small modifications it can be used for changing date formats in first column. I have just 2 weeks experience with PS so this is quite a challenge for me.
dir *.txt | %{
$content = gc $_.FullName
$output = @($content | select -First 1 )
$output += $content[2..($content.count -2)]
$sw = New-Object System.IO.StreamWriter($_.FullName,$false)
$output | %{$sw.WriteLine($_)}
$sw.close()
}

A: You say your text files are comma delimited. Well, you could use Import-Csv -Path C:\file.txt. Then PowerShell makes each row into an object. Objects are easier/more accurate to manipulate than text. Objects might be "slower" but 5000 files/ 1M lines are nothing even for a cheap laptop. Not sure how PS would handle the 1st and last lines of your files, since I don't know the format.
Converting the dates are easy. If I give Get-Date a date string formatted like m/d/yyyy, I use the -UFormat parameter to format the date however I want. Get-Help Get-Date -Full
PS> Get-Date 2/8/2016 -UFormat "%m/%d/%Y"
02/08/2016


text:
Q: Magnolia - Cross field validation We have below requirement.
Field 1 : comboBoxField and it is mandatory.
Field 2:  comboBoxField
Case 1. If editor choose field 1 value is "value1", then field 2 is mandatory
Case 2: if editor choose Field  1 value is "value2", then filed 2 is optional.
How to do this validation either in form/field validation before commit action.
Or how do we validate in commit action.
Any lead will help me a lot. I am stuck in this issue for longtime.
I tried with cross-field, dynamic filed , switchable and composite field as suggested in documentation, but I got null pointer exceptions. If you know the solution please share code snippet also.

A: I also suffered with this type of validation. The problem is in the isolation of the fields. I couldn't find a way to validate one field depending on another field value.
Anyway I found a workaround solution. I aggregate two dependent fields with complex field and create a validator for it.
Here's my code for the Magnolia 5.7 and vaadin validator (it's deprecated 7th  version, nevertheless the logic will be the same with the 8th version).
public class CompanyRequiredFieldsValidator implements Validator {

    private final ConfiguredFieldValidatorDefinition definition;

    public CompanyRequiredFieldsValidator(ConfiguredFieldValidatorDefinition definition) {
        this.definition = definition;
    }

    @Override
    public void validate(Object value) throws InvalidValueException {
        Optional<String> companyName = getString(value, "companyName");
        if (companyName.isPresent()) {
            getString(value, "companyAddress")
                    .orElseThrow(() -> new InvalidValueException(definition.getErrorMessage()));
        }
    }

    private Optional<String> getString(Object value, String property) {
        return Optional.of(value)
                .filter(Item.class::isInstance).map(Item.class::cast)
                .map(_v -> _v.getItemProperty(property))
                .map(Property::getValue)
                .filter(String.class::isInstance).map(String.class::cast)
                .filter(StringUtils::isNotEmpty);
    }

}

For complex fields validated value has com.vaadin.v7.data.Item type, so it's possible to get all properties from it.
The only problem, that the error message does not highlight the inner field, only whole complex field.


text:
Q: rxjava with for each loop I am trying to get the data from local db by each content asyncrounous,but the issue is that I want to get the data by the order that I retrieve,at first the data for the first conent,than the second etc.,currently I am getting the data in wrong order every time I run the code ,how can I achieve this?
 for (Content content : contents) {
                scoreCardDisposable = AppManagers.getContentManager()
                        .getScoreCardsAndUpdate(content.getId())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(scoreCards -> {
                           ...
                        });
                compositeDisposable.add(scoreCardDisposable);

           }

A: To make an observable stream from a List<> you can use Observable.fromIterable operator:
compositeDisposable.add(Observable.fromIterable(contents)
            .flatMap(content -> {
                return AppManagers.getContentManager()
                        .getScoreCardsAndUpdate(content.getId());
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(scoreCards -> {
                ...
            }));

UPD:
You can use a zip operator to combine content with the getScoreCardsAndUpdate result in custom object:
class Result {
    private String content;
    private String result;

    public Result(String content, String result) {
        this.content = content;
        this.result = result;
    }

    public String getContent() {
        return content;
    }

    public String getResult() {
        return result;
    }
}

public Observable<String> getScoreCardsAndUpdate(String content) {
    return Observable.just("result = " + content);
}

@Test
public void test() {
    List<String> contents = Arrays.asList("1", "2", "3", "4");

    Observable.fromIterable(contents)
            .flatMap(content -> {
                return Observable.zip(Observable.just(content),
                        getScoreCardsAndUpdate(content), Result::new);
            })
            .subscribe(scoreCards -> {
                System.out.println("content = " + scoreCards.getContent() +
                        ", " + scoreCards.getResult());
            });
}

A: You will have to process all the items in a single thread. You can achieve this by adding a scheduler in rxjava2
.subscribeOn(Schedulers.single())

Your code should be
for (Content content : contents) {
            scoreCardDisposable = AppManagers.getContentManager()
                    .getScoreCardsAndUpdate(content.getId())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.single())
                    .subscribe(scoreCards -> {
                       ...
                    });
            compositeDisposable.add(scoreCardDisposable);

       }


text:
Q: this.xxxxx.subscribe is not a function I'm trying to subscribe to an Observable string but I do not understand the error message:

this.templateName.subscribe is not a function

My code :
templateName: Observable<string>;

this.store.select(fromRoot.getRequestEntitiesState).subscribe(data => this.requestDetail = data)

this.templateName = this.requestDetail.request.templateName;

this.subscriptions.push(this.templateName.subscribe(templateName => {
  this.store.dispatch(new requestActions.LoadTemplateAction(templateName))
}))

A: this.requestDetail.request.templateName

Should return an Observable.


text:
Q: when i wanna parse a html page, why xpath query return null? I wanna parse an HTML page, that has a next page button. button title is tt. I wanna get button id for next page number. my code is:
$dom = new \DOMDocument;

@$dom->loadHTML($response);

$xpath = new \DOMXpath($dom);

$ne = $xpath->query('//a[@class="btn chang-page" and @title="tt"]/@id');

   while ($ne->length > 0)

        {

        // go to next page and parse nodes in it.
        // $response=nextpage();

         $dom = new \DOMDocument;

         @$dom->loadHTML($response);

         $xpath = new \DOMXpath($dom);

         $ne = $xpath->query('//a[@class="btn chang-page" and @title="tt"]/@id');

    }

this code just works for page one and page two. for page 3 return null. why?


text:
Q: MANOVA with variables from different datasets This question was already asked on stats.stackexchange, but no one answered. Since I'm not sure which forum is the appropriate one, I post this here again with some data.
I have done experiments on various characteristics of tree bark and now want to compare in how far the five examined tree species differ in regards to the assessed parameters. So, it was suggested that I should use a MANOVA to analyse my data and it seems reasonable to me. My analysis is conducted in R.
However, unlike most examples I've found on how to do a MANOVA (i.e. here, here, here), my data stems from different measurements and from different individuals. Now, I've found only this thread discussing unequal sample sizes, but this targets only sample sizes within the explaining factor.
To illustrate a bit further, imagine I have per tree species...

*

*9 measurements of the bark roughness.

*4 measurements of the bark thickness,

*3 pH measurements,

*5 measurements of the water-holding capacity,

*5 measurements of the water retention.

Of course, I could do separate ANOVAs for each of these variables (and I already did), but I think there should be some advantages in a MANOVA, right?
My Question:
Would a MANOVA be appropriate for such kind of data? Can I just ignore my different variable sizes? Is there an alternative way to do this or rather an alternative statistic test? Does my small sample size matter?
My results so far:
In R, I just put all the variables into one data.frame and filled the missing values due to unequal sample size by NAs (that's why there is the nums column in my data.frame below). Then, I ran a MANOVA like this: pH + water content + thickness + roughness ~ tree species with the manova function.
Example Data:
manova_df = structure(list(abbr = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L), .Label = c("AS", "BU", "CL", "MB", "PR"
), class = "factor"), nums = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L), comb_rugosity = c(3.44, 2.29, 5.21, 1.45,
2.84, 4.25, 1.54, 2.97, 1.38, 2.45, 9.44, 0, 0.58, 7.71, 5.53,
0.84, 1.22, 1, 10.83, 15.77, 5.5, 8.49, 10.46, 9.16, 5.52, 6.55,
1.77, 10.68, 13.43, 20.8, 8.82, 18.09, 15.1, 15.41, 16.3, 13.2,
2.67, 0.95, 1.49, 2.7, 0, 0.92, 0.83, 0, 1.89), bark_mm = c(9.59,
4.17, 17.23, 8.49, 3.58, NA, NA, NA, NA, 8.06, 13.53, 6.33, 10.96,
12.14, NA, NA, NA, NA, 17.94, 7.33, 10.54, 14.68, 16.66, NA,
NA, NA, NA, 8.52, 8.72, 7.57, 11.89, 6.41, NA, NA, NA, NA, 2.59,
9, 3.26, 5.81, NA, NA, NA, NA, NA), pH = c(6.5, 7.33, 8.17, NA,
NA, NA, NA, NA, NA, 7.84, 3.71, 12.47, 4.39, NA, NA, NA, NA,
NA, 11.04, 6.22, 5.41, 4.29, NA, NA, NA, NA, NA, 9.26, 11.18,
6.3, NA, NA, NA, NA, NA, NA, 8.42, 7.75, 4.33, NA, NA, NA, NA,
NA, NA), whc = c(192, 251, 166, 170, 466, NA, NA, NA, NA, 308,
187, 595, 324, 364, NA, NA, NA, NA, 171, 406, 790, 292, 579,
NA, NA, NA, NA, 672, 251, 700, 245, 260, 485, 383, NA, NA, 325,
481, 338, 476, 968, NA, NA, NA, NA), ret = c(83, 90, 286, 309,
374, NA, NA, NA, NA, 109, 159, 98, 164, 636, NA, NA, NA, NA,
144, 234, 383, 178, 446, NA, NA, NA, NA, 275, 56, 178, 107, 125,
367, 137, NA, NA, 132, 120, 142, 147, 330, NA, NA, NA, NA)), row.names = c(NA,
-45L), class = c("tbl_df", "tbl", "data.frame"))

Which looks like this (where abbr is the tree species, nums is the number of the measurement per tree species and the rest are the tree parameters):
> manova_df
# A tibble: 45 x 7
   abbr   nums comb_rugosity bark_mm    pH   whc   ret
   <fct> <int>         <dbl>   <dbl> <dbl> <dbl> <dbl>
 1 AS        1          3.44    9.59  6.5    192    83
 2 AS        2          2.29    4.17  7.33   251    90
 3 AS        3          5.21   17.2   8.17   166   286
 4 AS        4          1.45    8.49 NA      170   309
 5 AS        5          2.84    3.58 NA      466   374
 6 AS        6          4.25   NA    NA       NA    NA
 7 AS        7          1.54   NA    NA       NA    NA
 8 AS        8          2.97   NA    NA       NA    NA
 9 AS        9          1.38   NA    NA       NA    NA
10 BU        1          2.45    8.06  7.84   308   109
# ... with 35 more rows

My analysis is pretty straightforward:
mano_mod = manova(cbind(pH, bark_mm, comb_rugosity, whc, ret) ~ abbr, data = manova_df)
> summary(mano_mod)
          Df Pillai approx F num Df den Df Pr(>F)
abbr       4 1.5708   1.4226     20     44 0.1628
Residuals 12

I did not include my real data here, but they follow the same structure. The given data are far from being significant, whereas my actual data are! My question is solely regarding the many NAs in my data and if the test is accurate.
(If anything is unclear, please ask.)


text:
Q: How to keep the same button style after being pressed? When I click one of the buttons (forgot your code?), it displays solid red colour and lead to a different activity. When I return to the previous activity, the button has changed to default style and is displaying orange colour when pressed. How do I retain the button's original style and state after being pressed for the first time?
Button State xml file:

<item android:state_pressed="true" >
    <shape android:shape="rectangle"  >
        <corners android:radius="3dip" />
        <stroke android:width="1dip" android:color="#000000" />
        <gradient android:angle="-90" android:startColor="#FF0D00" android:endColor="#FF0D00"  />
    </shape>
</item>
<item android:state_focused="true">
    <shape android:shape="rectangle">
        <corners android:radius="3dip" />
        <stroke android:width="1dip" android:color="#000000" />
        <solid android:color="#FF0D00"/>
    </shape>
</item>
<item >
    <shape android:shape="rectangle"  >
        <corners android:radius="3dip" />
        <stroke android:width="1dip" android:color="#000000" />
        <gradient android:angle="-90" android:startColor="#D8D8D8" android:endColor="#848484" />
    </shape>
</item>

Screenshots:


text:
Q: Retrieve info from firebase I need to retrieve specific info from Firebase Realtime Database to send push messages, but don't know how to do it, I need to get in String the device token from all the users, so tried to call Users, the should call user ids (this part is where I'm lost, don't know how to get this path), and then device token.
This is what I have :
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

    usersIDs = UsersRef.getKey().toString();

    UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                if (dataSnapshot.hasChild("device_token")) {
                    receiverUserDeviceToken = dataSnapshot.child("device_token").getValue().toString();
                }
            }
        }

        @Override
        public void onCancelled(@NotNull DatabaseError error) {

        }
    });

A: According to your last comment:

Correct, I need to get both values.

Please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = rootRef.child("Users");
usersRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot userSnapshot : task.getResult().getChildren()) {
                String deviceToken = userSnapshot.child("device_token").getValue(String.class);
                Log.d("TAG", deviceToken);
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be:
f4...XMY:APA...wr3
eff...8NT:APA...Bd7

Remember, to be able to get all the results from a DataSnapshot object, you have to iterate through the children using .getChildren().


text:
Q: make a page refresh automaticly on a .txt change so I've been trying to make a page on php request that plays youtube links
I used php and used this
<?php
$VID = $_GET['vid'];
echo $VID;
$file = fopen("Vid.txt","w");
fwrite($file,$VID);
?>

to make a $_get request to grab a youtube ID and write it on a .txt file
then I made a page to read the file and use it on a embed youtube link

<?php
$file = fopen ("Vid.txt","r");
$id = fread($file,filesize("Vid.txt"));
fclose($file);
echo $id;
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $id  . '?autoplay=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
?>

what I would like to know is how could I automaticaly reload the page when the .txt changes
P.S : I have very basic knowledge about php,html and javascript
thanks in advance


text:
Q: How to correct loop counters for maze algorithm? I have figured out how to move my character around the maze using the algorithm I have written, but the count is not figuring correctly. At the end of each row my character moves up and down several times until the count reaches the specified number to exit the loop, then the character moves along the next row down until it reaches the other side and repeats the moving up and down until the count reaches the specified number again. Can anyone help me find why my count keeps getting off? The algorithm and the maze class I am calling from is listed below.
public class P4 {

public static void main(String[] args) {

    // Create maze
    String fileName = args[3];
    Maze maze = new Maze(fileName);
    System.out.println("Maze name: " + fileName);

    // Get dimensions
    int mazeWidth = maze.getWidth();
    int mazeHeight = maze.getHeight();

    // Print maze size
    System.out.println("Maze width: " + mazeWidth);
    System.out.println("Maze height: " + mazeHeight);

    int r = 0;
    int c = 0;

    // Move commands
    while (true){

        for (c = 0; c <= mazeWidth; c++){

            if (maze.moveRight()){
                maze.isDone();
                c++;
            }

            if (maze.isDone() == true){
                System.exit(1);
            }

            if (maze.moveRight() == false && c != mazeWidth){
                maze.moveDown();
                maze.moveRight();
                maze.moveRight();
                maze.moveUp();
                c++;
            }
        }
        for (r = 0; r % 2 == 0; r++){
            maze.moveDown();
            maze.isDone();

            if (maze.isDone() == true){
                System.exit(1);
            }
        }
        for (c = mazeWidth; c >= 0; c--){
            if (maze.moveLeft()){
                c--;
                maze.isDone();
                System.out.println(c);
            }

            if (maze.isDone() == true){
                System.exit(1);
            }
            if (maze.moveLeft() == false && c != 0){
                maze.moveDown();
                maze.moveLeft();
                maze.moveLeft();
                maze.moveUp();
                c--;
            }
        }
        for (r = 1; r % 2 != 0; r++){
            maze.moveDown();
            maze.isDone();

            if (maze.isDone() == true){
                System.exit(1);
            }
        }

    }
}

}
public class Maze {

// Maze variables
private char mazeData[][];
private int mazeHeight, mazeWidth;
private int finalRow, finalCol;
int currRow;
private int currCol;
private int prevRow = -1;
private int prevCol = -1;

// User interface
private JFrame frame;
private JPanel panel;
private Image java, student, success, donotpass;
private ArrayList<JButton> buttons;

// Maze constructor
public Maze(String fileName) {

    // Read maze
    readMaze(fileName);

    // Graphics setup
    setupGraphics();
}

// Get height
public int getHeight() {
    return mazeHeight;
}

// Get width
public int getWidth() {
    return mazeWidth;
}

// Move right
public boolean moveRight() {

    // Legal move?
    if (currCol + 1 < mazeWidth) {

        // Do not pass?
        if (mazeData[currRow][currCol + 1] != 'D')
        {
            currCol++;
            redraw(true);
            return true;
        }
    }
    return false;
}

// Move left
public boolean moveLeft() {

    // Legal move?
    if (currCol - 1 >= 0) {

        // Do not pass?
        if (mazeData[currRow][currCol - 1] != 'D')
        {
            currCol--;
            redraw(true);
            return true;
        }
    }
    return false;
}

// Move up
public boolean moveUp() {

    // Legal move?
    if (currRow - 1 >= 0) {

        // Do not pass?
        if (mazeData[currRow - 1][currCol] != 'D')
        {
            currRow--;
            redraw(true);
            return true;
        }
    }
    return false;
}

// Move down
public boolean moveDown() {

    // Legal move?
    if (currRow + 1 < mazeHeight) {

        // Do not pass?
        if (mazeData[currRow + 1][currCol] != 'D')
        {
            currRow++;
            redraw(true);
            return true;
        }
    }
    return false;
}

public boolean isDone() {

    // Maze solved?
    if ((currRow == finalRow) && (currCol == finalCol))
        return true;
    else
        return false;
}

private void redraw(boolean print) {

    // Wait for awhile
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    if (print)
        System.out.println("Moved to row " + currRow + ", column " + currCol);

    // Compute index and remove icon
    int index = (prevRow * mazeWidth) + prevCol;
    if ((prevRow >= 0) && (prevCol >= 0)) {
        buttons.get(index).setIcon(null);
    }

    // Compute index and add icon
    index = (currRow * mazeWidth) + currCol;
    if ((currRow == finalRow) && (currCol == finalCol))
        buttons.get(index).setIcon(new ImageIcon(success));
    else
        buttons.get(index).setIcon(new ImageIcon(student));

    // Store previous location
    prevRow = currRow;
    prevCol = currCol;
}

// Set button
private void setButton(JButton button, int row, int col) {

    if (mazeData[row][col] == 'S') {
        button.setIcon(new ImageIcon(student));
        currRow = row;
        currCol = col;
    } else if (mazeData[row][col] == 'J') {
        button.setIcon(new ImageIcon(java));
        finalRow = row;
        finalCol = col;
    } else if (mazeData[row][col] == 'D') {
        button.setIcon(new ImageIcon(donotpass));
    }
}

// Read maze
private void readMaze(String filename) {
    try {

        // Open file
        Scanner scan = new Scanner(new File(filename));

        // Read numbers
        mazeHeight = scan.nextInt();
        mazeWidth = scan.nextInt();

        // Allocate maze
        mazeData = new char[mazeHeight][mazeWidth];

        // Read maze
        for (int row = 0; row < mazeHeight; row++) {

            // Read line
            String line = scan.next();
            for (int col = 0; col < mazeWidth; col++) {
                mazeData[row][col] = line.charAt(col);
            }
        }

        // Close file
        scan.close();

    } catch (IOException e) {
        System.out.println("Cannot read maze: " + filename);
        System.exit(0);
    }
}

// Setup graphics
private void setupGraphics() {

    // Create grid
    frame = new JFrame();
    panel = new JPanel();
    panel.setLayout(new GridLayout(mazeHeight, mazeWidth, 0, 0));
    frame.add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
    frame.add(panel, BorderLayout.CENTER);

    // Look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Configure window
    frame.setSize(mazeWidth * 100, mazeHeight * 100);
    frame.setTitle("Maze");
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setAlwaysOnTop(true);

    // Load and scale images
    ImageIcon icon0 = new ImageIcon("Java.jpg");
    Image image0 = icon0.getImage();
    java = image0.getScaledInstance(100, 100, Image.SCALE_DEFAULT);

    ImageIcon icon1 = new ImageIcon("Student.jpg");
    Image image1 = icon1.getImage();
    student = image1.getScaledInstance(100, 100, Image.SCALE_DEFAULT);

    ImageIcon icon2 = new ImageIcon("Success.jpg");
    Image image2 = icon2.getImage();
    success = image2.getScaledInstance(100, 100, Image.SCALE_DEFAULT);

    ImageIcon icon3 = new ImageIcon("DoNotPass.jpg");
    Image image3 = icon3.getImage();
    donotpass = image3.getScaledInstance(100, 100, Image.SCALE_DEFAULT);

    // Build panel of buttons
    buttons = new ArrayList<JButton>();

    for (int row = 0; row < mazeHeight; row++) {
        for (int col = 0; col < mazeWidth; col++) {

            // Initialize and add button
            JButton button = new JButton();
            Border border = new LineBorder(Color.darkGray, 4);
            button.setOpaque(true);
            button.setBackground(Color.gray);
            button.setBorder(border);
            setButton(button, row, col);
            panel.add(button);
            buttons.add(button);
        }
    }

    // Show window
    redraw(false);
    frame.setVisible(true);
}

}

A: One error I can see in your code is that you're incrementing your c counter more often than you should. You start with it managed by your for loop, which means that it will be incremented (or decremented, for the leftward moving version) at the end of each pass through the loop. However, you also increment it an additional time in two of your if statements. That means that c might increase by two or three on a single pass through the loop, which is probably not what you intend.
Furthermore, the count doesn't necessarily have anything obvious to do with the number of moves you make. The loop code will always increase it by one, even if you're repeatedly trying to move through an impassible wall.
I don't really understand what your algorithm is supposed to be, so I don't have any detailed advice for how to fix your code.
One suggestion I have though is that you probably don't ever want to be calling methods on your Maze class without paying attention to their return values. You have a bunch of places where you call isDone but ignore the return value, which doesn't make any sense. Similarly, you should always be checking the return values from your moveX calls, to see if the move was successful or not. Otherwise you may just blunder around a bunch, without your code having any clue where you are in the maze.


text:
Q: convert properties file in arabic to unicode I have a requirement where a client will supply properties file in arabic where i have to convert the file(arabic.properties) to unicode. The file contains more than 500 lines.please help me to write the code to convert "arabic character" to "unicode character".

A: Using command line go to Java folder, and write:
\Java\bin>native2ascii -encoding utf-8 Labels_ar.txt Labels_ar.properties

UPDATE
Not sure what exactly you mean by not proper, but try this scenario:
Open notepad and write something in Arabic: let's say:
MyLabel = تجربه1

Then save it as test.txt and make sure to choose UTF-8 from Encoding.
Now from the command line:
native2ascii -encoding utf-8 test.txt test_ar.properties

Now test_ar.properties contain:
MyLabel = \u062a\u062c\u0631\u0628\u06471

Notice, sometimes native2ascii might add \ufeff as the first character in the file. You will need to remove it manually if you found it.

A: I'm guessing that the client is supplying the file encoded in codepage 1256 (Windows Arabic). I'm further guessing that by Unicode you actually mean UTF-8 encoding. If that's correct, then the following Python 3 script would do this:
with open("arabic.properties", "r", encoding="cp1256") as infile:
    with open("utf8.properties", "w", encoding="utf-8") as outfile:
        outfile.write(infile.read())

A: Well, you first have to know the encoding of the file they're going to give you. "Arabic characters" may describe what individual graphemes you may encounter but, without the encoding, it'll be like trying to train a cat or nail jelly to a tree.
With any luck, they'll give you one of the Unicode encodings (UTF-8, UCS-2, etc) and the "conversion" will be relatively painless.


text:
Q: hive count(distinct) only one reducer it's troubling me for a long time.  I like to use hive aggregation with multiple distinct like below:
select count(case when pv=1 then 1 else null end), count(distinct case when pv=1 and uid>1 then uid else null end), count(distinct component), count(message) from log_table;

this will lead to only 1 reducer which make job very very a long time. Since most work are in reducer job.
it's not suitable to use subquery like below as there are several distinct columns.
 select count(1) from (select v from tbl group by v) t.

Any good idea to optimize this problem.  Only have to split it into several query and then join?
Thank you!

A: did you try something like this:
select
 sum(a.pv_cnt),
 count(a.uniq_uids),
 count(a.uniq_uids),
 sum(a.msg_cnt)
from
  (
   select
     case when pv=1 then 1 else 0 end  as pv_cnt,
     distinct ( case when pv=1 and uid>1 then uid ) as uniq_uids,
     component,
     count(message) msg_cnt;
   from
    log_table
  )a;


text:
Q: DataTables, DataSets, Entity Framework, LINQ & Lambda Expression for Financial Technical Analysis C# this is more of an architectural question more than a specific code problem as I've hit a major block in how I am going to proceed with this project.
I'm building a financial scanning software that filters stock picks on specific criteria, for example.  For example if out of 8000 stocks, its closing price today is above the SMA 100 and 10 days ago the closing price is below the SMA 100, then return this stock Symbol back to me.
However, note that the SMA (Simple Moving Average) is calculated with the last 100 days of data in the above example, but it could be that we could change the 100 days for lets say another value, 105 or 56 - could be anything.
In my Database I have a table definition called EODData with a few columns, here is the definition below;
EODData
sSymbol nvarchar(6)
mOpen money
mClose money
mHigh money
mLow money
Date datetime

The table will hold 3 years of End Of Day Data for the American Stock Exchange so that is approximately 6,264,000 rows, no problem for MS SQL 2008 R2.
Now, I'm currently using Entity Framework to retrieve data from my database, however what would be the best way to run or create my filter because the SMA must be calculated for each Symbol or underlying Stock Ticker each time a scan is performed because the 100 day variable can change.
Should I convert from Entity Objects to a DataSet for in memory filtering etc???
I've not worked with DataSets or DataTables much so I am looking for pointers.
Note that the SMA is just one of the filters, I have another algorithm that calculates the EMA (Exponential Moving Average, which is a much more complicated formula) and MACD (Moving Average Convergence Divergence).
Any opinions?

A: What about putting the calculations in the database?  You have your EODData table, which is great.  Create another table that is your SummaryData, something like:
SummaryData
stockSymbol varchar(6) -- don't need nvarchar, since AMSE doesn't have characters outside of normal English alphabet.
SMA decimal
MCDA decimal
EMA decimal

Then you can write some stored procedures that run on close of day and update this one table based on the data in your EODData table.  Or you could write a trigger so that each insert of the EODData table updates the summary data in your database.
One downside to this is that you're putting some business logic in the database.  Another downside is that you will be updating statistical data on a stock symbol that you might not need to do.  For example, if nobody ever wants to see what XYZZ did, then the calculation on it is pointless.
However, this second issue is mitigated by the fact that 1. you're running SPs on the server which MSSQL can optimize and 2. You can run these after hours when everyone is at home, so if it takes a little bit of time you're not affected. (To be honest, I'd assume if they're calculations like rolling averages, min/max etc, SQL won't be that slow.)
One upside is your queries should be wicked fast, because you could write
select stockSymbol from SummaryData where SMA > 10 you've already done the calculation.
Another upside is that the data will only change once per day (at the close of the business day) but you might be querying several times throughout the day.  For example, you want to run several different queries today for all the data up to and including yesterday.  If you run 10 queries, and your partner runs the same 10 queries, you've just done the same calculation over. (Essentially, write once, read many.)


text:
Q: Excel - VBA to split data into sheets without keeping entire range I have utilized some code created by Ron de Bruin (linked at the bottom of this question) for quite some time in order to split a large table into multiple sheets based on whenever the values change in column A.
I have a new project with similar needs however this code is unfortunately not sufficient as is for two main reasons:
1 - The final data that I need should have no header row, yet this code treats Row 1 as a header and adds it on each created sheet.
2 - The data that I am using starts with no unique identifier but instead, a numeric identifier for what should be each new sheet. I can create a unique identifier in column A, but then this unnecessary column of data will be copied, along with the necessary data, into each created sheet.
Here is what the raw table and data looks like.
Here is how we need the data in each individual sheet
I would greatly appreciate any assistance in finding a solution for my problem here as I am very much a novice with VBA.
Thank you
https://www.rondebruin.nl/win/s3/win006_4.htm
EDIT: Just for posterity, I am linking the clunky code that I came up with. It works which is I guess what counts. I was only able to get it to work by deleting data as it goes so that the range always begins at "A1".
Dim BOTTOM_VAL As Long

BOTTOM_VAL = Range("A2").Value

Do Until Range("A1") = 0

  If (Range("A" & (BOTTOM_VAL + 1)).Value = 1) Or (Range("A" & (BOTTOM_VAL + 1)).Value = 0) Then

   Sheets("Sheet1").Range("A1", "O" & BOTTOM_VAL).Select
   Selection.Cut
   Worksheets.Add After:=Sheets(Sheets.Count)
   Range("A1").Select
   ActiveSheet.Paste
   ActiveSheet.Name = Range("B1") & "-" & Range("C1")
   Worksheets("Sheet1").Activate
   Sheets("Sheet1").Range("A1", "O" & BOTTOM_VAL).EntireRow.Delete
   BOTTOM_VAL = Range("A2").Value

  Else

    ' In case the loop breaks
      If Range("A1").Value = 0 Then
        Exit Sub

      Else
        BOTTOM_VAL = (BOTTOM_VAL + 1)
      End If

  End If

Loop
Application.DisplayAlerts = False
Sheets("Sheet1").Delete
Application.DisplayAlerts = True

End Sub

A: If I'm not mistaken to get what you mean, maybe something like this ?
The code assumed that the id of the data is changed if the cell value in column A is 1.
Sub test()
Set rg = Range("A1", Range("A" & Rows.Count).End(xlUp))
For Each cell In rg
Range(cell, cell.Offset(0, 13)).Copy
    If cell.Value = 1 Then
        Set WSnew = Worksheets.Add(After:=Sheets(Sheets.Count))
            If WSnew.Range("A1").Value = "" Then _
                WSnew.Range("A1").PasteSpecial (xlValues)
    Else
        Set oStart = WSnew.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
        oStart.PasteSpecial (xlValues)
    End If
Next
End Sub

The process:

*

*The code take all the value in column A of an active sheet where the macro is run by the range ---> rg.

*then it loop to each cell in rg, copy the row of the cell from A to N

*check if the cell value is 1 then it will create a new worksheet and paste to cell A1 of the newly created sheet.

*if the cell value is not 1 then it will paste to the next available blank row of the newly created sheet.

I'm not sure though if this is what you mean.


text:
Q: sorting linked list simplest way I am trying to code very basic sorting method for linked lists. I am getting unhandled exception. What is the mistake i am making? Here is my code:-
   struct LinkedNode// structure for linked list
        {
            int data;
            struct LinkedNode *next;
        }*start = NULL;

following function creates a linked list
 void CreateLinkedList()
        {
        LinkedNode *newNode, *current;
        printf("enter 5 numbers to create linked list\n");
        for(int i=0; i<5; i++)
            {
            newNode = (struct LinkedNode *)malloc(sizeof(LinkedNode));
            scanf("%d", &newNode->data);
            newNode->next = NULL;
            if(start == NULL)
                {
                start = newNode;
                current = newNode;
                }
            else
                {
                current->next = newNode;
                current = newNode;
                }
           }
        }

following function is used for sorting the linked list nodes
 void SortLinkedList()
    {
    struct LinkedNode *node=NULL, *temp = NULL;
    int tempvar;//temp variable to store node data
    node = start;
    temp = node->next;//temp node to hold node data and next link
    while(node != NULL && node->next != NULL)
    {
        for(int j=0; j<5; j++)//value 5 because I am taking only 5 nodes
        {
            if(node->data > temp->data)//swap node data
            {
                tempvar = node->data;
                node->data = temp->data;
                temp->data = tempvar;
            }
            temp = temp->next;
        }
        node = node->next;
      }
    }

A: Try This code
void SortLinkedList()
    {
    struct LinkedNode *node=NULL, *temp = NULL;
    int tempvar;//temp variable to store node data
    node = start;
    //temp = node;//temp node to hold node data and next link
    while(node != NULL)
    {
        temp=node;
        while (temp->next !=NULL)//travel till the second last element
        {
           if(temp->data > temp->next->data)// compare the data of the nodes
            {
              tempvar = temp->data;
              temp->data = temp->next->data;// swap the data
              temp->next->data = tempvar;
            }
         temp = temp->next;    // move to the next element
        }
        node = node->next;    // move to the next node
    }
}

1 - outer while loop is use for the total number of pass that will require to sort the linked list..
2- In second while loop we are actually comparing the data of the nodes that we want to sort

A: Instead of implementing your own sort, you can just use qsort. Of course, qsort requires an array, but that is easy enough to create.
In this case, you know that the list has 5 members. But, if you didn't know, you could just count them.
int size_of_list = 0;
struct LinkedNode *p;

for (p = start; p != NULL; p = p->next) ++size_of_list;

if (size_of_list == 0) {
    // Nothing to do
    return;
}

Now you can create your array;
struct LinkedNode *arr[size_of_list + 1], **arrp = arr;
for (p = start; p != NULL; p = p->next) *arrp++ = p;
*arrp = NULL;

Then, use qsort on arr. There are lots of examples, but the trick is writing an appropriate comparison function.
int cmp_LinkedNode(const void *a, const void *b) {
    const struct LinkedNode * const *aa = a;
    const struct LinkedNode * const *bb = b;
    return ((*aa)->data > (*bb)->data) - ((*aa)->data < (*bb)->data);
}

//...
qsort(arr, size_of_list, sizeof(*arr), cmp_LinkedNode);

And then, rewire the list into the sorted order.
for (int i = 0; i < size_of_list; ++i) arr[i]->next = arr[i+1];
start = arr[0];

A: yeah sorting a linked list using nodes/links is a pretty hard job. Spend hours doing it myself but since i have done it why not help others..
What you need to do is simply find the minimum value in your list. Swap it with the head node and the recur for head->next.
The code for sort is only of 3 to 4 lines if you have FindMin() and Swap() functions made..
here is the complete code for sort(),swap()and findmin().
void sort(node **start)
{
    if (((*start)->next == NULL) || (*start == NULL))
    {
        return;
    }
    node *min = findmin(*start);
    swap(*start, min, start);
    sort(&((*start)->next));
}

void swap(node *p1, node *p2, node **start)
{
    node *p1pre = NULL;
    node *p1curr = *start;
    while (p1curr!=p1)
    {
        p1pre = p1curr;
        p1curr = p1curr->next;
    }
    node *p2pre = NULL;
    node *p2curr = *start;
    while (p2curr != p2)
    {
        p2pre = p2curr;
        p2curr = p2curr->next;
    }
    if (p1pre != NULL)
    {
        p1pre->next = p2curr;
    }
    else
    {
        *start = p2curr;
    }
    if (p2pre != NULL)
    {
        p2pre->next = p1curr;
    }
    else
    {
        *start = p1curr;
    }
    node *temp = p2curr->next;
    p2curr->next = p1curr->next;
    p1curr->next = temp;
}

node* findmin(node *start)
{
    int flag = 0;
    if (start == NULL)
    {
        cout << "list is empty" << endl;
    }
    else
    {
        node *curr = start->next;
        node *min = start;
        while (curr->next != NULL)
        {
            if (min->value > curr->value)
            {
                min = curr;
                flag++;
            }
            curr = curr->next;
        }
        if ((curr->next == NULL) && (min->value > curr->value))
        {
            min = curr;
            flag++;
        }
        if (flag > 0)
        {
            return min;
        }
    }
}


text:
Q: PHP SOAP Error Premature end of data in tag html line 1 Sample of the XML request and my code below:
XML
<GetInventory>
<ClientID>API_ClientID </ClientID>
<UserID>API_UserID </UserID>
<Password>API_Password </Password>
<SecurityKey>API_SecurityKey</SecurityKey>
<Item>
    <SKU>7003</SKU>
</Item>
<Item>
    <SKU>7046</SKU>
</Item></GetInventory>

PHP
$options = array(
    'exceptions' => 0,
    'trace' => 1
);

$client = new SoapClient($soap_url, $options);

$clie_info = array(
    'ClientID' => $client_id,
    'UserID' => $user_id,
    'Password' => $password,
    'SecurityKey' => $security_key,
    'Item' => array('SKU' => 'XX-XX-XX-XXXX-XXXX-10')
);

$result = $client->GetInventory($clie_info);

print_r($result);

Above is my simple request to a SOAP service.
In response I get:

Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://xxx.xxx.com/v4/sandbox/xxxxx' : Premature end of data in tag html line 1 in D:\xxx\xxxxx\xxxx\api_3linx.php on line 15

Line 15 being:
$client = new SoapClient($soap_url, $options);

My question is: am I doing something wrong, or should I point the finger on the other end - the SOAP service support?


text:
Q: Transactions in LexDb Im using LexDb for Win8.1 universal App, I have to insert data in more than one table.
I want to use save / insert statement in one transaction for data consistency, So it should save all data or save nothing in case of exception or failure. I didn't  find a way to apply transaction in Lex Db.
sume forums say db.BulkWrite() creates transaction but its not creating transaction in true sense. Any help will be appreciated.

A: According to this post: (http://blogs.u2u.be/diederik/post/2013/12/09/Using-LexDB-as-a-local-storage-in-a-Windows-8-Store-app.aspx), transactions are not supported yet in LexDb.


text:
Q: forcing checkbox selected I'm trying to find see if we can make a checkbox selected if we chose an option from the dropdown menu. Here's a mock-up code of what I'm trying to modify.

$('.stackoverflow').on('change', function() {
  $(this).parent().next().find('input:checkbox').attr("checked", true);
});

    <input type="checkbox" id="How" /> How

    <input type="checkbox" id="Do" /> do

    <input type="checkbox" id="I" /> I

    <input type="checkbox" id="Force" /> force

    <input type="checkbox" id="The" /> the

    <input type="checkbox" id="checkbox" /> checkbox
    <select class="stackoverflow">
      <option value="to">to</option>
      <option value="be">be</option>
      <option value="selected">selected</option>
      <option value="when">when</option>
      <option value="we">we</option>
      <option value="select">select</option>
      <option value="an">an</option>
      <option value="option">option</option>
    </select>

    <input type="checkbox" id="not this one" /> not this checkbox but the previous one

I'm trying to have the checkbox "checkbox" be selected if I do select an option from the dropdown menu. Is there an easy way to do this? When searching stackoverflow, the closest thing that I found was to have the next one be selected and not the current one. Thank you very much for any help at all.

A: Just reference the correct checkbox correctly?
In your case, you have this:
$(this).parent().next().find('input:checkbox').attr("checked", true);

*

*this refers to the select

*parent refers to

*next would then refer to

*and finally find('input:checkbox') would find: <input
type="checkbox" id="not this one" />
Since the checkbox you want is a child of the same parent element that the select is in, the next() method call is what's causing the problem.
So, you could write:
$(this).parent().find('input:checkbox').attr("checked", true);

But, there are many ways to access an element. If it has an id, that is the simplest and most efficient way. So you are better off writing:
$('#checkbox').prop("checked", true);

Also, use .prop instead of .attr as .attr fails when you manually uncheck the checkbox and then select an item from the drop down.

$('.stackoverflow').on('change', function() {
  $('#checkbox').prop("checked", true);
});

    <input type="checkbox" id="How" /> How

    <input type="checkbox" id="Do" /> do

    <input type="checkbox" id="I" /> I

    <input type="checkbox" id="Force" /> force

    <input type="checkbox" id="The" /> the

    <input type="checkbox" id="checkbox" /> checkbox
    <select class="stackoverflow">
      <option value="to">to</option>
      <option value="be">be</option>
      <option value="selected">selected</option>
      <option value="when">when</option>
      <option value="we">we</option>
      <option value="select">select</option>
      <option value="an">an</option>
      <option value="option">option</option>
    </select>

    <input type="checkbox" id="not this one" /> not this checkbox but the previous one

A: You have a couple of options to check the checkbox:
$(document).ready(function() {
   $(".stackoverflow").on("change", function() {
       //$("#checkbox").prop("checked", true);
       $(this).prev("input[type='checkbox']").prop("checked", true);
   })

})

Here is a fiddle of it working based on your example: https://jsfiddle.net/gz6mab4k/

A: Hurray, you are using the relative position of your dom elements to locate each other.  I assume that's because you're going to get rid of all the IDs and add this structure many times to your page.  So you have a small error in the javascript handler, as mentioned in a comment you break stuff by having .next(), which will force the handler to look for a checkbox in the div coming after the select's parent which is the one that contains checkbox id='not this one'.  So you want:
$('.stackoverflow').on('change', function() {
  $(this) // the select
    .parent() // its parent DIV
    .find('input:checkbox') // the only checkbox in the parent div
    .attr("checked", true);
});


text:
Q: How to Remove Underline from HyperLink? I am trying to create an email signature that has a website link. However, the link appear as underlined. I tried many options to remove the underline from the website link but failed. Any Idea to solve this?

    <title>Email Signature</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

            {firstName} {lastName}

            {title}

            T: {phone}

            M: {mobile}

            E: {email}

{company}

            {website}

A: This should do it:
{website}
more info on styling links in css can be found here: https://www.w3schools.com/css/css_link.asp

A: Use Text-decoration: none; you can use it in css and inline too.

/*a {text-decoration: none;}*/
<title>Email Signature</title>
<meta content="text/html; charset=utf-8"http-equiv="Content-Type">

            {firstName} {lastName}

            {title}

            T: {phone}

            M: {mobile}

            E: {email}

{company}

            {website}

A: Have you tried this? : text-decoration:none;

A: Add a style attribute to the anchor tag and add the text-decoration to none. Example:
style="text-decoration: none"

A: try this CSS style.
a,a:hover{text-decoration: none;}

A: Add inline CSS to the anchor tag
style="text-decoration: none;


text:
Q: grails 3.3.0: does it include bootstrap? When trying to figure out how to get bootstrap into grails 3.3.0, when the plugins supporting this are out of date/unsupported, I noticed that there is already a bootstrap entry in application.css:
*= require bootstrap
*= require grails
*= require main
*= require mobile
*= require_self

In bootsrap.css it says its version 3.3.6.
this seems to be an undocumented feature, and there are a lot of posts on how to get bootstrap into grails 3 which makes no sense if its already there, unless they are trying to figure out how to update the bootstrap version?
In order to see if bootstrap is working, I edited the default main.gsp and added:
<button type="button" class="btn btn-default btn-lg">
   Star
</button>

Unfortunately, what is rendered seems broken - where the glyph should be is a square box.
I have tried many other bootstrap examples, and they do not appear to work, i.e. there are not rendered correctly.  I dont know if this is because bootstrap is not working, or if in the bowels of the thousands of lines of CSS which grails produces by default everything is overridden.
Does anyone know of something I could put in main.gps which would show one way or the other if bootstrap is working?

A: It does only include the bootstrap stylesheet. If you want to use glyph icons, you need to download the glyph font separately.
This you also see in the bootstrap stylesheet, as the fontface refers to not existing lib.
@font-face {
  font-family: 'Glyphicons Halflings';

  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

I guess that the only included the bootstrap stylesheet, to style the starting "template" where the don't make use of glyph icons.
The complete package of Bootstrap look like this (http://getbootstrap.com/getting-started/#download):
bootstrap/
├── css/
│   ├── bootstrap.css
│   ├── bootstrap.css.map
│   ├── bootstrap.min.css
│   ├── bootstrap.min.css.map
│   ├── bootstrap-theme.css
│   ├── bootstrap-theme.css.map
│   ├── bootstrap-theme.min.css
│   └── bootstrap-theme.min.css.map
├── js/
│   ├── bootstrap.js
│   └── bootstrap.min.js
└── fonts/
    ├── glyphicons-halflings-regular.eot
    ├── glyphicons-halflings-regular.svg
    ├── glyphicons-halflings-regular.ttf
    ├── glyphicons-halflings-regular.woff
    └── glyphicons-halflings-regular.woff2


text:
Q: How to access Provided (Provider.of()) value inside showModalBottomSheet? I have a FloatingActionButton inside a widget tree which has a BlocProvider from flutter_bloc. Something like this:
BlocProvider(
  builder: (context) {
    SomeBloc someBloc = SomeBloc();
    someBloc.dispatch(SomeEvent());

    return someBloc;
  },
  child: Scaffold(
    body: ...
    floatingActionButton: FloatingActionButton(
      onPressed: _openFilterSchedule,
      child: Icon(Icons.filter_list),
    ),
  )
);

Which opens a modal bottom sheet:
void _openFilterSchedule() {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return TheBottomSheet();
      },
    );
  }

I am trying to access SomeBloc using BlocProvider.of<SomeBloc>(context) inside TheBottomSheet but I get the following error:
BlocProvider.of() called with a context that does not contain a Bloc of type SomeBloc.

I have tried to use the solution described in https://stackoverflow.com/a/56533611/2457045 but only works for BottomSheet and not ModalBottomSheet.

Note: This is not restricted to BlocProvider or flutter_bloc. Any Provider from the provider package has the same behaviour.
How can I access BlocProvider.of<SomeBloc>(context) inside the showModalBottomSheet?
In case it's not possible to do that, how to adapt https://stackoverflow.com/a/56533611/2457045 solution to Modal Bottom Sheet?

A: You need move Provider to top layer(MaterialApp)
According to picture, Dialog widget is under MaterialApp, so this is why you using wrong context

A: InheritedWidgets, and therefore Providers, are scoped to the widget tree. They cannot be accessed outside of that tree.
The thing is, using showDialog and similar functions, the dialog is located in a different widget tree – which may not have access to the desired provider.
It is therefore necessary to add the desired providers in that new widget tree:
void myShowDialog() {
  final myModel = Provider.of<MyModel>(context, listen: false);
  showDialog(
    context: context,
    builder: (_) {
      return Provider.value(value: myModel, child: SomeDialog());
    },
  );
}

A: Provider in showModalBottomSheet (Bottom-Sheet)
void myBottomSheet() {
  final myModel = Provider.of<MyModel>(context, listen: false);
  showModalBottomShee(
    context: context,
    builder: (_) {
      return ListenableProvider.value(
        value: myModel,
        child: Text(myModel.txtValue),
      );
    },
  );
}

A: wrap your whole child widget inside the consumer.
void myShowDialog() {
  showDialog(
    context: context,
    builder: Consumer<MyModel>(
        builder: (context, value, builder) {
        retuen widget();
      }
  );
}

A: You should split Scaffold widget and its children, to another StatefulWidget
From single Widget
class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      builder: (context) {
        SomeBloc someBloc = SomeBloc();
        someBloc.dispatch(SomeEvent());
        return someBloc;
      },
      child: Scaffold(
        body: ...
        floatingActionButton: FloatingActionButton(
          onPressed: _openFilterSchedule,
          child: Icon(Icons.filter_list),
        ),
      )
    );
  }
}

Splitted into these two widget
class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      builder: (context) {
        SomeBloc someBloc = SomeBloc();
        someBloc.dispatch(SomeEvent());
        return someBloc;
      },
      child: Screen(),
    );
  }
}

and ..
class Screen extends StatelessWidget {

  void _openFilterSchedule() {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return TheBottomSheet();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ...
      floatingActionButton: FloatingActionButton(
        onPressed: _openFilterSchedule,
        child: Icon(Icons.filter_list),
      ),
    );
  }
}

A: I found a solution, Just return your showModalBottomSheet with a StatefulBuilder and use the context of your modalsheet builder to pass to your provider. a snippet of my code below:
Future<Widget> showModal(int qty, Product product) async {
    return await showModalBottomSheet(
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext ctx) {
          return StatefulBuilder(builder: (ctx, state) {
             return Container(
                  child: RaisedButton(
                          onPressed: () {
                             Product prod = Product(product.id,
                                         product.sku, product.name, qty);
                             Provider.of<CartProvider>(ctx, listen:
                                        false).addCart(prod);}),);
    }
  }
);
}

A: TLDR: Make sure your import statement's casings match your project's folder casings.
I came across one other quirk while debugging this same error. I had several providers that were all working, including in showModalBottomSheets, however one was not working. After combing through the entire widget tree, without finding any discrepancies, I found that I had capitalized the first letter of a folder on one of the import statements of my problem-child notifier. I think this confused the compiler and caused it to throw the Could not find the correct Provider above this widget error.
After ensuring the import statement casing matched the folder name, my provider problems were resolved. Hopefully this will save someone a headache.

A: Not finding a clear explanation of adding multiple provided values, I thought I'd share here for reference.
   await showMobileModals(
    isDismissible: false,
    context: context,
    child: MultiProvider(
      providers: [
        Provider.value(
          value: provided_one,
        ),
        Provider.value(
          value: provided_two,
        ),
        Provider.value(
          value: provided_three,
        ),
      ],
      child: Container(),
    ),
  );

A: Faced the same issue while dealing with showModelBottomSheet, since it happens to work in a different (context)widget tree I had to level up my state to that of the app so that I could access my provider using the context.


text:
Q: JSPerf test case giving errors but works fine on codepen Can anybody clue me in as to why this JSPerf test case is giving me errors? I reviewed the code several times and I can't find any mistakes. I even the code in codepen and everything ran fine.
JSPerf


text:
Q: setLocation after window moved I made a drag'n'drop algorithm to let components be dragged inside the window.
It performs well, until I move the frame window...
If I move the window, the position of the component is then shifted from a distance equal to the distance I moved the frame when I click on it and when I drag it.
Anyone knows why ?
Code sample:
public void mousePressed(final MouseEvent e) {

    if(SwingUtilities.isLeftMouseButton(e)) {

        origin = panel.getLocationOnScreen();

        panel.setLocation(origin.x, origin.y-panel.getHeight()/2);

        view.add(panel, JLayeredPane.DRAG_LAYER);
    }

}

public void mouseDragged(MouseEvent e) {

   if(SwingUtilities.isLeftMouseButton(e)) {

       panel.setLocation(e.getLocationOnScreen().x - panel.getWidth()/2, e.getLocationOnScreen().y - panel.getHeight()/2);

   }

}

A: Assuming the mouse events are raised by the container in which the panel should be dragged, you should use relative coordinates only.
That is, use
public void mouseDragged(MouseEvent e) {
   if(SwingUtilities.isLeftMouseButton(e)) {
      panel.setLocation(e.getPoint().x - panel.getWidth()/2, e.getPoint().y - panel.getHeight()/2);
   }
}


text:
Q: How to remove tasks (TODO) from R.java I configure my task lists to be shown by some standard words (TODO, FIXme...).
Now I see some task in my project R.java.
It's an auto-generated file and I do not see any option to exclude this file from tasks:
    ...
    public static int fbrowse_item_text_color=0x7f070056;
    public static int header_color=0x7f07006d;
    /**  TODO: This is 40% alpha on the default accent color.
     */
    public static int highlighted_text_material_dark=0x7f070020;
    ...

It annoys me.
I don't want to see in tasks this 'dead' TODO.
Is there any way to exclude R.java files from the TODO lists?

A: Although it is not a good practice in general, you could remove these contents from the Android SDK code.  It looks like the comments are in $ANDROID_HOME/platforms/android-21/data/res/values/colors_material.xml

<!-- TODO: This is 40% alpha on the default accent color. -->
<color name="highlighted_text_material_dark">#6680cbc4</color>
<!-- TODO: This is 40% alpha on the default accent color. -->
<color name="highlighted_text_material_light">#66009688</color>

So if you remove these XML comments from the SDK code, they will then be omitted from the generated R.java code.
Again, it is not a good practice to edit Android SDK code, although in this case the removal of comments is safe (i.e. it wont hurt anything).


text:
Q: Filtrar con ComboBox y TextBox enc# SqlServer Tengo que filtrar los datos de un datagrid con un textview y un combo box.
Pero, ocurre lo siguiente: el combo inicializa en 0 por lo que no me capta el valor del primer item. Intente agregar un item manualmente para que el valor 0 sea "Seleccione" y los demás sean de la base de datos.
Error:
System.ArgumentException: 'No se puede modificar la colección Items cuando está establecida la propiedad DataSource.'

En el siguiente método intento formular la query de sql para que tome los parámetros (combobox y textbox) y realizar el filtro en el datagrid:
private void filtrarTituloYAEMP(int valor){
cmbTipoPago.Items.Add("Seleccione");
            if (txtTitulo.Text == null || txtTitulo.Text == ""){
                try{
                    llenaTitulo();
                }catch (SqlException ex){
                    MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else{
                try{
                    SqlConnection conexion = new SqlConnection();
                    conexion.ConnectionString = "acá mi conexión a la bd";
                    conexion.Open();
                    DataSet ds = new DataSet();

     string sSQL = "SELECT titulo FROM V_CuetaWeb, ArchivoElectronico_MedioPago where titulo LIKE @valor + '%' and AEMP_Id = @id";
                SqlCommand command = new SqlCommand(sSQL, conexion);
                command.Parameters.Add("@valor", SqlDbType.VarChar).Value = valor;
                command.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(cmbTipoPago.SelectedValue);
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(ds, "V_CuetaWeb");
                conexion.Close();
                dtgTitulo.DataSource = ds;
                dtgTitulo.DataMember = "V_CuetaWeb";
            }catch (SqlException exx){
                MessageBox.Show("Error: " + exx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

Claramente, así no funciona. Entonces, los problemas son:
1- Que el ComboBox tenga una opción extra('Seleccione') que tome el valor 0
2- Que el método filtre con el textbox y el combobox
¿Alguien tiene idea de como lograr arreglar esos detalles?

A: como bien lo dice la excepción no puedes agregarle items por medio de la propiedad cmbTipoPago.Items.Add("Seleccione"); ya que anteriormente fue llenado con un DataSource, puedes usar la propiedad SelectedItem, asi evitas tener que agregar el item seleccione, ya que esta propiedad volvedera el item seleccionado.
        if (cmbTipoPago.SelectedItem is null)
        {
            ///seleccione un item valido
        }
        else
        {
            command.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(cmbTipoPago.SelectedItem);
        }

En caso de que quieras agregar la opción seleccione podes traerlo desde la base de datos.
SELECT 'SELECCIONE'
UNION ALL
-- su sql

        if (cmbTipoPago.SelectedItem is null || cmbTipoPago.SelectedItem.ToString() == "SELECCIONE")
        {
            ///seleccione un item valido
        }
        else
        {
            command.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(cmbTipoPago.SelectedItem);
        }


text:
Q: Azure add application role assignments with Python I am trying to add a new application role to Azure AD users via Graph API using Python. But I face issue.
I follow the Microsoft docs: https://learn.microsoft.com/en-us/graph/api/user-post-approleassignments?view=graph-rest-1.0&tabs=http
the structure works properly when using Postman.
Below is the Python script:
import json, requests

def test():
    token={ACCESS_TOCKEN}
    data={"principalId":"ff868303-fbb7-4027-87a1-00b92013d343","resourceId":"4f162966-2c98-4439-b924-7730c40e98551","appRoleId":"827ee854-4907-4e96-b238-c861d846c450"}
    return requests.post('https://graph.microsoft.com/v1.0/Users/ff868303-fbb7-4027-87a1-00b92013d343/appRoleAssignments',
    headers={'Authorization': 'Bearer ' + token_request , 'Content-Type': "application/json"},
    data=data
    )

The error:
{'error': {'code': 'BadRequest', 'message': 'Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.', 'innerError': {'date': '2020-11-25T15:43:24', 'request-id':
'8301f593-cab8-4228-b053-c9d24139a85f', 'client-request-id': '8301f593-cab8-4228-b053-c9d24139a85f'}}}

A: Because you are not posting a json to the REST API. Use 'json' argument instead of 'data' of post method. Refer https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests. Should be:
import json, requests
from uuid import UUID

def test():
    token={ACCESS_TOCKEN}
    data={"principalId":UUID("ff868303-fbb7-4027-87a1-00b92013d343"),"resourceId":UUID("4f162966-2c98-4439-b924-7730c40e98551"),"appRoleId":UUID("827ee854-4907-4e96-b238-c861d846c450")}
    return requests.post('https://graph.microsoft.com/v1.0/Users/ff868303-fbb7-4027-87a1-00b92013d343/appRoleAssignments',
    headers={'Authorization': 'Bearer ' + token, 'Content-Type': "application/json"},
    json = data
    )

Or, you can also dump json from the dictionary and pass in the data argument. data = json.dumps(data).


text:
Q: How To Add Subitem in ListViewItem in WPF C# I want to import data From excel datasheet to listview in WPF.
I want to add item and subitem to listviewitem.
If in Windows Form code:
foreach(DataRow drow in dtblImport.Rows)
{
  ListViewItem lvi = new ListViewItem();
  lvi.DataContext = drow[0].ToString();

   foreach(DataColumn dcol in dtblImport.Column)
    {
      if(drow[dcol.Ordinal] != DBNull.Value){
      lvi.SubItem.Add(drow[dcol.Ordinal].ToString());}
      else {
      lvi.SubItem.Add("");}
    }
   ListView.Items.Add(lvi);

}

But how if i want do it in WPF? Thanks

A: Define this control in your XAML
<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
            <GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}" />
        </GridView>
    </ListView.View>
</ListView>

and then in the code-behind you can add new items to the List view by typing:
listView.Items.Add(new Item());

And the class Item contains the properties Name and Description.
If you want to change the columns shown, then change the XAML.
This is not a good approach, as here you aren't using MVVM, what you should do is bind the ListView ItemsSource property to a collection in your ViewModel, and then work over that collection.


text:
Q: How to mask sensetive data for particular requests (NLog) Some of my actions accept models like:
    public class PaymentRequest
    {
        public decimal Amount { get; set; }
        public bool? SaveCard { get; set; }
        public int? SmsCode { get; set; }
        public BankCardDetails Card { get; set; }
    }

    public class BankCardDetails
    {
        public string Number { get; set; }
        public string HolderName { get; set; }
        public string ExpiryDate { get; set; }
        public string ValidationCode { get; set; }
    }

And the action method looks like:
        [HttpPost]
        [Route("api/v1/payment/pay")]
        public Task<BankCardActionResponse> Pay([FromBody] PaymentRequest request)
        {
            if (request == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            return _paymentService.PayAsync(DataUserHelper.PhoneNumber, request);
        }

I use Nlog. I think it's clear this is a bad idea to log all this bank data. My log config file contained the following line:
<attribute name="user-requestBody" layout="${aspnet-request-posted-body}"/>

I logged the request. I decided to refactor that and planned the following strategy. Actions that contain sensitive data into their requests I will mark with an attribute like
 [RequestMethodFormatter(typeof(PaymentRequest))]

then take a look at my custom renderer:
    [LayoutRenderer("http-request")]
    public class NLogHttpRequestLayoutRenderer : AspNetRequestPostedBody
    {
        protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
        {
            base.DoAppend(builder, logEvent);

            var body = builder.ToString();

            // Get attribute of the called action.
            var type = ... // How can I get "PaymentRequest" from the [RequestMethodFormatter(typeof(PaymentRequest))]
            var res = MaskHelper.GetMaskedJsonString(body, type);

            // ... and so on
        }
    }

I think you understand the idea. I need the type from the method's RequestMethodFormatter attribute. Is it even possible to get it into the renderer? I need it because I'm going to deserialize request JSON into particular models (it's gonna be into the MaskHelper.GetMaskedJsonString), work with the models masking the data, serialize it back into JSON.
So, did I choose a wrong approach? Or it's possible to get the type from the attribute into the renderer?

A: After some research, I ended up with the following solution:

namespace ConsoleApp7
{
    internal class Program
    {
        private static void Main()
        {
            var sourceJson = GetSourceJson();
            var userInfo = JsonConvert.DeserializeObject(sourceJson, typeof(User));

            Console.WriteLine("----- Serialize without Resolver-----");
            Console.WriteLine(JsonConvert.SerializeObject(userInfo));

            Console.WriteLine("----- Serialize with Resolver-----");
            Console.WriteLine(JsonConvert.SerializeObject(userInfo, new JsonSerializerSettings
            {
                ContractResolver = new MaskPropertyResolver()
            }));
        }

        private static string GetSourceJson()
        {
            var guid = Guid.Parse("3e92f0c4-55dc-474b-ae21-8b3dac1a0942");
            return JsonConvert.SerializeObject(new User
            {
                UserId = guid,
                Age = 19,
                Name = "John",
                BirthDate = new DateTime(1990, 5, 12),
                Hobbies = new[]
                {
                    new Hobby
                    {
                        Name = "Football",
                        Rating = 5,
                        DurationYears = 3,
                    },
                    new Hobby
                    {
                        Name = "Basketball",
                        Rating = 7,
                        DurationYears = 4,
                    }
                }
            });
        }
    }

    public class User
    {
        [MaskGuidValue]
        public Guid UserId { get; set; }
        [MaskStringValue("***")] public string Name { get; set; }
        public int Age { get; set; }
        [MaskDateTimeValue]
        public DateTime BirthDate { get; set; }

        public Hobby[] Hobbies { get; set; }
    }

    public class Hobby
    {
        [MaskStringValue("----")]
        public string Name { get; set; }

        [MaskIntValue(replacement: 11111)]
        public int Rating { get; set; }

        public int DurationYears { get; set; }
    }

    public class MaskPropertyResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var props = base.CreateProperties(type, memberSerialization);
            var allowedPropertyTypes = new Type[]
            {
                typeof(Guid),
                typeof(DateTime),
                typeof(string),
                typeof(int),
            };

            foreach (var prop in props.Where(p => allowedPropertyTypes.Contains(p.PropertyType)))
            {
                if (prop.UnderlyingName == null)
                    continue;

                var propertyInfo = type.GetProperty(prop.UnderlyingName);
                var attribute =
                    propertyInfo?.GetCustomAttributes().FirstOrDefault(x => x is IMaskAttribute) as IMaskAttribute;

                if (attribute == null)
                {
                    continue;
                }

                if (attribute.Type != propertyInfo.PropertyType)
                {
                    // Log this case, cause somebody used wrong attribute
                    continue;
                }

                prop.ValueProvider = new MaskValueProvider(propertyInfo, attribute.Replacement, attribute.Type);
            }

            return props;
        }

        private class MaskValueProvider : IValueProvider
        {
            private readonly PropertyInfo _targetProperty;
            private readonly object _replacement;
            private readonly Type _type;

            public MaskValueProvider(PropertyInfo targetProperty, object replacement, Type type)
            {
                _targetProperty = targetProperty;
                _replacement = replacement;
                _type = type;
            }

            public object GetValue(object target)
            {
                return _replacement;
            }

            public void SetValue(object target, object value)
            {
                _targetProperty.SetValue(target, value);
            }
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class MaskStringValueAttribute : Attribute, IMaskAttribute
    {
        public Type Type => typeof(string);
        public object Replacement { get; }

        public MaskStringValueAttribute(string replacement)
        {
            Replacement = replacement;
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class MaskIntValueAttribute : Attribute, IMaskAttribute
    {
        public object Replacement { get; }
        public Type Type => typeof(int);

        public MaskIntValueAttribute(int replacement)
        {
            Replacement = replacement;
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class MaskGuidValueAttribute : Attribute, IMaskAttribute
    {
        public Type Type => typeof(Guid);
        public object Replacement => Guid.Empty;
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class MaskDateTimeValueAttribute : Attribute, IMaskAttribute
    {
        public Type Type => typeof(DateTime);
        public object Replacement => new DateTime(1970, 1, 1);
    }

    public interface IMaskAttribute
    {
        Type Type { get; }
        object Replacement { get; }
    }
}

I hope somebody will find it helpful.

A: You can try nuget package https://www.nuget.org/packages/Slin.Masking and https://www.nuget.org/packages/Slin.Masking.NLog.
It can easily be integrated with DotNet projects with slight changes, and you can define your rules for it. But the document needs some improvement.
As a suggestion, you can use two files:

*

*masking.json (can be a generic one, that shared across all projects)

*masking.custom.json (can be used with particular rules for specific projects)


text:
Q: How to call dialog inside botframework v4 in net-core? I finally migrated a bot from v3 to v4 and it is working. It wouldn't be possible with out this community. Thank you all!
Now I am trying to include dialog in my bot. I've read documentation and have studied samples in github (botframework v4 repository), in this case all samples always start with dialog.
I don't need to start with dialogs because not all messages from the users require dialog. The most of messages from users call Luis and it is enough to unique response.
The issue is:
In some cases, my logic identify that user message requires more details, then I need to start a dialog to ask for more detail. I don't know how to start the dialog after user has sent several messages that doesn't require dialogs in the same session.
Thank you for ever help me!

A: You don't need to use Dialog to process single turn responses. In your case you can process the user input in OnMessageActivityAsync from your ActivityHandler, run against Luis, then use SendActivityAsync to send response back directly for simple intents, or run dialog.RunAsync to start a dialog when needed.
Your simple intents don't have a state, so there is nothing you need to worry about "previous messages".
However, I personally would suggest you start with a parent dialog which handles intent identification and intent processing. By doing that your intent identification/processing logic can be moved out of the ActivityHandler and it's easier to add things like authentication.
This does require a bit of code though. I tried to simplify this kind of situation in one of my projects so that bot developers can focus on their business logic. I shared the code on git hub with some sample. If you are interested you can check it out.


text:
Q: compensating the delay caused by hardware when logging tick data Sorry if it is too broad.
I dedicated a server for logging data that is being gathered from various sensors (temperature, wind direction ...). In my script, I set to log data (saving into a PostgreSQL database) every second. But when I investigate the data, I notice that sometimes 1 second is missing; for example:
2019-10-02 18:23:55,0.32342,67.587
2019-10-02 18:23:57,0.32341,67.582
2019-10-02 18:23:58,0.32340,67.583
2019-10-02 18:23:59,0.32341,67.582

Later on I found out that, the delay is not because of delay in reading sensors data but the hardware of the server itself; For example a burst of SSD activity, has caused the delay in execution of script.
Is there any solution or strategy for avoiding or compensating this scenario?


text:
Q: Having problems with a expanding Java Array I am currently doing an Array in Java that requires for the user to input a number which leads to an expanding array without the use of a conditional loop like if...else or switch. For example:
If user entered 2:
Output : 2 2 2
2 1 2
2 2 2
or if user entered 3:
Output: 3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
This is what I have gotten so far but it breaks the rule of no conditional if...else.
import java.util.*;

public class Test2
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        int choice;
        String space= " ";
        System.out.println("Please Enter an input : ");
        choice=input.nextInt();
        int adapt[];
        int num=choice;
        int increment=choice-1;

        if(choice==2)
        {
            for(int i=0; i<=choice; i++)
            {
                for(int j=0; j<choice-increment; j++)
                {
                    System.out.print(space + (choice) + space);
                }

                for(int j=choice-increment; j<choice; j++)
                {
                    if(i==choice-increment)
                    {
                        System.out.print(space + (choice-increment) + space);
                    }
                    else
                    System.out.print(space + (choice) + space);
                }

                for(int j=choice-increment; j<choice; j++)
                {
                    System.out.print(space + (choice) + space);
                }
                System.out.println();
            }
        }
    }
}

A: The phrasing of the question is confusing. Inspecting your code it looks like you are trying to draw a square grid of integers, where the digits increment radially from the central digit (1) in the middle of the grid. This is a typical programming question which is designed to teach you about loops and indices. Thus your question is really not Java related, however I have given you a working solution in Java below.
Conditional statements are not necessary to solve this problem. The only language construct required is a for loop, specifically a double-nested for loop since this is a two-dimensional problem.
public class Grid {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Please Enter an input : ");
    final int p = input.nextInt();
    // square grid with side length 2p + 1
    final int[][] grid = initGrid(2 * p + 1);
    fillGrid(grid, p);
    printGrid(grid);
  }

  private static int[][] initGrid(int size) {
    // 2-d int array
    int[][] grid = new int[size][];
    for (int i = 0; i < size; i++) {
      grid[i] = new int[size];
    }
    return grid;
  }

  private static void fillGrid(int[][] grid, int p) {
    for (int row = 0; row < grid.length; row++) {
      for (int col = 0; col < grid[row].length; col++) {
        grid[row][col] = calculateValue(row, col, p);
      }
    }
  }

  private static int calculateValue(int row, int col, int centre) {
    // the algorithm for calculating the value of the cell
    int dx = Math.abs(row - centre);
    int dy = Math.abs(col - centre);
    return 1 + Math.max(dx, dy);
  }

  private static void printGrid(int[][] grid) {
    for (final int[] row : grid) {
      for (int cell : row) {
        System.out.print(String.format(" %2d ", cell));
      }
      System.out.println();
    }
  }
}


text:
Q: Skype sound not working and crashes while in call I am using Ubuntu 12.10 but this same problem happened when I was running 12.04.
Whenever I call someone or I get called and pick up, I hear nothing and they cant hear me. After a few seconds skype just crashes and the same problem persists again. What can I do to fix this?

A: I had similar issues once, with the Skype version found on the official website.
If you also downloaded your version there, then you might try to use the Skype version found in the Canonical Partner repository instead, which is optimized for Ubuntu (and especially: pulseaudio). To get this version, first uninstall your current Skype installation and then follow this guide:
https://help.ubuntu.com/community/Skype#Installing_Skype

A: A recent update to the pulseaudio package included with Ubuntu 13.04 (Raring Ringtail) and Kubuntu 13.04 may be causing some users to experience a persistent background noise, or hum. It appears that this particular bug will affect VLC, Skype, and possibly other applications which emit audio. This problem is primarily affecting Intel-HDA (high definition audio) chipsets and ALSA sound drivers in regards to "glitch-free" PA (pulse audio).
Modify the following line in /etc/pulse/default.pa:
Change load-module module-udev-detect to load-module module-udev-detect tsched=0
Source and Complete Guide: UbuntuLinuxGuide.com


text:
Q: Creating a Title Page Activity Got a question on some android manifest and activity coordination. I have created an app that goes straight to the main activity, from which the user can interact with the app. I want to create an activity that displays a simple title of the app (maybe with a pic, but that's later...), then after a few second delay switches into the main activity. Here's what I have so far...
TitleActivity:
public class TitleActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_title);
    try {
        Thread.sleep(3000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    Intent intent = new Intent(this,MainActivity.class);
    startActivity(intent);
}
...

Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="khandy.application.convertible"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="khandy.application.convertible.TitleActivity"
        android:label="@string/title_activity_title" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="khandy.application.convertible.MainActivity"
        android:label="@string/app_name" >
    </activity>
...

What happens on startup is that none of my views/widgets show on the title_activity while the 3 second delay happens, then it switches into the main activity. Then when I press the android back button i retreat back into the title activity, which runs with the views/widgets. I'm fairly sure that the views/widgets not appearing has something to do with my very coarse multithreading...
So, my questions are:

*

*How do I get my views/widgets to appear when the title activity
is first opened?

*How can I set the main activity to simply exit the app when the
back button is pressed? That is, how can I use the back button in
the main activity to return to the android home screen?

Thanks!

A: you want a SplashScreen I think:
public class TitleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_title);

       new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {

                 Intent intent = new Intent(TitleActivity.this,MainActivity.class);
                 TitleActivity.this.startActivity(intent);
                 TitleActivity.this.finish();
            }
        }, 3000);

    }
}

A: finish titleactivity after mainactivity launch, this solves question 2. use
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
finish();

for question 1, use following code
public class SplashScreen extends Activity{

private SplashHandler mSplashHandler = new SplashHandler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash);

    mSplashHandler.sendEmptyMessageDelayed(SplashHandler.TIMER_EXPIRED, 5);
}

class SplashHandler extends Handler {
    static final int TIMER_EXPIRED = 100;
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case TIMER_EXPIRED:
            Intent in = new Intent(SplashScreen.this, nextActivity.class);
            startActivity(in);
            finish();
            break;

        default:
            break;
        }
    }
}

@Override
protected void onDestroy() {
    mSplashHandler = null;
    super.onDestroy();
}
}


text:
Q: Kivy installation in Anaconda3 Python 3.5.4 Ubuntu 16.04 Fails First I activated my conda environment using:
source activate building
Approaches Tried:
Prerequisites were installed following this https://kivy.org/docs/installation/installation-linux.html#ubuntu-example

*

*Installing using pip:

*

*pip install cython==0.25.2

*pip install kivy

*Result: FAIL

*

*Log: https://pastebin.com/m9zu390R

*gist:
ld: cannot find -lSDL2
ld: cannot find -lSDL2_ttf
ld: cannot find -lSDL2_image
ld: cannot find -lSDL2_mixer
ld: cannot find -lSDL2_ttf
ld: cannot find -lSDL2_image
ld: cannot find -lSDL2_mixer
ld: cannot find -lSDL2

*Installing using source:

*

*git clone https://github.com/kivy/kivy.git && cd kivy

*git checkout stable

*make

*Result: FAIL

*

*Log: https://pastebin.com/tjuYWrJ7

*gist: ld: cannot find -lGL
I did found kivy packages on Anaconda cloud, but they were for python2.


text:
Q: iPhone 4S video showing as 568 x 320 pixels resolution I was under the impression that the iPhone 4S recorded video at 1080p by default (using the native camera app). But when I send a video to myself via email and look at the video properties it is 568 x 320 pixels resolution. I wonder if this has to do with some compression given that it is being "shared" by email.
In that case, how do I extract the video without losing its pixel resolution?
Using iOS 7.

A: The issue relates to the fact that the video is being sent by email and the iPhone will compress the video for this purpose. It is not related to an email server capacity for attachments.
Reference here:
http://www.ilounge.com/index.php/articles/comments/transferring-videos-from-iphone-4s-to-computer
In order for video to be transferred at full resolution, the iPhone needs to be connected to a computer via USB. This will allow transfer of the entire file, for example using iPhoto.
When transferring a video file by email, a progress bar indicating compression is seen at the moment of transmittal, which measn the file is being compressed in resolution although it remains at full resolution within the phone until it is deleted.
In addition it is recommended to unlock the phone (if using a passcode) before connecting, to have access to this read/write functionality.


text:
Q: What is the difference between ManagementObject and ManagementBaseObject When i Compiled the following both codes it gives same result (I think so).
//ManagementObject :
SelectQuery query = new SelectQuery("Win32_Environment");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
  Console.WriteLine("Variable : {0}, Value = {1}",envVar["Name"], envVar["VariableValue"]);

//ManagementBaseObject :
SelectQuery query = new SelectQuery("Win32_Environment");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementBaseObject envVar in searcher.Get())
  Console.WriteLine("Variable : {0}, Value = {1}",envVar["Name"], envVar["VariableValue"]);

what is the difference between both code execution...?

A: In this particular case, there is no difference.
The ManagementObjectSearcher.Get() method returns a ManagementObjectCollection which is a collection of  ManagementBaseObject. This means that the collection can contain instances of type ManagementBaseObject or of any type that is descended from ManagementBaseObject.
However, the ManagementBaseObject is designed as a base class, which means that in reality, it won't be instantiated, but instead, it's descended classes will be instantiated. Note that this is a just a convention, and it is not enforced by the language or framework.
Additionally, since the only class in the framework that (directly) inherits the ManagementBaseObject is ManagementObject, the Get() effectively returns a collection of ManagementObject instances. Note that this is just the current situation, and nothing prevents the creation of additional ManagementBaseObject inheritors.
So, with all mentioned caveats, that means, that if you use only properties defined in the base class (and not overriden) you could iterate either way, and the code will behave exactly the same. In your code you use only the indexer, which is indeed defined, and not overriden, in the ManagementBaseObject class.
If you want an example of code that will fail for one loop, and work in the other, you could try any of the properties defined on ManagementObject, like, for example, Path:
foreach (ManagementObject envVar in searcher.Get())
  Console.WriteLine("Path : {0}, Value = {1}",envVar.Path.Path); //works

foreach (ManagementBaseObject envVar in searcher.Get())
  Console.WriteLine("Path : {0}, Value = {1}",envVar.Path.Path); //compile error

A: You should preferably use ManagementBaseObject here. The Get() method returns a (non-generic) ManagementObjectCollection which contains ManagementBaseObject-derived types, including ManagementObject and ManagementClass.
The first version may work for your particular query, but in general you might get an invalid cast exception.
If you only need to consider objects of type ManagementObject you might consider the following version:
var query = new SelectQuery("Win32_Environment");
var searcher = new ManagementObjectSearcher(query);
foreach (var envVar in searcher.Get().OfType<ManagementObject>())
{
    Console.WriteLine("Variable: {0}, Value = {1}",
        envVar["Name"], envVar["VariableValue"]);
}


text:
Q: Load only IDs of ManyToOne relationship I am having performance issues using hibernate. I have the following:
@Data
@Entity
@Table(name="\"Order_product\"")
public class OrderProduct {
    @Id
    @SequenceGenerator(name="Order_product_id_seq",
            sequenceName="Order_product_id_seq",
            allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator="Order_product_id_seq")
    private long id;
    @ManyToOne
    @NotNull
    private Product product;
    @ManyToOne
    @NotNull
    private ProductPrice price;
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @NotNull
    private Order order;
}

Now, whenever I am trying to execute:
List<OrderProduct> findByOrderId(@Param(value = "order") Long orderId);

Hibernate will load whole Order for each OrderProduct. How can I disable this, so that only ID of the Order will load?

A: You are already on a good track as the association is lazy, so Hibernate will make a proxy of Order in the order field.
However, the proxy instance is initialized as soon as you call any of its methods. Take a look at this question about how to disable proxy initialization when you need only id (foreign key pointing to the associated entity in your case). Of course, make sure not to invoke other methods on the proxy.
Alternatively, you could map the foreign key column explicitly and use it instead of accessing the associated entity (it has to be neither insertable nor updatable because the column is already mapped in the association):
@Column(name = "order_id", insertable = false, updatable = false)
private long orderId;