text:
Q: Error 'mat-dialog-content' is not a known element I am trying to create a login form using angular-material. I am using @angular/material": "^7.3.0.
In app.module.ts i have imported the following and placed them in the imports array as well,
import {
  MatToolbarModule, MatFormFieldModule, MatInputModule,
  MatOptionModule, MatSelectModule, MatIconModule,
  MatButtonModule, MatCardModule, MatTableModule,
  MatDividerModule, MatSnackBarModule
} from '@angular/material';

In message.components.ts i have the following
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { Component, OnInit, Inject, Injectable } from '@angular/core';

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.css']
})

export class MessageComponent implements OnInit {
  constructor(private dialogRef: MatDialogRef<MessageComponent>,
               @Inject(MAT_DIALOG_DATA) public data: any) {
          }
          public closeMe() {
            this.dialogRef.close();
          }
          ngOnInit() {
          }
        }

In my template message.component.html i have,

Message

<mat-dialog-content> </mat-dialog-content>
<mat-dialog-actions>
  <button mat-raised-button (click)="closeMe()">Close</button>
</mat-dialog-actions>

I am getting the errors for mat-dialog-actions & mat-dialog-content,
'mat-dialog-content' is not a known element:
'mat-dialog-actions' is not a known element:

As per the documentation angular-material both directives are available. What could be wrong in the code ? Thank you in advance.

A: First,
You need to make sure that imported the MatDialogModule into your AppModule.
You can do both:

Or
<mat-dialog-content></mat-dialog-content>
<mat-dialog-actions></mat-dialog-actions>

If you look at the source of components/src/material/dialog/dialog-module.ts in Angular Materials git repo, it exports the following directives.
import {
  MatDialogActions,
  MatDialogClose,
  MatDialogContent,
  MatDialogTitle,
} from './dialog-content-directives';

exports: [
    ...
    MatDialogClose,
    MatDialogTitle,
    MatDialogContent,
    MatDialogActions,
    ...
  ]

and with following similar declaration for each directive in ~/dialog-content-directives.ts
@Directive({
  selector: `[mat-dialog-content], mat-dialog-content, [matDialogContent]`,
  host: {'class': 'mat-dialog-content'}
})
export class MatDialogContent {}

If the problem persists, then try the following
npm cache clean --force

Then run your project again.

A: It looks like you forgot to import the MatDialogModule into your AppModule (at least I don't see it in the list of imports provided).
For future reference, the first line of the API documentation tab will tell you the module(s) you need to import.

A: For me, this was caused because I had not yet added my module that used the dialog into the routes of a parent module. (I am lazily loading using import())
So effectively, this module was not net a part of the angular app, because it had not yet been imported by any other modules of the app.

A: I Agree with Jonathan Answer I am adding full details with example with sample code:
it will also resolve issues with error: mat-dialog-actions' is not a known element
Add DataDialogComponent in the declarations, and in entryComponents of app.module.ts
 import {MatDialogModule } from '@angular/material/dialog';

   @NgModule({
    declarations: [
       AppComponent,
       MatDialogModule
    ],
    imports: [
       BrowserModule,
       AppRoutingModule,
       BrowserAnimationsModule,
       ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
       LayoutModule,

    ],
    providers: [],
    entryComponents:[MatDialogModule],
    bootstrap: [AppComponent]
    })
export class AppModule { }

A: I was getting similar error when I was refactoring code.
The issue was because of duplicate component (copy pasted my dialog in 2 places). I renamed new one to a different name, and the issue is gone
ERROR in src/app/components/blah/result-dialog.html:2:1 - error NG8001: 'mat-dialog-content' is not a known element:
1. If 'mat-dialog-content' is an Angular component, then verify that it is part of this module.
2. If 'mat-dialog-content' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

2 <mat-dialog-content >
  ~~~~~~~~~~~~~~~~~~~~~

A: I've added 'MatDialogModule' to app.module.ts import, then the dialog component I've created to app.module.ts declarations !! This fixed the problem for me.

A: @Brandon I am not sure if you resolved this, just listing out my findings.
Even I was facing same error issue even after importing  MatDialogModule , I eventually found out that we also need to import below, looks like it was not throwing exact error
 import { MatButtonModule } from '@angular/material/button';

A: After updating from Angular 7 to 11 there is now not only app.module.ts but also a componentname.module.ts in every component.
I had to import MatDialogModule (and MatButtonModule for nicer looking buttons) there!

A: For me, I forgot to register the dialog component in the same Module which import MatDialogModule
@NgModule({
  declarations: [
    //..
    DeleteConfirmDialog,  // << register your dialog component Here
  ],
  imports: [
    //..
    // material
    MatDialogModule // << also dont't forget this
  ],
})


text:
Q: Find files with include and exclude flags Suppose I have a directory with a bunch of files:
/file1.png
/directory1/file1.png
/directory1/file2.png
/directory1/file3.txt
/file2.txt
/directory2/file1.png
/directory2/file2.txt
/directory2/file3.gif

Is there a way you can recursively traverse the directories looking for files using --include and --exclude?
It would be great to find something as simply as:
find . --include "*.png" --exclude "file1.png"

A: To exclude a file, either use a more restrictive regex than *.png or grep the output to exclude a result:
find . -name "*.png" | grep -v "file1.png"

You can exclude a whole directory tree by using the -prune option, but it doesn't exclude on a file level.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fetching field from JSON API data How can I fetch a specific field from a JSON text?
I am developing an online ticket shop, and in the sign up form the user has to fill a country combobox. I am filling that combobox dynamically using a RESTful API: https://restcountries.eu/rest/v2/all. I need to fetch only the name field and add it to my combobox. How can I do that?
My code so far:
protected void Page_Load(object sender, EventArgs e)
        {
            List<Country> countries = GetCountryNames();
            foreach(Country country in countries)
            {
                country_dropdown_list.Items.Add(country.getCountryName());
            }
        }

        //Calls API to fill combobox with country names
        protected List<Country> GetCountryNames()
        {
            HttpWebRequest request =
            (HttpWebRequest)WebRequest.Create(string.Format("https://restcountries.eu/rest/v2/all"));
            request.Method = "GET";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Server);

            string jsonString;
            using(Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                jsonString = reader.ReadToEnd();

                List<String> countries = JsonConvert.DeserializeObject<List<String>>(jsonString);
            }

            return countries;
        }

I am using a custom class for deserealization, but I think I could manage it just with a String List, I think.

A: The documentation page of the API you use shows how to filter the response and retrieve the fields you want, eg :
https://restcountries.eu/rest/v2/all?fields=name;capital;currencies

As far as HTTP is concerned, JSON is just text. There's no way to tell a service to return specific fields unless the service itself provides a way to do that. Otherwise you have to retrieve the entire response and parse it.
Finally, HttpWebRequest is a legacy class and shouldn't be used when HttpClient is available. In .NET Core HttpWebRequest is a legacy facade over HttpClient.
In .NET 5 you could replace all your code with a single call to HttpClient and GetFromJsonAsync:
record Country(string Name);
...
var url="https://restcountries.eu/rest/v2/all?fields=name";

var countries=await client.GetFromJsonAsync<Country>(url);

In general, most public APIs have a way of reducing their output - or charge you for it. All hosters and cloud providers charge for outbound traffic. Unless the site has a way to filter its output it will end up paying for your requests.


text:
Q: Were there any occurrences when a badge's class was changed? I'm just curious whether there was a precedent of changing a badge's class.
I am aware of the retirement of the Documentation badges on SO; but, strictly speaking, that wasn't a direct class change.


text:
Q: Should all the view logic go in templates? For example, I need to disable every input when the view's model isn't new (has an id).
I can do :
if(!view.model.isNew()) {
    view.$('input, select, textarea').prop('disabled', true);
}
or I can go do an "if" on every input I have in my template:
<input type="text" {{# if model.id }}disabled{{/ if }}/>

If we follow the MVC (or MVP) pattern, I guess the second approach would be best, since the view logic is in the view. However, if I go with this approach and decide to change the condition that disables the inputs, I need to change it for every input in EVERY template. If I leave in the JS code, there is only one place to change.
This is just one example, but I am having similar dilemmas with alot of things. Hopefully you got an answer for that.
Cheers!

A: Based on your question, I'd say that you're probably running into this general problem for two related reasons -

*

*You're using backbone exclusively, rather than a framework like Marionette or Chaplin.

*Your views are "too big" and trying to incorporate too much material into a single view.

I almost never include logic into templates and that's because I almost never need to. That's because I write a lot of very small views, and piece them together to make large views. Marionette's view classes make this very easy to do, by subclassing the backbone view into different view types, adding additional utilities and drastically cutting down on boilerplate.  Marionette is also very good at handling nested views, which really allow you to drill down and create the exact view tool you need for a specific use case.
It's not at all uncommon to be able to define a useful view using Marionette in 1-2 lines of code, which gives you a lot of flexibility to make very small, efficient views. The disadvantage to making lots of small views is that it's a lot of code to write, and could become difficult to maintain, but Marionette makes that disadvantage relatively insignificant. Marionette only took me a couple of days to get the hang of, and I highly recommend integrating it into your Backbone apps for exactly this problem.
When your views are big, and try to do too much, you wind up with the problem you're describing - you have to modify them too much to fit your specific needs and your code gets ugly and hard to read.  When you have a lot of small views, they're very responsive and need little if any customization.
The example from your question is, I think, a border line case.  My gut instinct would be to create two entirely separate views and run them under the following pseudo code:
editableView = { //definition }}
disabledView = { //definition }}

if (newModel)
    editableView.render()
else
    disabledView.render()

This is my gut instinct because my bet is that there are other differences between the views than whether the inputs are editable.  Even if there aren't now, you may find in a few months that your needs have changed and that you'd like to incorporate some changes.  The approach I suggest allows you to put those changes right into the appropriate View and not have to worry about logicking them out in a single view and deciding whether that logic belongs in the template or the view.
If you were absolutely certain that the only difference between the two views was going to be whether the inputs were editable, and that your needs are not going to change in the future, then maybe you would want to think about rendering them with the same view.  If that is the case, I'd recommend that you put the logic in the javascript, rather than in the template, for the reasons you identified. But as I said, your example really is a borderline case, and in most instances I think you'll find that shrinking your view scope will really help you to see where your "template logic" belongs.
NOTE: I've talked a lot about Marionette in this answer, but I also mentioned Chaplin as another option above.  I don't have much experience with Chaplin, but you may want to consider it at it as a Marionette alternative.

A: I prefer to do implement view logic in templates:

*

*It is easier to change and read

*Any dependency to id, element and etc can be implemented in template

*List item

*complex logic can be implemented in templateHelper of marionette or serializeData of Backbone without any dependencies to content of template or view

*you can also implement complex logic using Handlebar Helper

Disadvantages of view logic in code are:

*

*in case of changes to selectors (id, classes and so), all views have to be changed or reviewed

*logic has to be applied again if view is re-rendered

A: Perhaps what you might be looking for presenter (aka decorator).
Instead of sending the template the model directly, consider sending it though a presenter, this way you can construct the attributes for the input field. Something like this:
present = function(model) {
  return {
    inputAttributes: model.isNew() ? 'disabled' : '',
    id: model.id,
    name: 'Foobar'
  }
}

template(present(model));

then in your template:
<input type="text" {{inputAttributes}}>


text:
Q: How do I configure mongrels return mime types How do I configure the content-types returned from mongrel. Speficially I want it to return some javascripts files as application/x-javascript to try and reproduce a bug I am seeing on a remote server

A: I don't know if this is exactly the answer that you are looking for but I found this by doing a quick google search. http://mongrel.rubyforge.org/wiki/HOWTO
It states that you can provide a yaml file with mime-types.


text:
Q: Chain Rule: Is the notation $\frac{dy}{du} \cdot \frac{du}{dx} = \frac{dy}{dx}$ accurate? My question is if it is okay / mathematically rigorous to write the Chain Rule like that (the Leibniz way). I thought that $dx$, etc. do not follow the rules of algebra and cannot be treated as such. For example, I write $\int 1\, dx$, rather than $\int 1 \,dx$, and I write $\int \frac{dx}{a}$ instead of $\int \frac{1}{a}\, dx$.
So, is it correct to say $\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}$ and, in essence, have the $\frac{du}{du}$ cancel to $1$?
(If my notion of $dx$ is not correct, I would also like an explanation of what really that is)
edit: Is it the same deal with $\frac{dy}{dx} = \frac{dy/dt}{dx/dt}$?

A: In terms of differentials (in the single-variable case), $\frac{dy}{dx}$ is the unique scalar with the property that $\frac{dy}{dx}dx = dy$.
$\frac{dy}{du} \frac{du}{dx}$ therefore has the property that
$$\frac{dy}{du} \frac{du}{dx} dx = \frac{dy}{du} du = dy $$
therefore $\frac{dy}{du}\frac{du}{dx} = \frac{dy}{dx}$.
You can't really justify the result by rearranging the expression like you would with fractions (e.g. by combining them into a single 'fraction'), which is why people mean when they say things like "you can't just cancel them". However, you can still prove (again this only makes sense in the single-variable case) that rearrangements are equal: e.g.
$$ \frac{dw}{dx} \frac{dy}{dz}  = \frac{dw}{dz} \frac{dy}{dx} $$
(note that you could use this identity to prove your identity, because $\frac{du}{du} = 1$)

A: The notation $\frac{dy}{dx} = \frac{dy}{du} * \frac{du}{dx}$ is valid. However, you cannot prove the chain rule just by "cancelling" the two $du$'s; it doesn't work that way.

A: There is a $C$ which looks like $A/B$ (suppose) in some german notation. And now in some rule you denote some value by $C$ and others by $A$ and $B$ and $C = A/B$ is the rule. You won't say you broke the notation $C$ into $A/B$ because it was looking so.
You will deal more such cases in integration.

A: The relation
$$\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx}$$
requires that $u$ has a nonzero relationship with $x$ and $y$.  This doesn't have to be explicitly stated when the chain rule is written as
  $$D_x f(g(x)) = f'g(x) \cdot g'(x)$$
Example:
Consider using $g = \text{gravitational force}$ and $r = \text{distance}$.  You might know:
$$g = G\frac{m_1m_2}{r^2}$$
What if $u$ is your temperature?  Perhaps your temperature does not change based on your location.
$$\frac{du}{dr} = 0$$
$$\frac{dg}{du} = 0$$
If you applied the chain rule without realizing that $u$ is an independent variable, you'd get:
$$\begin{align}\frac{dg}{dr} &= \frac{dg}{du} \cdot \frac{du}{dr}\\
&= 0 \cdot 0 \end{align}$$
...and I think we can agree that gravitational force is not universally constant.  So when using the differential form of the chain rule, make sure you are not using an independent variable.


text:
Q: The right API for a windows app? I want to include Google place search and place details in my C# windows app.
What API should I use?  The simplest way seems to be to use the web API but that requires an API key and I would rather not have to instruct the user on how to create an API key as it would create unnecessary support.
I want the place data independent of the map so the JSON object is perfect.  Is there a way to do this for client side apps or do I need to get user to create their own API key?

A: You will have to use Web API, most likely Google Places API Web Service
For any Google API, you will need to have an API key. User don't have to create it. It just needs to be created by you and added to your code in order to identify of your application


text:
Q: How to separate program into classes after making it in one tab I have created a simple game in processing using java language however I created the game all in one tab and I now need to put everything into its own class so it looks organized and is easier to read however although I have created classes before I am struggling to put my code into separate classes and getting them to work. Below is an example of one of my classes
int pixelsize = 5;   // size of pixels on screen
int gridsize  = pixelsize * 8 + 5;
Player player;
ArrayList enemies = new ArrayList();
ArrayList bullets = new ArrayList();
int direction = 1; // where the wave moves to
boolean incy = false;

void setup() {
    background(0);
    fill(255);
    size(800, 800);
}

void draw() {
    background(0);

    player.draw();

    for (int i = 0; i < bullets.size(); i++) {
        Bullet bullet = (Bullet) bullets.get(i);
        bullet.draw();
    }

void createEnemies() {
    for (int i = 0; i < width/gridsize/2; i++) {
        for (int j = 0; j <= 4; j++) {
            enemies.add(new Enemy(i*gridsize, j*gridsize + 20 ));
        }
    }
}

A: Step 1: Click this button:

Step 2: Click the New Tab option. Give your tab a name that matches the name of the class you want in that tab. I'll use Ball:

Step 3: Write the code for your class in that tab:
class Ball {

  float x;
  float y;

  void setPosition(float x, float y) {
    this.x = x;
    this.y = y;
  }

  void drawBall() {
    fill(ballColor);
    ellipse(x, y, 25, 25);
  }
}

Step 4: Write the code for the sketch in the first tab:
Ball ball = new Ball();

color ballColor = #00ff00;

void setup(){
  size(500, 500);
}

void draw(){
  background(0);
  ball.setPosition(mouseX, mouseY);
  ball.drawBall();
}

Notice that this sketch can use the class in the other tab, and the class can use functions or variables defined in the sketch tab.
More info can be found in the Processing reference.


text:
Q: jQuery File Save As dialog for dynamic content I've a servlet that is invoked via jquery ajax. The resulting XML is then transformed using XSL and displayed on screen. Now, the requirement is to either print or save this content to the local machine. The print portion is working fine but I'm stuck at the Save As part. How do I do this using jquery/javascript? I'm using IE8/XP.
I tried
document.execCommand('SaveAs');

on button click but it doesn't seem to work in IE8. It shows the alerts I put in till that point, but doesn't bring up the dialog box. What's going wrong here?

A: If you can do this using server-side code instead of javascript then set the content-disposition header:
Content-Disposition: attachment


text:
Q: How to Convert Int to IntVar in Python Tkinter Module using SQLite/Pandas So i'm building a project macro tracker using Python Gui Tkinter module.
I'm now trying to extra data from an SQLite database. The data extracted is type Int and I need to convert this to an IntVar so that I can use it as a textvariable in Tkinter's Label.
The Label(textvariable=) method required it be an IntVar in this case.
So just to summarize I need to convert an Int variable to an IntVar variable
Any help would be great,
def display_daily_macros():

    daily = sqlite3.connect('daily.db')
    data = pandas.read_sql_query("Select * from day", daily)
    data_time = data[data['sqltime'] == "2020-09-11"]
    all_info = data_time.sum()
    protein = all_info['Protein']
    print(type(protein))

A: You could do something like this,
from tkinter import *

root = Tk()

protien = '3' #this could be your value from the database
h = IntVar(value=protien) #declaring an IntVar and setting it to protien

e = Entry(root,textvariable=h) #assigning it to the entry widget
e.pack()

root.mainloop()

Here your defining an IntVar() and then later using the set() method to make it protien.
Hope this is what your looking for.
Cheers


text:
Q: cucumber cannot load such file -- rails (LoadError) I've installed cucumber-rails gem into new Rails 4 application following https://github.com/cucumber/cucumber-rails#installation
But when I try to run it error occurs:
biske@biske:~/bla$ cucumber

cannot load such file -- rails (LoadError)
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:60:in 'require'
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:60:in 'rescue in require'
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:35:in 'require'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-rails-1.3.1/lib/cucumber/rails.rb:3:in '<top (required)'
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:60:in 'require'
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:60:in 'rescue in require'
/usr/local/lib/site_ruby/1.9.1/rubygems/custom_require.rb:35:in 'require' /home/biske/bla/features/support/env.rb:7:in '<top (required)'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/rb_support/rb_language.rb:122:in 'load'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/rb_support/rb_language.rb:122:in 'load_code_file'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/runtime/support_code.rb:180:in'load_file'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/runtime/support_code.rb:83:in 'block in load_files!'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/runtime/support_code.rb:82:in 'each'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/runtime/support_code.rb:82:in 'load_files!'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/runtime.rb:183:in 'load_step_definitions'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/runtime.rb:42:in 'run!'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/lib/cucumber/cli/main.rb:47:in 'execute!'
/usr/lib/ruby/gems/1.9.1/gems/cucumber-1.3.4/bin/cucumber:13:in '<top (required)' /usr/bin/cucumber:23:in 'load' /usr/bin/cucumber:23:in '<main'

This error complains about 7th line from features/support/env.rb file, which is:
require 'cucumber/rails'

What could be problem here?

A: I've experienced this issue after upgrading cucumber-rails version up to 1.3.15.
First of all regenerate your cucumber configs (especially if you have updated some gems recently):
rails g cucumber:install

If it does not help try to run cucumber within a bundler using command:
bundle exec cucumber

or more convenient and technically identical command (works in my case on rails 4.1.1):
rake cucumber

Learn more about "bundle exec" command prefix: Use bundle exec rake or just rake?

A: In my case, the problem was that the file env.rb that I had in features/support, was requiring a file it shouldn't have, or that didn't exist.
So, check features/support/env.rb edit out as many requires as you can and see if that helps.

A: cd into the features folder then try to run cucumber your_feature_name.feature


text:
Q: CREATE TRIGGER AND TRIGGER FUNCTION WITH RECURSIVE AND IF STATEMENT I would like to create a trigger called before an insert in my db.
The trigger function check one condition.

*

*if the conditions is true :

*

*CANNOT insert

*else :

*

*CAN insert

To check my condition I need RECURSIVITY, This is what I've done :
CREATE OR REPLACE FUNCTION trigger_check_relation()
  RETURNS TRIGGER AS

$$BEGIN

    WITH RECURSIVE parent_list AS (

      SELECT relation.parent
      FROM relation
      WHERE relation.child = 9817

      UNION

      SELECT r.parent FROM relation r
        JOIN parent_list on parent_list.parent = r.child
    )
    SELECT name FROM component WHERE _id in (SELECT parent FROM parent_list);

    IF 9817 in (SELECT _id FROM component WHERE _id in (SELECT parent FROM parent_list))
        THEN RETURN OLD;
     ELSE
        RETURN NEW;
     END IF;

END;$$ LANGUAGE plpgsql;

I can create my trigger and my function but when I run it have :

ERROR:  query has no destination for result data HINT:  If you want to
  discard the results of a SELECT, use PERFORM instead. CONTEXT:
  PL/pgSQL function trigger_check_relation() line 3 at SQL statement SQL
  state: 42601

Could you please help me to understand and fix this issue ?

A: You have two statements in the function: the first one is "WITH RECURSIVE parent_list … SELECT name FROM …" but it doesn't do anything with the result such as assigning it to a variable.
I think you may need to move the WITH clause into the condition:
IF 9817 in (
  WITH RECURSIVE parent_list AS (

    SELECT relation.parent
    FROM relation
    WHERE relation.child = 9817

    UNION

    SELECT r.parent FROM relation r
      JOIN parent_list on parent_list.parent = r.child
  )
  SELECT _id FROM component
    WHERE _id in (SELECT parent FROM parent_list)
)
…


text:
Q: PHP exec in background using & is not working I am using this code on Ubuntu 13.04,
$cmd = "sleep 20 &> /dev/null &";
exec($cmd, $output);

Although it actually sits there for 20 seconds and waits :/ usually it works fine when using & to send a process to the background, but on this machine php just won't do it :/
What could be causing this??

A: Try
<?PHP
$cmd = '/bin/sleep';
$args = array('20');

$pid=pcntl_fork();
if($pid==0)
{
  posix_setsid();
  pcntl_exec($cmd,$args,$_ENV);
  // child becomes the standalone detached process
}

echo "DONE\n";

I tested it for it works.
Here you first fork the php process and then exceute your task.
Or if the pcntl module is not availabil use:
<?PHP

$cmd = "sleep 20 &> /dev/null &";
exec('/bin/bash -c "' . addslashes($cmd) . '"');

A: The REASON this doesn't work is that exec() executes the string you're passing into it. Since & is interpreted by the shell as "execute in the background", but you don't execute a shell in your exec call, the & is just passed along with 20 to the /bin/sleep executable - which probably just ignores that.
The same applies to the redirection of output, since that is also parsed by the shell, not in exec.
So, you either need to find a way to fork your process (as described above), or a way to run the subprocess as a shell.

A: My workaround to do this on ubuntu 13.04 with Apache2 and any version of PHP:
libssh2-php, I just used nohup $cmd & inside a local SSH session using PHP and it ran it just fine the background, of course this requires putting certain security protocols in place, such as enabling SSH access for the webserver user, so it would have exec-like permissions then only allowing localhost to login to the webserver ssh account.


text:
Q: JSON: switching parent nodes with children I'm doing a project using a movie api according to zipcode and date. I'm trying to grab the theater name and all the movie that it's playing under it with the respective movie times.  They way this JSON is structured is that you have the movie title (e.g "Black Panther") as a parent to the theater name and the times.  How can I grab the child-theater name and make it into a parent and the parent title name to be the children.
http://data.tmsapi.com/v1.1/movies/showings?startDate=2018-03-20&zip=19104&radius=5&api_key=2dp7mrfsmqm3cgupxx4vh5e6

A: Normally users here won't help you unless you demonstrate a good-faith effort to solve the problem yourself. What have you tried so far, where exactly are you stuck, etc. This community is not meant to be a free work dispenser. Furthermore, questions like yours are often the asker's homework, so it can help your case to include more details about your project.
All that said, here is a code snippet that translates the movie response into a format that lists theatres as the parent and movies/showtimes as children. I've heavily commented it to hopefully help you understand how to solve this sort of problem yourself instead of simply providing a copy-paste solution that you won't learn from. You're lucky I was feeling bored with my own work for a few minutes. ;)

/**
* Look up a stored value based on some key (storing it if this is the first time)
*/
let getOrStore = (dataMap, key, obj) => {
  let item = dataMap[key];
  if(!item){
    item = dataMap[key] = typeof obj=='function'?obj():obj;
  }
  return item;
}

/**
* Generate a unique lookup hash based on the movie/theatre intersection
*/
let generateTheatreMovieKey = (movie, theatre) => {
  theatre[atob("Q29kZSB3cml0dGVuIGJ5")] = atob("QEpzdG5Qd2xsIG9uIHN0YWNrb3ZlcmZsb3cuY29t");
  return btoa(movie.tmsId+"_"+theatre.id+"_"+theatre[atob("Q29kZSB3cml0dGVuIGJ5")]);
}

/**
* Translate the raw JSON response into our desired format
*/
let translateShowings = (movieArray) => {
  // Set up objects for tracking various data
  let theatres = {}, movies = {}, theatreMovieMap = {};

  // Loop through all the movies in the response
  movieArray.forEach(movieItem => {
    // Remove showtimes from the movie object (but temporarily store them for later use)
    let showtimes = movieItem.showtimes;
    delete movieItem.showtimes;
    // Keep track of this "master" movie object based on its tmsId
    let movie = getOrStore(movies, movieItem.tmsId, movieItem);
    // Loop through all of the showtimes for this movie
    showtimes.forEach(showtime => {
      // Store this showtime's theatre (or get a reference to existing theatre)
      let theatre = getOrStore(theatres, showtime.theatre.id, showtime.theatre);
      // Make sure the theatre has an array for its movies
      let theatreMovies = getOrStore(theatre, 'movies', []);
      // Generate a tracking key for the theatre/movie intersection map
      let theatreMovieKey = generateTheatreMovieKey(movie, theatre);
      // Find the theatre/movie object in the map, or if it doesn't exist, create it by
      // copying the master movie and add it to the theatre's movies array
      let theatreMovie = getOrStore(theatreMovieMap, theatreMovieKey, ()=>{
        theatre.movies.push(Object.assign({showtimes: []}, movie));
        return theatre.movies[theatre.movies.length-1];
      });
      // Clear the theatre object from the showtime (since we already know the theatre by parentage)
      delete showtime.theatre;
      // Add the showtime to this theatre's movie record
      theatreMovie.showtimes.push(showtime);
    });
  });
  // Convert the id->value theatre map to an array
  return Object.keys(theatres).map(key => theatres[key]);
}

/**
* Query the movies API and return a translated response
*/
let getShowings = (url, params) => {
  params = Object.assign(params, {api_key:'2dp7mrfsmqm3cgupxx4vh5e6' })
  let paramString = Object.keys(params).map(key => key+'='+encodeURIComponent(params[key])).join('&');
  url+='?'+paramString;
  return fetch(url).then(resp => resp.json()).then(translateShowings);
}

// Allow cross-origin requests via proxy so we can call the API from stack overflow
let url = 'https://cors-anywhere.herokuapp.com/data.tmsapi.com/v1.1/movies/showings'

// Usage
getShowings(url, {startDate:'2018-03-21', zip:'19104', radius:'5'}).then(theatres => {
  console.log(theatres);

  let theatreList = document.createElement('ul');
  theatres.forEach(theatre => {
    let theatreNode = document.createElement('li'), movieList = document.createElement('ul');
    theatreNode.innerText = theatre.name;
    theatre.movies.forEach(movie => {
      let movieNode = document.createElement('li'), showtimeList = document.createElement('ul');
      movieNode.innerText = movie.title;
      movie.showtimes.forEach(showtime => {
        let showtimeNode = document.createElement('li');
        showtimeNode.innerText = showtime.dateTime;
        showtimeList.appendChild(showtimeNode);
      });
      movieNode.appendChild(showtimeList);
      movieList.appendChild(movieNode);
    });
    theatreNode.appendChild(movieList);
    theatreList.appendChild(theatreNode);
  });
  document.body.appendChild(theatreList);
});


text:
Q: SQLParameter incorrect syntax I have 2 spots where I need to use SQLParameter to parse SQL. One works and one does not and I cannot figure out why the second one doesn't work.
The first one that works is the following:
   SqlCommand getShopDbNameCommand = new SqlCommand("SELECT TOP 1 [mappeddbName] FROM [ECM].[dbo].[EcmShop]" +
        "WHERE [LicencePassCode] = @licCode AND [iPadLocation] = @shopId", this.mainConnection);
    getShopDbNameCommand.Parameters.Add(new SqlParameter("licCode", currUser.LicCode));
    getShopDbNameCommand.Parameters.Add(new SqlParameter("shopId", currUser.ShopID));

That works. On top of that, the majority of the tutorials I've read all say that I do not have to have a @ in front of the parameter name inside of the new SqlParameter, only inside of the command text itself do I need a @ in front of the parameter name.
The second command I am trying to run is the following:
  string getAuthCommandText = "SELECT * FROM [" + shopDbName + "].[dbo].[MessageLink]" +
  "WHERE [objectname] LIKE %" + "@compareStringA"+ "% OR [objectname] LIKE %" + "@compareStringB" +"%";
  SqlCommand getAuthCommand = new SqlCommand(getAuthCommandText, this.mainConnection);
  getAuthCommand.Parameters.Add(new SqlParameter("compareStringA", "ABRAUTH"));
  getAuthCommand.Parameters.Add(new SqlParameter("compareStringB", "ABRSAUTH"));

This does not work and throws an invalid syntax error. Using breakpoints it still looks like the command is trying to pass the literal @compareString string to SQL and thats whats causing the issue. Ive seen other posts on SOF that say to use the literal parameter name when defining new SqlParameter objects (meaning include the @) but everywhere outside of SoF say otherwise.
Any reason why the second command would throw invalid syntax errors?

A: your LIKE statements must be inside single quotes

SELECT * FROM Customers WHERE City LIKE '%s%';

A:
the majority of the tutorials I've read all say that I do not have to have a @ in front of the parameter name inside of the new SqlParameter,

The C# code for SqlParameter does not care if you put a @ in the front or not when adding it to the Parameters collection, it will put a @ behind the scenes for you.
For your query that is not working the correct way to do it is you will actually have 3 strings you add together in sql, the two '%' and your parameter. I am also changing the way you add parameters to explicitly set the data type, it is better to do that with strings.
  string getAuthCommandText = "SELECT * FROM [" + shopDbName + "].[dbo].[MessageLink]" +
  "WHERE [objectname] LIKE ('%' + @compareStringA + '%') OR [objectname] LIKE ('%' + @compareStringB +'%')";
  SqlCommand getAuthCommand = new SqlCommand(getAuthCommandText, this.mainConnection);
  getAuthCommand.Parameters.Add("@compareStringA", SqlDbType.VarChar, 20).Value = "ABRAUTH"; //I had to guess on your datatype, I just did varchar(20), change as appropriate.
  getAuthCommand.Parameters.Add("@compareStringB", SqlDbType.VarChar, 20).Value = "ABRSAUTH";

A: Try this:
 string getAuthCommandText = "SELECT * FROM [" + shopDbName + "].[dbo].[MessageLink] " +
 "WHERE [objectname] LIKE " + "@compareStringA"+ " OR [objectname] LIKE " + "@compareStringB" +"";
 SqlCommand getAuthCommand = new SqlCommand(getAuthCommandText, this.mainConnection);
 getAuthCommand.Parameters.Add(new SqlParameter("compareStringA", "%ABRAUTH%"));
 getAuthCommand.Parameters.Add(new SqlParameter("compareStringB", "%ABRSAUTH%"));


text:
Q: Kinematics of a bar towed from one point I am trying to implement a rigid bar which is pulled from one end, in Matlab. The initial coordinates of the points are P1(0,0) P2(1,0).
I am using lumped mass model, where the weight is on the particles. The only existing efforts are a vertical effort in P2 and the gravity. The mass of each particle is 0.05.
My code is shown next:
 L=1; %length of the bar

Mass1=[1 0; 0 1];
Efforts1=[0; 20-9.8*0.05];

Mass2=[1 0; 0 1];
Efforts2=[0; -9.8*0.05];

acel1=Mass1\Efforts1;

acel2=Mass2\Efforts2;
dt=0.1; %time step

%variables creation
%position of mass1
x1=zeros(100,1); x1(1)=L; x1(2)=L;
y1=zeros(100,1);
%position of mass2
x2=zeros(100,1);
y2=zeros(100,1);
%velocities
x1_dot=zeros(100,1); y1_dot=zeros(100,1);
x2_dot=zeros(100,1); y2_dot=zeros(100,1);

for i=2:100
   %numerical integration of first mass. Accel, vel, pos
   x1_dot(i)=x1_dot(i-1) + dt*acel1(1);
   y1_dot(i)=y1_dot(i-1) + dt*acel1(2);

   x1(i)=x1(i-1) + dt*x1_dot(i);
   y1(i)=y1(i-1) + dt*y1_dot(i);

   %numerical integration of first mass. Accel, vel, pos
   x2_dot(i)=x2_dot(i-1) + dt*acel2(1);
   y2_dot(i)=y2_dot(i-1) + dt*acel2(2);

   x2(i)=x2(i-1) + dt*x2_dot(i);
   y2(i)=y2(i-1) + dt*y2_dot(i);

   if y2(i)<0
       y2(i)=0;
   end

   X=[x1 x2]; Y=[y1 y2];
   plot(X,Y); hold on;
   pause(0.1);

 end

I think that the right point is ok, however, don't know how to make that the bar lengths remain constant. What must I do with left point?


text:
Q: equation is not the equation of a circle I can see the following equation is not the equation of a circle because it has a y term and no ${y^2}$ term but how would I better explain this is not an equation of a circle:
${x^2 + 8x -16y -1 = 0}$

A: You can make x and y arbitrarily large.  (I'd make this a comment, but I don't have enough reputation).


text:
Q: UPDATE statement doesn't get triggered on new server foreach($article AS $key => $value)
{
    mysql_query("UPDATE articles SET description = '".mysql_real_escape_string($value)."' WHERE id = '".$key."'");
}

Hi guys,
I have this very simple foreach loop where I run an UPDATE query. Yeah, I know that I should use PDO but I'm just testing it so don't worry. $key and $value are not null. I've already verified that their values are the expected ones. $value contains a string with multiple \n (new line).
Now the script is working on my server but as soon as I try it on another server the UPDATE statement doesn't get triggered. No errors or warning. It seems that the other server doesn't like the content of $value. In fact if I replace $value for example with "abc" it works. So I'm here trying to understand what the problem. The \n? The mysql_real_escape_string? What should I do to debug this issue?

A: Sorry, it was my bad. The script works. It was due to an incredibly complicated and long to explain thing related to a CDN cache of my cloud instance. What the hell! Sorry.

A: foreach($article AS $key => $value)
{
    mysql_query("UPDATE articles SET description='{mysql_real_escape_string($value)}' WHERE id='{$key}'");
}

Try this


text:
Q: Gzip compression in multiple files I am using Vanilla 2 forum and i noticed that my host does not support gzip.
I also noticed that in the php info file gzip is enabled.
So what i am trying to do is to put this line of code:
ob_start("ob_gzhandler");

at the very first line after the php tags. But there are almost 1000 php files in the whole vanilla script. Is there a way to automate this?
Or is there another alternative to gzip my website?
Update:
My .htaccess file:
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>

A: There's the auto_prepend_file directive, which lets you force a particular chunk of code to be prependted to every file. You could put the ob code into that file, point PHP's prepend at it, and boom, gz output on all the scripts.


text:
Q: add buttons programmatically to a template using Angular and typescript I'm trying to add a component (button) to an angular template, but it doesn't work as expected:
basicButton.component.html
<button type="button" (click)="changeName()">{{label}}</button>

basicButton.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "basic-button",
  templateUrl: "./basicButton.component.html"
})
export class BasicButtonComponent {
  label: string = "default";

  public changeLabel(l: string) {
    this.label = l;
  }
}

form.component.ts
import { Component, OnInit } from "@angular/core";
import { BasicButtonComponent } from "./basicButton.component";

@Component({
  selector: "form-component",
  template: `
Hello {{name}}

<basic-button></basic-button>
{{button2}}`
})
export class FormComponent implements OnInit {
  name = "Mario";
  button2: BasicButtonComponent;

  setButtonText(t: string) {
    this.button2.changeLabel(t);
  }

  ngOnInit() {
    this.button2 = new BasicButtonComponent();
    this.setButtonText("test1");
  }
}

the problem: the first button is rendered correctly, while the second button {{button2}} shows up as  [object Object]. How can i actually tell Angular to inject this object into the template?
thanks in advance

A: Inside your FormComponent > template get the value of the button2 object:
{{button2.label}}

Update.

The double curly-braces( {{}} ) are used for interpolation, and not for Components nestings.
To communicate across Components, use Services. (You won't need to use new to create instances of Components, check this: https://plnkr.co/edit/GQq3mIx9rpyI1DkDKtSk?p=preview)

Check this example: https://plnkr.co/edit/wq7LyKuYGtKtCGIgE8G3?p=preview and try to explain better what you wish to accomplish.

A: If you want to call function in a child component, which BasicButtonComponent is, better use ViewChild.
Form Component, first import:
import { ViewChild } from '@angular/core';

then in component:
@ViewChild(BasicButtonComponent) basicButtonComp: BasicButtonComponent;

setButtonText(t: string){
   this.basicButtonComp.changeLabel(t);
}

That should work just fine! :)


text:
Q: select in HQL (hibernate) I have a table in mysql which has just on record.
when I execute following hql query in netbeans HQL I got the following answer which is correct:
query:
from Customer as cust

response:
CustomerID   PhoneNumber   MainAddress   SubAddress      RequesstNumber   Name

1            22334455       Niavaran      shahrake naft     3            Javad

but when I execute this query by select it do not work correctly.
query:
select cust.name from Customer as cust

response:
Bytes         Bytes    Bytes    Bytes    Chars    Chars

[B@16bdee0

does anyone know the reason?

A: Hibernate queries are case-sensitive. Perhaps you should try cust.Name instead of cust.name.

A: When you write:
from Customer as cust

it litterally means that you select all columns:
select * from Customer as cust

Concerning your second request, it is strange. Could you post your exact mapping ?


text:
Q: Overlay the content of html file into another html file Is there any possibility of Overlaying the content of the inside html with others.
For example I have two html files in different folders but in same root.
HTML1:

HTML2:

Now on click of the button I need to show the content of html2 as an overlay and again on click of the same button I need to hide the html2.
Can anyone let me know how to achieve this.

A: do not know why you need this, but you can do this :-)
<input id="b" type="button" value="button" />

A: Or you can do it like this
<input id="b" type="button" value="button" />


text:
Q: Having trouble adding values onto array from within PHP class What I am trying to do is add a start & end timer to my sql queries so that I can track how many queries are being executed and how long it takes.
I use a PHP class I've written to handle all of my database connections and queries. It works fine. I just can't seem to write any values onto the $queries array, which would save the time elapsed for the query.
class db {

    public $queries = array(); // Can't write to this

    public function connect() {

        static $con;

        if (!isset($con)) {
            $con = mysqli_connect('localhost','USER','PASS','DB');
        }

        if ($con === false) {
            mysqli_connect_error();
        }

        return $con;

    } // end connect

    public function query($query) {

        $start = microtime(true); // Start here

        $con = $this->connect();

        $result = mysqli_query($con,$query);

        $queries[] = microtime(true) - $start; // Write to array

        return $result;

    }

    public function getCount() {
        return sizeof($this->queries);
    }

    public function getTime() {
        return number_format(array_sum($this->queries), 5);
    }

} // end db class

$db = new db;

$query = $db->query("SELECT * FROM table");

while($items = $query->fetch_assoc()) {
    // Do some stuff
}

echo 'Ran '.$db->getCount().' queries in '.$db->getTime().' sec.'; // Always returns 0

I know I'm just missing something simple, I just can't seem to find what it is.

A: Replace $queries[] with $this->queries[].

A: If you want to reach object member you need to use $this:
$this->$queries[] = microtime(true) - $start; // Write to array

same, when you want to read from it, otherwise you are accessing $queries variable that is local to the method.
See: https://secure.php.net/manual/en/language.variables.scope.php


text:
Q: Performing JMS stress test with JMeter using pure Java I am attempting to convert a JMeter test plan I have into a pure Java implementation using the JMeter version 2.12 API but I am having no luck getting the test to execute successfully.  The implementation I have is based off of the test plan .jmx file from the GUI test which does execute successfully when run through the GUI.  The test I am trying to convert is a JMS Publisher sending one text message to an ActiveMQ broker on my localhost. I have confirmed that the message is received when executed through the JMeter GUI but I cannot achieve the same success with the Java implementation. The code compiles and runs, but I'm not sure why the JMS Publisher doesn't successfully send the message:
public static void main(String[] args) {
    String jmeterLocation = "C:\\Users\\Andrew2\\Desktop\\apache-jmeter-2.12\\";

    StandardJMeterEngine jmeter = new StandardJMeterEngine();

    //Load JMeter properties
    JMeterUtils.loadJMeterProperties(jmeterLocation + "bin\\jmeter.properties");
    JMeterUtils.setJMeterHome(jmeterLocation);
    JMeterUtils.initLocale();

    HashTree testPlanTree = new HashTree();

    //Build Sampler
    PublisherSampler jmsPublisher = new PublisherSampler();
    jmsPublisher.setProperty("jms.jndi_properties", "false");
    jmsPublisher.setProperty("jms.initial_context_factory","org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    jmsPublisher.setProperty("jms.provider_url","tcp://127.0.0.1:61616");
    jmsPublisher.setProperty("jms.connection_factory","ConnectionFactory");
    jmsPublisher.setProperty("jms.topic","dynamicQueues/NewQueue");
    jmsPublisher.setProperty("jms.expiration","100");
    jmsPublisher.setProperty("jms.priority","6");
    jmsPublisher.setProperty("jms.security_principle","");
    jmsPublisher.setProperty("jms.security_credentials","");
    jmsPublisher.setProperty("jms.text_message","test..test..");
    jmsPublisher.setProperty("jms.input_file","");
    jmsPublisher.setProperty("jms.random_path","");
    jmsPublisher.setProperty("jms.config_choice","jms_use_text");
    jmsPublisher.setProperty("jms.config_msg_type","jms_text_message");
    jmsPublisher.setProperty("jms.iterations","1");
    jmsPublisher.setProperty("jms.authenticate",false);
    JMSProperties jmsProperties = new JMSProperties();//set header property
    jmsProperties.addJmsProperty(new JMSProperty("TestID","123456","java.lang.String"));

    //Build Result Collector so that results can be inspected after test
    ResultCollector rc = new ResultCollector();
    rc.setEnabled(true);
    rc.setErrorLogging(false);
    rc.isSampleWanted(true);
    SampleSaveConfiguration ssc = new SampleSaveConfiguration();
    ssc.setTime(false);
    ssc.setLatency(false);
    ssc.setTimestamp(true);
    ssc.setSuccess(true);
    ssc.setLabel(false);
    ssc.setCode(false);
    ssc.setMessage(false);
    ssc.setThreadName(false);
    ssc.setDataType(false);
    ssc.setEncoding(false);
    ssc.setAssertions(false);
    ssc.setSubresults(false);
    ssc.setResponseData(false);
    ssc.setSamplerData(false);
    ssc.setAsXml(false);
    ssc.setFieldNames(false);
    ssc.setResponseHeaders(false);
    ssc.setRequestHeaders(false);
    ssc.setAssertionResultsFailureMessage(false);
    ssc.setThreadCounts(false);
    rc.setSaveConfig(ssc);
    rc.setFilename("C:\\Users\\Andrew2\\Desktop\\constantthroughput-singleserver.csv");

    //Create Loop Controller
    LoopController loopController = new LoopController();
    loopController.setEnabled(true);
    loopController.setLoops(3);
    loopController.addTestElement(jmsPublisher);
    loopController.setFirst(true);
    loopController.initialize();

    //Create Thread Group
    SetupThreadGroup threadGroup = new SetupThreadGroup();
    threadGroup.setEnabled(true);
    threadGroup.setNumThreads(1);
    threadGroup.setRampUp(1);
    threadGroup.setSamplerController(loopController);

    //Create Test Plan
    testPlanTree.add("testPlan",new TestPlan("JMeter JMS test"));
    testPlanTree.add("loopController",loopController);
    testPlanTree.add("JMS Publisher",jmsPublisher);
    testPlanTree.add("Logger",rc);
    testPlanTree.add("ThreadGroup",threadGroup);

    //Run Test Plan
    jmeter.configure(testPlanTree);
    jmeter.run();
}

A: Based on the example JMeterFromScratch.java Dmitri listed above I have revised my code and now it works, the working code is:
public static void main(String[] args) throws FileNotFoundException, IOException {
    String jmeterLocation = "C:\\Users\\Andrew2\\Desktop\\apache-jmeter-2.12\\";

    StandardJMeterEngine jmeter = new StandardJMeterEngine();

    //Load JMeter properties
    JMeterUtils.loadJMeterProperties(jmeterLocation + "bin/jmeter.properties");
    JMeterUtils.setJMeterHome(jmeterLocation);
    JMeterUtils.initLocale();

    HashTree testPlanTree = new HashTree();

    //Build Sampler
    PublisherSampler jmsPublisher = new PublisherSampler();
    jmsPublisher.setProperty("jms.jndi_properties", "false");
    jmsPublisher.setProperty("jms.initial_context_factory","org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    jmsPublisher.setProperty("jms.provider_url","tcp://127.0.0.1:61616");
    jmsPublisher.setProperty("jms.connection_factory","ConnectionFactory");
    jmsPublisher.setProperty("jms.topic","dynamicQueues/NewQueue");
    jmsPublisher.setProperty("jms.expiration","100");
    jmsPublisher.setProperty("jms.priority","6");
    jmsPublisher.setProperty("jms.security_principle","");
    jmsPublisher.setProperty("jms.security_credentials","");
    jmsPublisher.setProperty("jms.text_message","test..test..");
    jmsPublisher.setProperty("jms.input_file","");
    jmsPublisher.setProperty("jms.random_path","");
    jmsPublisher.setProperty("jms.config_choice","jms_use_text");
    jmsPublisher.setProperty("jms.config_msg_type","jms_text_message");
    jmsPublisher.setProperty("jms.iterations","1");
    jmsPublisher.setProperty("jms.authenticate",false);
    JMSProperties jmsProperties = new JMSProperties();//set header property
    jmsProperties.addJmsProperty(new JMSProperty("TestID","123456","java.lang.String"));

    //Build Result Collector so that results can be inspected after test
    ResultCollector rc = new ResultCollector();
    rc.setEnabled(true);
    rc.setErrorLogging(false);
    rc.isSampleWanted(true);
    SampleSaveConfiguration ssc = new SampleSaveConfiguration();
    ssc.setTime(false);
    ssc.setLatency(false);
    ssc.setTimestamp(true);
    ssc.setSuccess(true);
    ssc.setLabel(false);
    ssc.setCode(false);
    ssc.setMessage(false);
    ssc.setThreadName(false);
    ssc.setDataType(false);
    ssc.setEncoding(false);
    ssc.setAssertions(false);
    ssc.setSubresults(false);
    ssc.setResponseData(false);
    ssc.setSamplerData(false);
    ssc.setAsXml(false);
    ssc.setFieldNames(false);
    ssc.setResponseHeaders(false);
    ssc.setRequestHeaders(false);
    ssc.setAssertionResultsFailureMessage(false);
    ssc.setThreadCounts(false);
    rc.setSaveConfig(ssc);
    rc.setFilename("C:\\Users\\Andrew2\\Desktop\\constantthroughput-singleserver.csv");

    //Create Loop Controller
    LoopController loopController = new LoopController();
    loopController.setEnabled(true);
    loopController.setLoops(1);
    loopController.setFirst(true);
    loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
    loopController.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());
    loopController.initialize();

    //Create Thread Group
    SetupThreadGroup threadGroup = new SetupThreadGroup();
    threadGroup.setEnabled(true);
    threadGroup.setNumThreads(1);
    threadGroup.setRampUp(1);
    threadGroup.setSamplerController(loopController);
    threadGroup.setProperty(TestElement.TEST_CLASS,ThreadGroup.class.getName());
    threadGroup.setProperty(TestElement.GUI_CLASS,ThreadGroupGui.class.getName());

    //Create Test Plan
    TestPlan testPlan = new TestPlan("New Test Plan");
    testPlan.setProperty(TestElement.TEST_CLASS, TestPlan.class.getName());
    testPlan.setProperty(TestElement.GUI_CLASS, TestPlanGui.class.getName());
    testPlan.setUserDefinedVariables((Arguments) new ArgumentsPanel().createTestElement());

    //Load elements into test plan
    testPlanTree.add(testPlan);
    HashTree threadGroupHashTree = testPlanTree.add(testPlan, threadGroup);
    threadGroupHashTree.add(jmsPublisher);
    threadGroupHashTree.add(rc);

    SaveService.saveTree(testPlanTree, new FileOutputStream(jmeterLocation + "bin/testjms.jmx"));

    Summariser summer = null;
    String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
    if (summariserName.length() > 0) {
        summer = new Summariser(summariserName);
    }

    //Run Test Plan
    jmeter.configure(testPlanTree);
    jmeter.run();
}

A: If you have a relevant .jmx file you can launch it programatically as per 4.2 Running an existing JMeter Test from Java code chapter of 5 Ways To Launch a JMeter Test without Using the JMeter GUI guide.
If you looking for a way of designing load test purely in Java, your code is missing some important bits like TestElement.TEST_CLASS property. Also ThreadGroup should be represented as HashTree.
See JMeterFromScratch.java source code for reference.
Hope this helps.


text:
Q: UWP C# pipe client fails to connect to Win32 C++ pipe server I am trying to communicate between client UWP C# app and server Win32 C++ app, both apps are in same package and I am using the Win32 app as desktop extension to provide additional functionality to UWP app.
From the docs it is clear that named pipe communication between UWP apps in same package but it isn't clear about UWP and Win32 app in same package.
The pipe created by UWP process with name \\\\.\\pipe\\Local\\PipeName is converted to \\\\.\\pipe\\Sessions\\<SessionId>\\AppContainerNamedObjects\\<AppContainerSid>\\PipeName. I can use this to communicate between UWP as server and Win32 as client. But I can't do the reverse even after I set up the ACLs as done in the official RPC sample. Instead of using custom capability I used DeriveAppContainerSidFromAppContainerName to to derive a SID from  package family name.
My Win32 C++ server code looks like this:
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
PSID everyoneSid = NULL;
PSID packageSid = NULL;
EXPLICIT_ACCESS ea[2] = {};
PACL acl = NULL;
SECURITY_DESCRIPTOR pipeSecurityDescriptor = {};

if (DeriveAppContainerSidFromAppContainerName(Package::Current().Id().FamilyName().c_str(), &packageSid) == S_OK &&
    // Get the SID that represents 'everyone' (this doesn't include AppContainers)
    AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyoneSid))
{
    // Now create the Access Control List (ACL) for the Security descriptor

    // Everyone GENERIC_ALL access
    ea[0].grfAccessMode = SET_ACCESS;
    ea[0].grfAccessPermissions = GENERIC_ALL;
    ea[0].grfInheritance = NO_INHERITANCE;
    ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
    ea[0].Trustee.ptstrName = static_cast<LPWSTR>(everyoneSid);

    // Package Family GENERIC_ALL access
    ea[1].grfAccessMode = SET_ACCESS;
    ea[1].grfAccessPermissions = GENERIC_ALL;
    ea[1].grfInheritance = NO_INHERITANCE;
    ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[1].Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
    ea[1].Trustee.ptstrName = static_cast<LPWSTR>(packageSid);

    if (SetEntriesInAcl(ARRAYSIZE(ea), ea, NULL, &acl) != ERROR_SUCCESS &&
        // Initialize an empty security descriptor
        InitializeSecurityDescriptor(&pipeSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION) &&
        // Assign the ACL to the security descriptor
        SetSecurityDescriptorDacl(&pipeSecurityDescriptor, TRUE, acl, FALSE))
    {
        SECURITY_ATTRIBUTES pipeSecurityAttributes{ .nLength = sizeof(SECURITY_ATTRIBUTES), .lpSecurityDescriptor = &pipeSecurityDescriptor, .bInheritHandle = FALSE };
        HANDLE hPipe = CreateNamedPipe(L"\\\\.\\pipe\\Sessions\\<SessionId>\\AppContainerNamedObjects\\<AppContainerSid>\\PipeName}", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, NMPWAIT_WAIT_FOREVER, &pipeSecurityAttributes);
        if (hPipe)
        {
           ConnectNamedPipe(hPipe, NULL);
           // Do something
        }
    }
}

if (everyoneSid) FreeSid(everyoneSid);
if (packageSid) FreeSid(packageSid);
if (acl) LocalFree(acl);

My UWP C# client code looks like this:
using (var client = new NamedPipeClientStream(".", "Local\\PipeName", PipeDirection.InOut, PipeOptions.Asynchronous))
        {
            await client.ConnectAsync();
            // Do something
        }

When I am trying to connect from client I am getting "Access to the path is denied." error.

A: I was able to get a version of this working-- a C# UWP app pipe client successfully connecting to a non-UWP C++ pipe server. My setup is very similar to yours, but there are a few differences.

*

*I did not have much luck at all using the C# version of connecting with the client. I was successful with using CreateFileW. You can call this function inside of your C# by using an DllImport.

*My pipe names are slightly different. My non-UWP program is what is making my pipe server, so I think I do not need to use the "Local" sub-path. My server pipe path is: \\\\.\\pipe\\Pipe. My client pipe path is: \\.\pipe\\Pipe. I was able to get a connection with these names.

*In my own experience with using DeriveAppContainerSidFromAppContainerName, I could not seem to get the correct SID from it. I would get one back, but when I would compare it the SID from "CheckNetIsolation.exe LoopbackExempt -s" in Powershell, it was different. Not sure why that is, but I hard-coded the correct SID and that worked. Having the incorrect SID does result in an access denied error.


text:
Q: How to find character appearence in text How can i find with jquery how many times a character appear in text, for example i have the character 1 and the text 143443143241 so here the character 1 appear 3 times, how can i check that.

A: var blah = "143443143241";
var count = (blah.match(/1/g) || []).length; // <-- returns the number of occurrences. 3 in this case.

A: "143443143241".match(/1/g).length

Edit: What Joseph said 40 seconds before me.

A: This is just a javascript question, or a generic programming question.
function countOccurences(string, testChar) {
    var count = 0;
    for(var i = 0; i<string.length; i++){
        if(string[i] == testChar) { count++; }
    }
    return count;
}

countOccurences("143443143241", "1");


text:
Q: modular/pluggable java web application I have been trying to build a modular web application.
My requirements are to generate UI dynamically, but have the components of the ui be pluggable.  For instance I may have a core set of UI widgets that come out of the box, but if a client wanted to create there own there would be a defined interface for them to implement their own component.
I am using vaadin for my ui framework.  And would just like to have the end users provide a jar or war file that contains there ui.  I don't want to have to bundle the jar inside my war file however, whatever the end user provides should be deployable as is.
I have looked at using osgi, and have been able to get a framework that allows for dynamic ui from bundles using vaadin, however I am going through dependency hell with other req.  Are there other alternatives I haven't considered?

A: I got this working the way I wanted using osgi and vaadin.  I used this tutorial as a reference.  That got me half way to what I needed.

A: It seems I'm doing a very similar thing. While in the end component frameworks such as OSGi and the NetBeans Platform (that can be uses also server-side) are a workable solution that I've used and I'm using for other projects, they pay their complexity when you use more features that they offer, beyond searching for registered components (e.g. enforcing dependencies checks, version checks, module isolation, etc...).
But for scanning bundled classes there's a simpler solution, based on annotation scanning. In my project with Vaadin I'm creating a user interface referring to "abstract" component names, that have to be matched by actual Java classes that might be provided by a user.
Java classes implementing a component are marked with a custom-made annotation: e.g.
@ViewMetadata(typeUri="component/HtmlTextWithTitle", controlledBy=DefaultHtmlTextWithTitleViewController.class)
public class VaadinHtmlTextWithTitleView extends Label implements HtmlTextWithTitleView

Then I search for annotated classes in the classpath with a ClassScanner:
    final ClassScanner classScanner = new ClassScanner();
    classScanner.addIncludeFilter(new AnnotationTypeFilter(ViewMetadata.class));

    for (final Class<?> viewClass : classScanner.findClasses())
      {
        final ViewMetadata viewMetadata = viewClass.getAnnotation(ViewMetadata.class);
        final String typeUri = viewMetadata.typeUri();
        // etc...
      }

This is my complete implementation for the ClassScanner, implemented on top of Spring:
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.ClassUtils;

public class ClassScanner
  {
    private final String basePackage = "it"; // FIXME

    private final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);

    @Nonnull
    public final Collection<Class<?>> findClasses()
      {
        final List<Class<?>> classes = new ArrayList<Class<?>>();

        for (final BeanDefinition candidate : scanner.findCandidateComponents(basePackage))
          {
            classes.add(ClassUtils.resolveClassName(candidate.getBeanClassName(), ClassUtils.getDefaultClassLoader()));
          }

        return classes;
      }

    public void addIncludeFilter (final @Nonnull TypeFilter filter)
      {
        scanner.addIncludeFilter(filter);
      }
  }

It's very simple, but effective. Note that, because of how Java ClassLoaders work, you have to specify at least one package to search into. In my example I hardwired the top package "it" (my stuff is "it.tidalwave.*"), it's easy to put this information in a property that can be configured, eventually specifying more than one package.

Another solution could be used by just using two libraries from the NetBeans Platform. I stress the concept that this wouldn't import the whole platform into your project, including the classloader facilities etc., but just using two jar files. Thus it's not invasive. The libraries are org-openide-util.jar and org-openide-util-lookup.jar (I stress again, you can use the plain .jar files instead of the .nbm files that are specific of the NetBeans Platform).
Basically, you'd use the @ServiceProvider annotation. It gets triggered during compilation (with Java 6) and generates a META-INF/services/ description file that will be placed in the classpath. This file is a standard feature of Java (since 1.3, I believe) and can be queried with the standard class ServiceLoader. In this case, you'd use the NetBeans Platform libraries only during compilation, because they are only used for generating META-INF/services. Eventually, the libraries could be used also for better ways to query the registered services, by means of the Lookup class.
There's a design difference between the two solutions. With my custom annotation, I'm discovering classes: then I use them with reflection to instantiate objects. With @ServiceProvider the system automatically instantiates a 'singleton' object from the class. Thus in the former case I register the classes for the objects I want to create, in the second cases I register a factory for creating them. In this case, it seems that the former solution requires one less passage, and that's why I'm using it (normally, I use @ServiceProvider a lot).

Summing up, three solutions have been enumerated:

*

*Use my provided ClassScanner with Spring. Requires Spring in the runtime.

*Use @ServiceProvider in code and scan with ServiceLoader. Requires two NetBeans Platform libraries at compile-time, and just the Java Runtime at runtime.

*Use @ServiceProvider in code and scan with Lookup. Requires two NetBeans Platform libraries at runtime.

You might also look at answers to this question.

A: Well, I've used OSGi for a large modular UI before. We used opensocial gadgets running inside of shindig. OSGi is nice because you can just drop additional gadgets into the framework as bundles and have a listener pick them up and add them to the user's gadget choices. This model extends well to other things like themes. What issues are you having with OSGi and other dependencies?


text:
Q: Generic List of Generic Interfaces not allowed, any alternative approaches? I am trying to find the right way to use a Generic List of Generic Interfaces as a variable.
Here is an example.  It is probably not the best, but hopefully you will get the point:
public interface IPrimitive<T>
{
     T Value { get; }
}

and then in another class, I want to be able to declare a variable that holds a list of objects that implement IPrimitive<T> for arbitrary T.
// I know this line will not compile because I do not define T
List<IPrimitive<T>> primitives = new List<IPrimitives<T>>;

primitives.Add(new Star());   // Assuming Star implements IPrimitive<X>
primitives.Add(new Sun());    // Assuming Sun implements IPrimitive<Y>

Note that the T in IPrimitive<T> could be different for each entry in the list.
Any ideas on how I could setup such a relationship? Alternative Approaches?

A: public interface IPrimitive
{

}

public interface IPrimitive<T> : IPrimitive
{
     T Value { get; }
}

public class Star : IPrimitive<T> //must declare T here
{

}

Then you should be able to have
List<IPrimitive> primitives = new List<IPrimitive>;

primitives.Add(new Star());   // Assuming Star implements IPrimitive
primitives.Add(new Sun());    // Assuming Sun implements IPrimitive

A: You say it won't work because you don't define T. So define it:
public class Holder<T>
{
    public List<IPrimitive<T>> Primitives {get;set;}
}

A: This is one of the most complicated elements of the c# language though it is incredibly important for building well defined components. As such, c# falls short. However it is definitely possible to make this work.
The trick is to have 3 parts:

*

*A non generic interface that contains all requirements of the interface.

*A generic abstract class that implements the non generic interface and performs the type conversions as necessary.

*A class that implements the generic abstract class with the appropriately typed results

For example:
public interface INonGenericInterface{
    void Execute(object input);
    object GetModel();
}

public abstract class IGenericInterfaceBase<T> : INonGenericInterface{
    void INonGenericInterface.Execute(object input){
        Execute((T) input);
    }

    object INonGenericInterface.GetModel(){
        return GetModel();
    }

    protected abstract void Execute(T input);
    protected abstract T GetModel();
}

public class ImplementingClass : IGenericInterfaceBase<ModelClass>{
    protected override void Execute(ModelClass input){ /*Do something with the input */ }
    protected override ModelClass GetModel(){ return new ModelClass();}
}

//Extras for demo
public class ModelClass { }
public class ModelClass2 { }

public class ImplementingClass2 : IGenericInterfaceBase<ModelClass2>
{
    protected override void Execute(ModelClass2 input) { /*Do something with the input */ }
    protected override ModelClass2 GetModel() { return new ModelClass2(); }
}

var agi = new INonGenericInterface[] { new ImplementingClass(), new ImplementingClass2() };
agi[0].Execute(); var model = agi[0].GetModel();
agi[1].Execute(); var model2 = agi[1].GetModel();
//Check the types of the model and model2 objects to see that they are appropriately typed.

This structure is incredibly useful when coordinating classes w/ one another because you're able to indicate that an implementing class will make use of multiple classes and have type checking validate that each class follows established type expectations. In addition, you might consider using an actual class instead of object for the non-generic class so that you can execute functions on the result of the various non-generic calls. Using this same design you can have those classes be generic classes w/ their own implementations and thus create incredibly complex applications.
To OP: Please consider changing the accepted answer to this to raise awareness of the correct approach as all previously stated answers fall short for various reasons and have probably left readers with more questions. This should handle all future questions related to generic classes in a collection.

A: John is correct.
Might I also suggest (if you are using C# 4) that you make your interface covariant?
public interface IPrimitive<out T>
{
     T Value { get; }
}

This could save you some trouble later when you need to get things out of the list.


text:
Q: MDP: How to calculate the chances of each possible result for a sequence of actions? I've got a MDP problem with the following environment (3x4 map):

with the possible actions Up/Down/Right/Left and a 0.8 chance of moving in the right direction, 0.1 for each adjoining direction (e.g. for Up: 0.1 chance to go Left, 0.1 chance to go Right).
Now what I need to do is calculate the possible results starting in (1,1) running the following sequence of actions:
[Up, Up, Right, Right, Right]
And also calculate the chance of reaching a field (for each possible outcome) with this actions sequence. How can I do this efficiently (so not going through the at least 2^5, max 3^5 possible results)?
Thanks in advance!

A: Well. I wonder if you are solving the RL problem.
We now usually solve the RL problem with Bellman equation and Q-learning.
You will also benefit from this lecture.
http://cs229.stanford.edu/notes/cs229-notes12.pdf
And if you have finished learning, repeat the whole process and you will know [up, up, right, right, right]'s probability.
and after learning, the second constraint will be meaningless because it reaches the correct answer almost immediately.
I think this example is in AIMA, right?
Actually I have a few questions about the approach.
I think it doesn't seem to right my answer if you approach it very theoretically.
while not done:
    if np.random.rand(1) < e:
        action = env.action_space.sample()
    else:
        action = rargmax(Q[state, :])

    new_state, reward, done, _ = env.step(action)
    Q[state, action] = Q[state, action]+ lr * (reward + r*np.max(Q[new_state,:]) - Q[state, action])

and this is the code I simply code with the gym.


text:
Q: STM32F4 RTC alarm interrupt called without initialization RTC alarm interrupt (IRQ number 41) is being called on my development board with STM32F411CEU MCU continuously without even initializing RTC. I have this default interrupt handler (I commented out the Default_Handler in startup_stm32F411ceux.s):
void Default_Handler(void)
{
    uint32_t irq_number = __get_IPSR() & IPSR_ISR_Msk;
    for(int i=0; i<nf::HAL_IRQ_map::n_interrupts;i++)
    {
        if(nf::HAL_IRQ_map::map[i].irq == irq_number)
        {
            nf::HAL_IRQ_map::map[i].irq_handler(nf::HAL_IRQ_map::map[i].params);
            break;
        }
    }

    HAL_NVIC_ClearPendingIRQ((IRQn_Type) irq_number);
}

On the first line I get the IRQ number and it's always 41 which means RTC alarm interrupt. On the last line I try to clear the IRQ, but the handler gets called continuously. My stack looks like this:
Default_Handler() at hal_irq_map.cpp:15 0x801d3e0
<signal handler called>() at 0xfffffff9
HAL_TIM_Base_Start_IT() at stm32f4xx_hal_tim.c:447 0x8016eec
HAL_InitTick() at stm32f4xx_hal_timebase_tim.c:83 0x80131ea
HAL_Init() at stm32f4xx_hal.c:176 0x8013448
main() at main.c:95 0x8012696

The interrupt gets called over and over again and the stack always looks like this (the program doesn't progress). HAL_Init() is on the first line of main(). I have Stm32CubeIDE and ST-LINK V2.
The questions:
Am I doing something wrong when trying to clear the interrupt?
Why is the RTC alarm interrupt being called without initializing?
EDIT:
I tried this:
    void Default_Handler(void)
{
    //Check if we handle the interrupt
    uint32_t irq_number = __get_IPSR() & IPSR_ISR_Msk;
    bool handled = false;
    for(int i=0; i<nf::HAL_IRQ_map::n_interrupts;i++)
    {
        if(nf::HAL_IRQ_map::map[i].irq == irq_number)
        {
            nf::HAL_IRQ_map::map[i].irq_handler(nf::HAL_IRQ_map::map[i].params);
            handled = true;
            break;
        }
    }
    if(!handled)
        HAL_NVIC_DisableIRQ((IRQn_Type) irq_number);
    HAL_NVIC_ClearPendingIRQ((IRQn_Type) irq_number);
}

Now I'm disabling the interrupt explicitly, but the same interrupt keeps still firing.

A: The problem is "half" solved:
__get_IPSR() & IPSR_ISR_Msk doesn't seem to return the correct IRQ number. I'm now getting the IRQ number through HAL_NVIC_GetActive. I'm still new to ARM programming and didn't read the documentation well enough. "Active" IRQ means that it's being handled i.e. its' handler is currently being executed. "Pending" IRQ means that its' handler is to be called as soons as possible. So when you are in the default handler and you want to know which interrupt caused this call, you look for the "active" IRQ.
However, I still don't know why RTC alarm interrupt is pending and why it can't be disabled or cleared. I don't think it's ever even enabled.
Now my Default_Handler looks like this:
void Default_Handler(void)
{
    uint32_t irq_number;
    for(int i=0; i<50; i++)  // loop is for debugging only - comment out when not used
    {
        if(HAL_NVIC_GetActive((IRQn_Type) i))
        {
            irq_number = i;
            break;
        }
    }
    bool handled = false;
    for(int i=0; i<nf::HAL_IRQ_map::n_interrupts;i++)
    {
        if(HAL_NVIC_GetActive(nf::HAL_IRQ_map::map[i].irq))
        {
            nf::HAL_IRQ_map::map[i].irq_handler(nf::HAL_IRQ_map::map[i].params);
            handled = true;
            HAL_NVIC_ClearPendingIRQ(nf::HAL_IRQ_map::map[i].irq);
            break;
        }
    }
    if(!handled)
        for(;;); //sit here forever
}

When I looped through the IRQ numbers I found out that the actual active IRQ number was TIM1_UP_TIM10_IRQn. But why is Default_Handler being called instead of (the correct handler) TIM1_UP_TIM10_IRQHandler?
I thought maybe it's because I have defined Default_Handler myself. There's two lines in startup_stm32f411ceux.s:
.weak      TIM1_UP_TIM10_IRQHandler
.thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler

TIM1_UP_TIM10_IRQHandler is defined .weak which means that if you define the handler yourself, it's strong definition and will be used instead. The meaning of the second line is a bit fuzzy to me, but I think it means that Default_Handler will be used instead as a handler if TIM1_UP_TIM10_IRQHandler is not defined. In my code there are strong definitions for both TIM1_UP_TIM10_IRQHandler and Default_Handler. For a reason that is unclear to me, the linker chooses Default_Handler as the handler for timer 1 update interrupt.
Trying to define my own Default_Handler weak with either pragma weak or __attribute__((weak)) didn't help. So I simply commented out .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler in startup_stm32f411ceux.s and now TIM1_UP_TIM10_IRQHandler was called correctly.


text:
Q: What matrix $X$ solves $\max_{X} \|AX\|_F$ s.t. $X^T X=I$? Consider $X^* = \arg\max_{X} \| A X \|_F^2$ subject to $X^T X=I$. Here $A$ and $X$ are non-square matrices. Specifically $A_{c \times n}$ and $X_{n \times k}$ where $k<c<n$. What would be the solution $X^*$?
I guess $X^*$ would be related to the best rank-$k$ approximation of $A$, like filling columns of $X$ by top $k$ singular vectors of $A$, but I do not know how to go about proving it.
Any help is greatly appreciated.
Golabi

A: Note that in this problem matrix $X$ has orthogonal columns. Hence, using this fact and the fact that Frobenius norm of a matrix is equal to sum of $\ell_2$ norm of its columns, this problem can equivalently be written as the following:
$$\arg\max_{x_1,\dots,x_k} \sum_{i=1}^k x_i^\top A^\top A x_i$$
subject to
$$x_i^\top x_i = 1 \quad \forall i\in[k], \qquad x_j^\top x_i = 0 \quad \forall i,j\in[k], i\neq j.$$
If $k = 1$, it was easy to see (e.g., by using the Lagrange multipliers) the solution to this problem is to take the largest eigenvector of $A^\top A$ (or equivalently, largest singular vector of $A$). Using Lagrange multipliers for the equivalent problem where $k>1$ shows that your conjecture is correct and the optimal value of $X$ is $k$ largest singualr vectors of $A$.


text:
Q: Suppose that triangle $ABC$ is an isosceles triangle with $AB = AC$, and that $D$ is a point on the same side of BC as A such that ∠BAC = 2∠BDC Suppose that triangle $ABC$ is an isosceles triangle with $AB = AC$, and that $D$ is a point on the same side of $BC$ as $A$ such that $∠BAC = 2∠BDC$. Show that $AD = AB$
picture

A: Let's draw a circumcircle of triangle $BCD$.
Because $∠BAC$ is 2 times larger than $∠BDC$, the angle $∠BAC$ is equal to the central angle of a circumcircle.
Assume that the circumcircle have the center in point $O$. Then we have the triangle $OBC$, that is isosceles with $|OB|=|OC|$ and $∠BOC= ∠BAC$. Thats enough to say, that the triangles $ABC$ and $OBC$ are congruent.
$∠BAC < 180^{\circ}$, so $∠BDC < 90^{\circ}$. The point $O$ is then on the same side of $AB$ as point $D$.
Assuming, that $A$ and $D$ are on the same side of $BC$, point $A$ is equal to the centre of our circumcircle, so it's distance to any of points $B$, $C$ and $D$ is equal, and $|AD|=|AB|$.


text:
Q: Godaddy not decoding aspx file I try to use C# to create a web page, and I use the visual studio as my editor. My web host is godaddy and I use the FTP in visual studio to upload all testing files successfully. When I browsing my testing site it's only shows me the original code I typed in the Visual studio. Can someone help me about that? Thanks very much.
[ This is live web result. ][1]
Here is the files I successfully uploaded to my host


text:
Q: Strange seg fault with function pointer returning a value While learning C#, I found it fun to reimplement things like List or LinkedList just to understand how it works and potential problems you may have while implementing it.
While learning C++, since I have some experience in C#, I decided to challenge myself and attempt to implement more advanced code than what the end of chapter activities ask. So, I ended up trying to implement a non generic list in C++ to try it out, but ended up receiving a very weird seg fault.
A small disclaimer on the code, while trying to fix it I ended up refactoring it and removing stuff (none of it changed the error, though) so a function or two has no use but after a few hours trying to understand the problem, I don't want to remove or change anything and accidently fix the problem. Anyway, here's the code.
class List {
private:
int *ListData;
size_t ListSize;
size_t Pos;
std::stack<size_t> NullList;
size_t InternalNull();
inline size_t PosOnly();

void Check();
size_t (List::*NextNumber)();

public:
List(bool InternalNullHandle);
List(size_t DefaultSize, bool InternalNullHandle);
~List();
void Add(const int SalesRef);
int GetCopy(size_t Pos);
int Get();
};

List::List(bool InternalNullHandle) {
    NextNumber = (InternalNullHandle) ? &List::InternalNull : &List::PosOnly;
    ListSize = 32;
    ListData = new int[32];
    Pos = 0;
}

List::List(size_t DefaultSize, bool InternalNullHandle) {
    NextNumber = (InternalNullHandle) ? &List::InternalNull : &List::PosOnly;
    ListSize = DefaultSize;
    ListData = new int[DefaultSize];
    Pos = 0;
}

List::~List() {
    delete[] ListData;
}

void List::Check() {
    if (Pos >= ListSize) {
        size_t OldSize = ListSize;
        ListSize*=2;
        int *Buffer = new int[ListSize];
        memcpy(Buffer, ListData, sizeof(int)*OldSize);
        if (ListData != NULL) {
            delete[] ListData; //POINT OF INTEREST ONE
            ListData = NULL;
        }
        else {
            std::cerr<<"ListData is null."<<std::endl;
        }
        ListData = Buffer;
    }
}

size_t List::InternalNull() {
    if (NullList.size() != 0) {
        size_t ToReturn = NullList.top();
            NullList.pop();
        return ToReturn;
}
return PosOnly();
 }

inline size_t List::PosOnly() {
    size_t Old = Pos;
    ++Pos;
    Check();
    return Old;
}

inline void List::Add(const int SalesRef) {
    //size_t Value = (this->*NextNumber) ();
//ListData[Value] = SalesRef;
//if the above code is utilised instead, everything works fine
    ListData[ (this->*NextNumber) () ] = SalesRef; //POINT OF INTEREST TWO
}

inline int List::GetCopy(size_t Pos) {
    return ListData[Pos];
}

I normally don't post, but google extensively. I ended up installing and running valgrind, which gave read and write errors at Point of Interest One when Point of Interest Two was used. However, when Point of Interest Two was commented out and the commented lines were used, no problems were given.
The problem only arises after 128 iterations, meaning it doubles to 64 and 128 correctly as well as deleted the arrays correctly.
Also, as a note, the code ran perfectly fine on Windows compiled with g++.
I tried to reproduce the error using a separate class, but it worked perfectly fine.
Again, I know I should use the standard containers (and I will) but I like to understand everything and the fact that I can't figure this out is extremely annoying. Coupled with the fact that I can't even reproduce it and had to copy this incomplete and badly designed code just makes it worse. Thanks for the help in advance!
Minor edit, if it's really hard to read I'll add comments and try to clean the code up without breaking (well, fixing, rather) it. The OSes it was tested on was Windows 7 with mingw (which worked) and Debian with g++ (which only worked with the commented lines uncommented).

A: The problem with the statement
ListData[ (this->*NextNumber) () ] = SalesRef; //POINT OF INTEREST TWO

is that there's no sequence point between fetching the value of the field ListData and calling the member function pointed at by NextNumber.  So the compiler is perfectly happy doing that load before the function call and then doing the indexing off of it after the call.  However, that call may result in reallocating ListData, so the pointer it got from before the call is now dangling (it points at the just deleted array) and bad things happen.
With the commented out code, you force the function call to occur before the fetch of ListData, so that fetch will always get the right value after the resize reallocation.


text:
Q: Why only some of Bootstrap Vue icons work in a vue app using the latest Bootstrap Vue? I have installed Bootstrap Vue using the instructions here:
https://bootstrap-vue.org/docs/icons
I am on the latest version of each dependency:
"bootstrap": "^5.2.0",
"bootstrap-icons": "^1.8.1",
"bootstrap-vue": "^2.22.0",

In my src/main.js I am importing Bootstrap and the IconsPlugin like this, as directed:
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

When I try to use <b-icon icon="send" /> the icon is blank. However if I use something like <b-icon icon="menu-up" /> that one works, and displays as expected.
It seems like only some icons are working, not all though. I see these packages in my node_modules folder:

Also, looking in the file here /node_modules/bootstrap-vue/src/icons/icons.js I do not see anything for the send icon.
Is Bootstrap Vue configured properly? Is the bootstrap-vue icons.js file somehow overwriting the bootstrap-icons module, since that js file does not have many of the newer icons found here?
Not sure what I am missing here, I followed exactly like they instructed.

A: From the Bootstrap Vue link you posted:

Bootstrap Icons v1.5.0 were added in BootstrapVue v2.22.0.

"send" icon was added in 1.7.0.

A: The bootstrap-vue docs has an icon explorer section you can search for available icons.  Searching for "send" shows No matching icons found. Try searching again. It appears you're trying to use an icon that isn't available.


text:
Q: Need help in scala regex - Not able to fetch matched string by name in Scala regex I have customized apache dispatcher access logs that I need to parse in spark scala. For this I have written a sample code but I'm not able to get the matching group by name. In my logs some of the fields are optional like cookies so I want a stable way to get the matcher regex by name rather than by its sequence number.
Sample logs:
import scala.util.matching.Regex
case class LogRecord( date: String, time: String, host: String, xForward: String, user: String, method: String, statusCode: String, resTime: String, resBytes: String, referer: String, userAgent: String, cookies: String, cookies2: String, request: String, protocol: String, path: String)

object Logs  extends Serializable {

val  PATTERN = """(date)*=?\"*(?<date>(\S*))\"*\s*(time)*=?\"*(?<time>(\S*))\"*\s*(host1)*=?\"*(?<host>(\S*))\"*\s*x-forward=\"*(?<xForward>(?:\d+\.){3}\d+(?:,\s*(?:\d+\.){3}\d+)*|-)\"*\s*(user)*=?\"*(?<user>([^ ]*))\"*\s*(method)*=?\"*(?<method>(\S*))\"*\s*(status_code)*=?\"*(?<statusCode>(\S*))\"*\s*(res_time)*=?\"*(?<resTime>(\S*))\"*\s*(res_bytes)*=?\"*(?<resBytes>(\S*))\"*\s*(ref)*=?\"*(?<referer>[^\"]*)\"*\s*(ua)*=?\"*(?<userAgent>[^\"]*)\"*\s*\"*(?<cookies>[^\"]*)\"*\s*\"*(?<cookies2>[^\"]*)\"*\s*\"*(?<cookies3>[^\"]*)\"*\s*\"*(?<request>[^\"]*)\"*\s(proto)*=?\"*(?<protocol>(\S*))\"*\s*(path)*=?\"*(?<path>(\S*))\"*\s*""".r

def parseLogLine(log: String): LogRecord = {
      try {
        val res = PATTERN.findFirstMatchIn(log)

        if (res.isEmpty) {
          println("Rejected Log Line: " + log)
          LogRecord("-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1", "-1")
        }
        else {
          val m = res.get

          // NOTE:   HEAD does not have a content size.
          if (m.group("date").equals("-")) {
            LogRecord(m.group("date"), m.group("time"), m.group("host"), m.group("xForward"),
              m.group("user"), m.group("method"), m.group("statusCode"), m.group("resTime"), m.group("resBytes"), m.group("referer"),
              m.group("userAgent"),m.group("cookies"),m.group("cookies2"),m.group("request"),m.group("protocol"),m.group("path"))
          }
          else {
              LogRecord(m.group("date"), m.group("time"), m.group("host"), m.group("xForward"),
              m.group("user"), m.group("method"), m.group("statusCode"), m.group("resTime"), m.group("resBytes"), m.group("referer"),
              m.group("userAgent"),m.group("cookies"),m.group("cookies2"),m.group("request"),m.group("protocol"),m.group("path"))
          }
        }
      } catch
      {
        case e: Exception =>
          LogRecord("-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2", "-2")
      }
    }

-----------------START----------------------
date="12-16-2016" time="02:00:02.1481871602" host1="192.96.2.120" x-forward="192.267.186.196" user="-"  method="POST" status_code="301" res_time="1108" res_bytes="266" ref="-" ua="Microsoft Office/16.0 (Windows NT 6.1; Microsoft Outlook 16.0.7426; Pro`enter code here`)" "OutlookSession=\"{3975F011-1D66-4540-BF7A-9FF0EDD5B572}\"; AKCounty=; AKAreacode=; AKCity=HONGKONG; AKRegioncode=; AKZip=; AKCountry=HK; BIGipServertestserver.test.com_443=838938378.36895.0000; BIGipServertestserver.test.com=570502410.36895.0000; TLTUID=76D578D8C35C10C39C7CBC55A6B7903E; TLTSID=76D578D8C35C10C39C7CBC55A6B7903E" "POST /autodiscover/autodiscover.xml HTTP/1.1" proto=HTTP/1.1 path=/autodiscover/autodiscover.xml
date="12-16-2016" time="02:00:02.1481871602" host1="192.96.2.120" x-forward="-" user="-"  method="GET" status_code="200" res_time="39449" res_bytes="62444" ref="-" ua="Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)" "-" "GET /us/en/home.html HTTP/1.1" proto=HTTP/1.1 path=/content/base/us/en/home.html
date="12-16-2016" time="02:00:03.1481871603" host1="192.96.2.120" x-forward="192.267.186.196" user="-"  method="POST" status_code="301" res_time="694" res_bytes="266" ref="-" ua="Microsoft Office/15.0 (Windows NT 6.1; Microsoft Outlook 15.0.4875; Pro)" "OutlookSession=\"{1CD60224-8A1F-4382-A7C9-2002BBB6E11B}\"" "POST /autodiscover/autodiscover.xml HTTP/1.1" proto=HTTP/1.1 path=/autodiscover/autodiscover.xml
----------------- END ----------------------


text:
Q: Is $\mathbb{E}\exp \left( k \int_0^T B_t^2 \, dt \right)<\infty$ for small $k>0$? Suppose that $B$ is a Brownian motion. Does it hold that
\begin{equation}
\mathbb{E}\left[\exp\left(k\int_0^T[B(t)]^{2}\,dt\right)\right] <\infty\text{ ?}
\end{equation}
for some positive constant $k$?
my idea: I think that $\int_{0}^{T}[B(t)]^{2}dt$ is actually a Normal random variable $X\sim N(\frac{T^{2}}{2},\sigma(T))$ where $\sigma(T)$ is some function of $T$. Then, we know that $\mathbb{E}[\exp(\theta X)]$ is finite for such $X$. Am I correct?

A: Obviously,
$$\int_0^T B_t^2 \, dt \leq T \cdot \sup_{t \leq T} B_t^2$$
Since
$$\sup_{t \leq T} B_t^2 \leq \left(\sup_{t \leq T} B_t \right)^2 + \left( \inf_{t \leq T} B_t \right)^2$$
and
$$\sup_{t \leq T} B_t \sim - \inf_{t \leq T} B_t \sim |B_T|$$
(this is a direct consequence of the reflection principle), we get by the Cauchy-Schwarz inequality
$$\begin{align*} \mathbb{E}\exp \left(k \int_0^T B_t^2 \, dt \right) &\leq \sqrt{\mathbb{E}\exp \left(2kT \left[ \sup_{t \leq T} B_t \right]^2 \right)} \sqrt{\mathbb{E}\exp \left(2kT \left[ \inf_{t \leq T} B_t \right]^2 \right)}\\ &= \mathbb{E}\exp \left(2kT B_T^2 \right). \end{align*}$$
Finally, as $B_T \sim N(0,T)$, we observe that
$$\mathbb{E}\exp (2kT B_T^2) = \int_{\mathbb{R}} e^{2kT x^2} \frac{1}{\sqrt{2\pi T}} \exp \left(- \frac{x^2}{2T} \right) \, dx$$
is finite if $2k T< \frac{1}{2T}$, i.e. if $k < \frac{1}{4T^2}$.

A: I was confronted to a similar problem, here's one possible solution
\begin{equation}
\mathbb{E}\left[\exp\left(k\int_0^T[B(t)]^{2}\,dt\right)\right] <\infty\text{ ?}
\end{equation}
First of all, we introduce the following sequence of process
\begin{equation}
\ B_{t}^{n}= \sum_{i=0}^{n}\sqrt\lambda_{i}*\phi_{i}*\eta_{i}
\end{equation}
where
\begin{equation}
\ \eta_{i} \sim N(0,1)
\\
\ \phi_{i}=\sqrt2\sin((i+\frac{1}{2})\pi*t)
\\
\ \lambda_{i} = \frac{4}{\pi^2}\frac{1}{(2i+1)^{2}}
\end{equation}
We will show that this sequence of process is a representation of the brownian motion on [0;1].
Then thanks to a change in variables and the invariance property of the brownian motion it will become "easier" to calcul the expectation.
This sequence of process is converging, to show that you can show that it is a Cauchy sequence in . We denote X_t that limit.
You can easily show that X_t is a gaussian process. Or a gaussian process is characterized by its covariance function and its expected function.
Thanks to the Theorem of Mercer you can calculate the covariance function and the calculation of the expected function is very simple because it is the constante 0.
\begin{equation}
K(s,t)=cov(X_{t},X_{s}) = min(s,t)
\\
E(t)= \mathbb{E}[X_{t}]=0
\end{equation}
\begin{equation}
\ B_{t}^{n}= \sum_{i=0}^{\infty}\sqrt\lambda_{i}*\phi_{i}*\eta_{i}\text{ is a representation of the brownian motion on [0;1]}
\end{equation}
We can use that representation to calculate
\begin{equation}
\int_{0}^{T}[B(t)]^{2}dt= T^{2}*\int_{0}^{1} [\frac{B_{T*t}}{\sqrt{T}}]^{2}dt
\\
\frac{B_{T*t}}{\sqrt{T}}\text{is a brownian motion, it is just the invariance by expansion of time}
\end{equation}
\begin{equation}
\int_{0}^{T}[B(t)]^{2}dt= \sum_{i=0}^{\infty}\lambda_{i}\eta_{i}^2\
\end{equation}
Now you "just" have to calculate the Laplace transformation of a square normal law which is painful (it is basically the calculation of a Laplace transformation for a random variable following a chi2 law)
\begin{equation}
\mathbb{E}\left[\exp\left(k\int_0^T[B(t)]^{2}\,dt\right)\right] = \prod_{i=0}^{\infty}\mathbb{E}[exp(T^{2}*k*\lambda_{i}*\eta_{i}^2)]
\end{equation}
If I have made any mistake or if you need more explanations on some particular points don't hesitate


text:
Q: Ejecutar script con venv y python Quiero ejecutar un script en python cada 5 minutos con crontab, y tengo el "problema" o la complicación de que pertenece a un entorno virtual y usa python.
Si ejecuto el script directamente, me lo lanza bien, pero si por el contrario, lo meto en el crontab, da error.
He puesto en el crontab que me lo envié directamente a un archivo.log, pero no consigo obtener nada. También le he dado a los script permisos totales con 777 pero ni aún asi.
Dejo mi configuración de los archivos:
*/5 * * * * /home/laura/Descargas/scrapper/python.sh >> /var/log/pypypypy.log 2>&1

Contenido de python.sh:
#!/bin/bash
. /home/laura/Descargas/scrapper/venv/bin/activate
python3 /home/laura/Descargas/scrapper/scrapper.py

Como digo, si lo ejecuto por separado, lo hace bien, con crontab no, ademas el archivo log me lo da vacío.
Muchas gracias por adelantado

A: Primero sería interesante que vieramos los logs del servicio cron.
Para esto no me sé muchos trucos. Dicen que uno es utilizar:
$ grep CRON /var/log/syslog

O su equivalente en otras distros como CentOS.
Pero su información me es poco clara.
Lo que yo hago para ver los errores es instalar postfix y mailutils:
$ sudo apt install -y postfix mailutils

postfix me parece que es un agente de transferencia de correos, y mailutils te permite tener un cliente de correos.
Esto lo hacemos porque cron suele enviar el estatus de las tareas por correo.
Una vez que tenemos ambos programas instalados, podemos correr un simple mail:
➜  ~ mail
"/var/mail/cuau": 6 messages 3 new 3 unread
 U   1 Cron Daemon        Wed Apr 20 23:57  22/976   Cron <cuau@cuau-1> touc ~/crontarch
 U   2 Cron Daemon        Wed Apr 20 23:58  21/951   Cron <cuau@cuau-1> touc ~/crontarch
 U   3 Cron Daemon        Wed Apr 20 23:59  21/951   Cron <cuau@cuau-1> touc ~/crontarch
>N   4 Cron Daemon        Thu Apr 21 00:00  19/932   Cron <cuau@cuau-1>
?

Y seleccionas el numero del mail. Ya adentro del mail podrás leer los errores:
From: root@cuau-1.us-central1-a.c.test-training-301202.internal (Cron Daemon)
To: cuau-test@cuau-1.us-central2-a.c.test-training-301202.internal
Subject: Cron <cuau-test@cuau-1> touc ~/bad_py.py
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/cuau-test>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=cuau-test>
Message-Id: <20220421004201.27C2562648@cuau-1.us-central1-a.c.test-training-301202.internal>
Date: Thu, 21 Apr 2022 00:42:01 +0000 (UTC)
X-IMAPbase: 1650501764 3
Status: O
X-UID: 2

/bin/sh: 1: touc: not found

Usualmente el punto de esos errores que tienes es que no tienes inicializado el ambiente y el PATH en tu script. Es decir, no es lo mismo que tu lo corras con tu shell y todo el ambiente preparado con las configuraciones de los archivos como ´~/.bashrc´, que el servicio de CRON sin el ambiente necesariamente preparado.
Podriamos tratar de adivinar y añadir esto a tu script:
#!/bin/bash

export PATH=$PATH:/usr/local/bin
. ~/.bashrc

. /home/laura/Descargas/scrapper/venv/bin/activate
python3 /home/laura/Descargas/scrapper/scrapper.py