问:
Pyhton Link Redirected
I am trying to send mail from a site with pyhton. However, on the page I will send an e-mail, a 'page not found' warning appears. After passing this warning, I want it to take me back to the link and send the e-mail. How can I provide this redirect?
Normally I pull the connections from the database. However, I sent you a link as an example.
I told it to take me to the link when the content is 200, but it didn't, 'Request was not redirected' turning. I just want to return to the link I specified. I applied the answers in similar questions but did not get any results.

I want to open the same link without closing the driver

```<code>   ad_link = 'https://suchen.mobile.de/fahrzeuge/details.html?id=357845895&adLimitation=ONLY_FSBO_ADS&cn=DE&damageUnrepaired=NO_DAMAGE_UNREPAIRED&daysAfterCreation=1&grossPrice=true&isSearchRequest=true&makeModelVariant1.makeId=20100&makeModelVariant1.modelId=22&maxMile'
</code>```

```<code>     headers = {
            'Accept': 'application/json',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 OPR/89.0.4447.64',
            #'Referer': 'https://suchen.mobile.de/fahrzeuge/search.html?dam=0&isSearchRequest=true&ref=quickSearch&sb=rel&vc=Car',
        }
        response = requests.get(ad_link, headers=headers,  allow_redirects=True)
        #, allow_redirects=True
        print(response.history)
        #print(ad_link)

        if response.history == 200:
            ic("Request was redirected")

            for resp in response.history:
                print(resp.status_code, resp.url)
            ic("Final destination:")
            ic(response.status_code, response.ad_link)
            ic("Mail Sending")
            test.implicitly_wait(3)
            test.find_element(By.XPATH,"/html/body/div[6]/div/div[2]/div[2]/div[2]/aside/div[1]/div/div[4]/div/span").click()
            test.implicitly_wait(1)
            eMl = test.find_element(By.XPATH,"/html/body/div[2]/div[1]/div[1]/div[2]/div/div[1]/form/div[1]/div/input")
            test.implicitly_wait(3)
            eMl.click()
            time.sleep(1)
            eMl.send_keys("verkauf.bellic1012@gmail.com")
            time.sleep(3)
            passw = WebDriverWait(test, 5).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/div[1]/div[2]/div/div[1]/form/div[2]/div/input")))
            test.implicitly_wait(3)
            passw.click()
            time.sleep(1)
            test.find_element(By.XPATH, '/html/body/div/div[1]/div/div[2]/a').click()
            time.sleep(10)

        else:
            ic("Request was not redirected")
            ic(response)
        time.sleep(sleep_time)
</code>```

Title: Pyhton Link Redirected

Body:
I am trying to send mail from a site with pyhton. However, on the page I will send an e-mail, a 'page not found' warning appears. After passing this warning, I want it to take me back to the link and send the e-mail. How can I provide this redirect?
Normally I pull the connections from the database. However, I sent you a link as an example.
I told it to take me to the link when the content is 200, but it didn't, 'Request was not redirected' turning. I just want to return to the link I specified. I applied the answers in similar questions but did not get any results.

I want to open the same link without closing the driver

   ad_link = 'https://suchen.mobile.de/fahrzeuge/details.html?id=357845895&adLimitation=ONLY_FSBO_ADS&cn=DE&damageUnrepaired=NO_DAMAGE_UNREPAIRED&daysAfterCreation=1&grossPrice=true&isSearchRequest=true&makeModelVariant1.makeId=20100&makeModelVariant1.modelId=22&maxMile'

     headers = {
            'Accept': 'application/json',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 OPR/89.0.4447.64',
            #'Referer': 'https://suchen.mobile.de/fahrzeuge/search.html?dam=0&isSearchRequest=true&ref=quickSearch&sb=rel&vc=Car',
        }
        response = requests.get(ad_link, headers=headers,  allow_redirects=True)
        #, allow_redirects=True
        print(response.history)
        #print(ad_link)

        if response.history == 200:
            ic("Request was redirected")

            for resp in response.history:
                print(resp.status_code, resp.url)
            ic("Final destination:")
            ic(response.status_code, response.ad_link)
            ic("Mail Sending")
            test.implicitly_wait(3)
            test.find_element(By.XPATH,"/html/body/div[6]/div/div[2]/div[2]/div[2]/aside/div[1]/div/div[4]/div/span").click()
            test.implicitly_wait(1)
            eMl = test.find_element(By.XPATH,"/html/body/div[2]/div[1]/div[1]/div[2]/div/div[1]/form/div[1]/div/input")
            test.implicitly_wait(3)
            eMl.click()
            time.sleep(1)
            eMl.send_keys("verkauf.bellic1012@gmail.com")
            time.sleep(3)
            passw = WebDriverWait(test, 5).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[2]/div[1]/div[1]/div[2]/div/div[1]/form/div[2]/div/input")))
            test.implicitly_wait(3)
            passw.click()
            time.sleep(1)
            test.find_element(By.XPATH, '/html/body/div/div[1]/div/div[2]/a').click()
            time.sleep(10)

        else:
            ic("Request was not redirected")
            ic(response)
        time.sleep(sleep_time)


来源: stackexchange

问:
Getting error CredentialsProviderError: Could not load credentials from any providers
Getting CredentialsProviderError: Could not load credentials from any providers while accessing createJobCommand to create a job using Elastic transcoder in Node js

```<code>import { ElasticTranscoderClient, CreateJobCommand } from "@aws-sdk/client-elastic-transcoder";
import { videoUpload } from '../../services/s3fileupload.js'

// const client = new ElasticTranscoderClient({ region: process.env.AWS_REGION });
const client = new ElasticTranscoderClient({ region: process.env.AWS_REGION,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACESS_KEY,
  InputBucket: process.env.PIPELINE_INPUT_BUCKET,
  OutputBucket: process.env.AWS_S3_OUTPUT_BUCKET_NAME,
  Role: process.env.IAM_ROLE_ARN });
export const fileUpload = async(req, res) => {
    try {
        const file = req.files.video;
        const result = await videoUpload(file)
        const params = {
          PipelineId: process.env.PIPELINE_ID,
          Input: {
            Key: result.key,
            Container: "MP4"
          },
          Output: {
            Key: `${process.env.AWS_S3_BUCKET_NAME}outputs/${result.Key}`,
            PresetId: process.env.PRESET_ID
          }
        }
        const command = new CreateJobCommand(params);
        console.log('...commad', command);
        await client.send(command).then((data) => {
            res.json({
                status: 'success', data
            })
        },
        (error) => {
            console.log('error', error);
            return res.json({status: 'error'})
        })

    } catch(error) {
        console.log('error', error);
        res.json({
            status: 'failed'
        })
    }
}
</code>```

Can anyone help me on how to solve this?I want to perform video conversion using elastic transcoder in Node js.

ContentLicense: CC BY-SA 4.0

Body:
Getting CredentialsProviderError: Could not load credentials from any providers while accessing createJobCommand to create a job using Elastic transcoder in Node js

import { ElasticTranscoderClient, CreateJobCommand } from "@aws-sdk/client-elastic-transcoder";
import { videoUpload } from '../../services/s3fileupload.js'

// const client = new ElasticTranscoderClient({ region: process.env.AWS_REGION });
const client = new ElasticTranscoderClient({ region: process.env.AWS_REGION,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACESS_KEY,
  InputBucket: process.env.PIPELINE_INPUT_BUCKET,
  OutputBucket: process.env.AWS_S3_OUTPUT_BUCKET_NAME,
  Role: process.env.IAM_ROLE_ARN });
export const fileUpload = async(req, res) => {
    try {
        const file = req.files.video;
        const result = await videoUpload(file)
        const params = {
          PipelineId: process.env.PIPELINE_ID,
          Input: {
            Key: result.key,
            Container: "MP4"
          },
          Output: {
            Key: `${process.env.AWS_S3_BUCKET_NAME}outputs/${result.Key}`,
            PresetId: process.env.PRESET_ID
          }
        }
        const command = new CreateJobCommand(params);
        console.log('...commad', command);
        await client.send(command).then((data) => {
            res.json({
                status: 'success', data
            })
        },
        (error) => {
            console.log('error', error);
            return res.json({status: 'error'})
        })

    } catch(error) {
        console.log('error', error);
        res.json({
            status: 'failed'
        })
    }
}

Can anyone help me on how to solve this?I want to perform video conversion using elastic transcoder in Node js.


问:
Spring Security 6.0.1 custom AuthenticationProcessingFilter authentication success but won't redirect to index page
I'm using Spring Boot 3.0.1 with Spring Security 6.0.1 to build a web service.

My problem is I can't login to the server after adding a custom AuthenticationProcessingFilter to HttpSecurity.

When debugging the program, I found that the authenticate method was able to return AuthenticationToken in my custom AuthenticationProvider. After the authenticate, it won't redirect to the index page but still go to the login page.

I've tried to remove the custom AuthenticationProcessingFilter, it works fine to login/logout.

My codes:

SecurityConfig

```<code>@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Autowired
    private MyUsernamePasswordAuthenticationProvider myUsernamePasswordAuthenticationProvider;

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder =
                http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(myUsernamePasswordAuthenticationProvider);
        return authenticationManagerBuilder.build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.addFilterBefore(myUsernamePasswordAuthenticationFilter(http), UsernamePasswordAuthenticationFilter.class);// Works fine if comment this line.
        //http.addFilterBefore(myMobilephoneAuthenticationFilter(http), UsernamePasswordAuthenticationFilter.class);

        http.csrf().disable()
                .authorizeRequests((authorize) ->
                        authorize.requestMatchers("/login/**").permitAll()
                                .anyRequest().authenticated()
                ).formLogin(
                        form -> form
                                .loginPage("/login")
                                .loginProcessingUrl("/login/submit")
                                .defaultSuccessUrl("/index")
                                .permitAll()
                ).logout(
                        logout -> logout
                                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                                .logoutSuccessUrl("/login?msg=logout")
                                .permitAll()
                );
        return http.build();
    }

    @Bean
    public MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter(HttpSecurity httpSecurity) throws Exception {
        MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();
        filter.setAuthenticationManager(authManager(httpSecurity));
        filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/index"));
        filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?msg=invalid_simple"));
        filter.setFilterProcessesUrl("/login/submit");

        return filter;
    }
}
</code>```

MyUsernamePasswordAuthenticationProvider

```<code>@Component
public class MyUsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserService myUserService;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public Authentication authenticate(Authentication authentication) {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails dbUser = myUserService.loadUserByUsername(name);

        if (passwordEncoder().matches(password, dbUser.getPassword())) {
            var authorities = List.of(new SimpleGrantedAuthority("ROLE_USER"));
            // use the credentials
            // and authenticate against the third-party system
            return new MyUsernamePasswordAuthenticationToken(
                    name, password, authorities);
        } else {
            throw new BadCredentialsException("Wrong password");
//            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(MyUsernamePasswordAuthenticationToken.class);
    }
}
</code>```

MyUsernamePasswordAuthenticationFilter

```<code>Same as org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
</code>```

Body:
I'm using Spring Boot 3.0.1 with Spring Security 6.0.1 to build a web service.

My problem is I can't login to the server after adding a custom AuthenticationProcessingFilter to HttpSecurity.

When debugging the program, I found that the authenticate method was able to return AuthenticationToken in my custom AuthenticationProvider. After the authenticate, it won't redirect to the index page but still go to the login page.

I've tried to remove the custom AuthenticationProcessingFilter, it works fine to login/logout.

My codes:

SecurityConfig

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Autowired
    private MyUsernamePasswordAuthenticationProvider myUsernamePasswordAuthenticationProvider;

    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder =
                http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(myUsernamePasswordAuthenticationProvider);
        return authenticationManagerBuilder.build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.addFilterBefore(myUsernamePasswordAuthenticationFilter(http), UsernamePasswordAuthenticationFilter.class);// Works fine if comment this line.
        //http.addFilterBefore(myMobilephoneAuthenticationFilter(http), UsernamePasswordAuthenticationFilter.class);

        http.csrf().disable()
                .authorizeRequests((authorize) ->
                        authorize.requestMatchers("/login/**").permitAll()
                                .anyRequest().authenticated()
                ).formLogin(
                        form -> form
                                .loginPage("/login")
                                .loginProcessingUrl("/login/submit")
                                .defaultSuccessUrl("/index")
                                .permitAll()
                ).logout(
                        logout -> logout
                                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                                .logoutSuccessUrl("/login?msg=logout")
                                .permitAll()
                );
        return http.build();
    }

    @Bean
    public MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter(HttpSecurity httpSecurity) throws Exception {
        MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();
        filter.setAuthenticationManager(authManager(httpSecurity));
        filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/index"));
        filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?msg=invalid_simple"));
        filter.setFilterProcessesUrl("/login/submit");

        return filter;
    }
}

MyUsernamePasswordAuthenticationProvider

@Component
public class MyUsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserService myUserService;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public Authentication authenticate(Authentication authentication) {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails dbUser = myUserService.loadUserByUsername(name);

        if (passwordEncoder().matches(password, dbUser.getPassword())) {
            var authorities = List.of(new SimpleGrantedAuthority("ROLE_USER"));
            // use the credentials
            // and authenticate against the third-party system
            return new MyUsernamePasswordAuthenticationToken(
                    name, password, authorities);
        } else {
            throw new BadCredentialsException("Wrong password");
//            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(MyUsernamePasswordAuthenticationToken.class);
    }
}

MyUsernamePasswordAuthenticationFilter

Same as org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter


问:
QT:Why tooltip set by qstylesheet is covered when the enabled property of A QAction object changes?
I have one QToolBar with two QActions, defined in .ui file.

```<code>     <widget class="QToolBar" name="mainToolBar">
      <action name="reviewAct">
       <property name="text">
        <string>Review</string>
       </property>
       <property name="toolTip">
        <string>Review Job</string>
       </property>
      </action>
      <action name="enableAct">
       <property name="text">
        <string>Enable</string>
       </property>
       <property name="toolTip">
        <string>Enable b</string>
       </property>
      </action>
      <addaction name="reviewAct"/>
      <addaction name="enableAct"/>
     </widget>
</code>```

The tooltip of reviewAct is "Review Job". The enableAct is for setting reviewAct enable or not.

```<code>    ui.enableAct->setCheckable(true);
    connect(ui.enableAct, SIGNAL(triggered(bool)), ui.reviewAct, SLOT(setEnabled(bool)));
</code>```

Then set stylesheet below:

```<code>QToolButton[text="Review"] {
  qproperty-shortcut: "Ctrl+Shift+Return";
  qproperty-toolTip: "Review Job (Ctrl+Shift+Return)";
  background-color: red; border: none;
  }
</code>```

The tooltip is changed to "Review Job (Ctrl+Shift+Return)". Everything is ok until ui.enableAct is triggered, the tooltip will reset to "Review Job". It is not reasonable and I don't know why.

enter image description here

Why tooltip set by qstylesheet is covered?

Body:
I have one QToolBar with two QActions, defined in .ui file.

     <widget class="QToolBar" name="mainToolBar">
      <action name="reviewAct">
       <property name="text">
        <string>Review</string>
       </property>
       <property name="toolTip">
        <string>Review Job</string>
       </property>
      </action>
      <action name="enableAct">
       <property name="text">
        <string>Enable</string>
       </property>
       <property name="toolTip">
        <string>Enable b</string>
       </property>
      </action>
      <addaction name="reviewAct"/>
      <addaction name="enableAct"/>
     </widget>

The tooltip of reviewAct is "Review Job". The enableAct is for setting reviewAct enable or not.

    ui.enableAct->setCheckable(true);
    connect(ui.enableAct, SIGNAL(triggered(bool)), ui.reviewAct, SLOT(setEnabled(bool)));

Then set stylesheet below:

QToolButton[text="Review"] {
  qproperty-shortcut: "Ctrl+Shift+Return";
  qproperty-toolTip: "Review Job (Ctrl+Shift+Return)";
  background-color: red; border: none;
  }

The tooltip is changed to "Review Job (Ctrl+Shift+Return)". Everything is ok until ui.enableAct is triggered, the tooltip will reset to "Review Job". It is not reasonable and I don't know why.

enter image description here

Why tooltip set by qstylesheet is covered?


问:
Is it possible to add tabs inside another tabs in android?
I have an application which have 3 tabs on the top, I want inside the second tab to add another 5 tabs on the bottom.

is that possible? if yes can you show how?


问:
How to mock History in Angular jasmine testing?
I'm new in testing environment and Angular itself, I'm trying to write tests for a project that is already started.
Now I'm getting this error when I try to setup and run the test:
TypeError: Cannot read properties of null (reading 'data')

create-organization.component.ts

```<code>export class CreateOrganizationComponent implements OnInit {
  summaryFormValues: any = {};

  tabConfig!: TabStepperModel[];

  organizationData: any;

  constructor(
    private territoryService: TerritoryService,
    private organizationService: OrganizationService,
    private countryListService: CountryHelperService,
    private navService: NavigationService,
    private activeRoute: ActivatedRoute,
    private journeyService: JourneyService,
    private spinnerService: SpinnerService
  ) {}

  ngOnInit(): void {
    this.journeyService.clearData()
    const historyState = history.state.data ? history.state.data.data : null;
    if (historyState) {
      const createOrganizationData: CreateOrganizationModel = {
        basic: historyState.data.basic,
        organizationalContact: historyState.data.organizationalContact,
        extraDetails: historyState.data.extraDetails,
      };
      const journeyData = { ...createOrganizationData, isEdit: true };
      this.journeyService.setData(journeyData);
    }
  }
}
</code>```

create-organization.component.spec.ts

```<code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { getJourneyServiceSpyObj } from '../../../../common/testing/services/journey.service.test';
import { getTerritoryServiceSpyObj } from '../../../../common/testing/services/territory.service.test';
import { getNavigationServiceSpyObj } from '../../../../common/testing/services/navigation.service.test';
import { getSpinnerServiceSpyObj } from '../../../../common/testing/services/spinner.service.test';
import { TerritoryService } from '../../../cipfa-template/services/territory.service';
import { JourneyService } from '../../../shared/services/journey.service';
import { NavigationService } from '../../../shared/services/navigation.service';
import { SpinnerService } from '../../../shared/services/spinner.service';
import { getHttpClientSpyObj } from 'apps/client/src/app/common/testing/angular/http-client.test';

import { CreateOrganizationComponent } from './create-organization.component';
import { HttpClient } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';

fdescribe('CreateOrganizationComponent', () => {
  let component: CreateOrganizationComponent;
  let fixture: ComponentFixture<CreateOrganizationComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [CreateOrganizationComponent],
      providers: [
        { provide: NavigationService, useValue: getNavigationServiceSpyObj() },
        { provide: SpinnerService, useValue: getSpinnerServiceSpyObj() },
        { provide: JourneyService, useValue: getJourneyServiceSpyObj() },
        { provide: TerritoryService, useValue: getTerritoryServiceSpyObj() },
        { provide: HttpClient, useValue: getHttpClientSpyObj() },
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(CreateOrganizationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

Body:
I'm new in testing environment and Angular itself, I'm trying to write tests for a project that is already started.
Now I'm getting this error when I try to setup and run the test:
TypeError: Cannot read properties of null (reading 'data')

create-organization.component.ts

export class CreateOrganizationComponent implements OnInit {
  summaryFormValues: any = {};

  tabConfig!: TabStepperModel[];

  organizationData: any;

  constructor(
    private territoryService: TerritoryService,
    private organizationService: OrganizationService,
    private countryListService: CountryHelperService,
    private navService: NavigationService,
    private activeRoute: ActivatedRoute,
    private journeyService: JourneyService,
    private spinnerService: SpinnerService
  ) {}

  ngOnInit(): void {
    this.journeyService.clearData()
    const historyState = history.state.data ? history.state.data.data : null;
    if (historyState) {
      const createOrganizationData: CreateOrganizationModel = {
        basic: historyState.data.basic,
        organizationalContact: historyState.data.organizationalContact,
        extraDetails: historyState.data.extraDetails,
      };
      const journeyData = { ...createOrganizationData, isEdit: true };
      this.journeyService.setData(journeyData);
    }
  }
}

create-organization.component.spec.ts

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { getJourneyServiceSpyObj } from '../../../../common/testing/services/journey.service.test';
import { getTerritoryServiceSpyObj } from '../../../../common/testing/services/territory.service.test';
import { getNavigationServiceSpyObj } from '../../../../common/testing/services/navigation.service.test';
import { getSpinnerServiceSpyObj } from '../../../../common/testing/services/spinner.service.test';
import { TerritoryService } from '../../../cipfa-template/services/territory.service';
import { JourneyService } from '../../../shared/services/journey.service';
import { NavigationService } from '../../../shared/services/navigation.service';
import { SpinnerService } from '../../../shared/services/spinner.service';
import { getHttpClientSpyObj } from 'apps/client/src/app/common/testing/angular/http-client.test';

import { CreateOrganizationComponent } from './create-organization.component';
import { HttpClient } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';

fdescribe('CreateOrganizationComponent', () => {
  let component: CreateOrganizationComponent;
  let fixture: ComponentFixture<CreateOrganizationComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [CreateOrganizationComponent],
      providers: [
        { provide: NavigationService, useValue: getNavigationServiceSpyObj() },
        { provide: SpinnerService, useValue: getSpinnerServiceSpyObj() },
        { provide: JourneyService, useValue: getJourneyServiceSpyObj() },
        { provide: TerritoryService, useValue: getTerritoryServiceSpyObj() },
        { provide: HttpClient, useValue: getHttpClientSpyObj() },
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(CreateOrganizationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


问:
How to use events (Chrome-Developer-Tools) using Selenium with Python as a thread?

My current code is like that:

# Note: driver variable allready initialzed (Chrome)

import trio # async library that selenium uses
import requests
from PIL import Image
from io import BytesIO

def show_image(url):
    try:
        response = requests.get(url)
        img = Image.open(BytesIO(response.content))
        img.show()
    except Exception as e:
        print(e)

def intercept(event, devtools):
    return devtools.fetch.fail_request(request_id=event.request_id,error_reason=devtools.network.ErrorReason.CONNECTION_REFUSED)

async def at_event(listener, connection, intercept):
    session, devtools = connection.session, connection.devtools
    async for event in listener:

        print({"frame_id": event.frame_id, "url": event.request.url})
        #show_image(event.request.url)
        await trio.sleep(0.0001)
        try:
            await session.execute(intercept(event=event, devtools=devtools))
            # await session.execute(devtools.fetch.fulfill_request(request_id = event.request_id, response_code=200))
            # await session.execute(devtools.fetch.continue_request(request_id=event.request_id))
        except Exception as e:
            print(e)

async def async_interceptor(pattern,main_func, intercept):
    async with driver.bidi_connection() as connection:
        session, devtools = connection.session, connection.devtools

        pattern = devtools.fetch.RequestPattern.from_json(pattern)
        await session.execute(devtools.fetch.enable(patterns =[pattern]))

        listener = session.listen(devtools.fetch.RequestPaused)
        async with trio.open_nursery() as nursery:
            nursery.start_soon(at_event,listener, connection, intercept)
            nursery.start_soon(main_func)

async def interceptor():
    await async_interceptor({"resourceType":"Image"},main, intercept)
async def main():
    driver.get("https://www.youtube.com/")

trio.run(interceptor)
```

What I want to change:

I want interceptor to be a non-blocking like in a thread, and not inside a async function

atm, the listener doesn't always get triggered, maybe because something in the async code?

In my example code, I want to intercept and fail all requests which are Images

Body:
My current code is like that:

# Note: driver variable allready initialzed (Chrome)

import trio # async library that selenium uses
import requests
from PIL import Image
from io import BytesIO

def show_image(url):
    try:
        response = requests.get(url)
        img = Image.open(BytesIO(response.content))
        img.show()
    except Exception as e:
        print(e)

def intercept(event, devtools):
    return devtools.fetch.fail_request(request_id=event.request_id,error_reason=devtools.network.ErrorReason.CONNECTION_REFUSED)

async def at_event(listener, connection, intercept):
    session, devtools = connection.session, connection.devtools
    async for event in listener:

        print({"frame_id": event.frame_id, "url": event.request.url})
        #show_image(event.request.url)
        await trio.sleep(0.0001)
        try:
            await session.execute(intercept(event=event, devtools=devtools))
            # await session.execute(devtools.fetch.fulfill_request(request_id = event.request_id, response_code=200))
            # await session.execute(devtools.fetch.continue_request(request_id=event.request_id))
        except Exception as e:
            print(e)

async def async_interceptor(pattern,main_func, intercept):
    async with driver.bidi_connection() as connection:
        session, devtools = connection.session, connection.devtools

        pattern = devtools.fetch.RequestPattern.from_json(pattern)
        await session.execute(devtools.fetch.enable(patterns =[pattern]))

        listener = session.listen(devtools.fetch.RequestPaused)
        async with trio.open_nursery() as nursery:
            nursery.start_soon(at_event,listener, connection, intercept)
            nursery.start_soon(main_func)

async def interceptor():
    await async_interceptor({"resourceType":"Image"},main, intercept)
async def main():
    driver.get("https://www.youtube.com/")

trio.run(interceptor)

What I want to change:

I want interceptor to be a non-blocking like in a thread, and not inside a async function

atm, the listener doesn't always get triggered, maybe because something in the async code?

In my example code, I want to intercept and fail all requests which are Images


问:
How to enable clustering feature using custom view annotation on mapbox android?
i have a trouble about enable clustering feature on mapbox v10 android.
I have tried to reseach on homepage but didn't find any helpful way to resolve this.
I used to create point annotation manager from AnnotationPlugin before then i can add annotationConfig into them but now i must create custom view instead.
So i don't know how to add clustering for that

Here is way to add custom annotation view into mapview.

```<code>val point = fromLngLat(
    longitude,
    latitude
)
val view = mMapView.viewAnnotationManager.addViewAnnotation(
         R.layout.custom_layout,
         viewAnnotationOptions {
              geometry(point)
              allowOverlap(true)
         }
)
</code>```

Anyone help me please? Thanks

Body:
i have a trouble about enable clustering feature on mapbox v10 android.
I have tried to reseach on homepage but didn't find any helpful way to resolve this.
I used to create point annotation manager from AnnotationPlugin before then i can add annotationConfig into them but now i must create custom view instead.
So i don't know how to add clustering for that

Here is way to add custom annotation view into mapview.

val point = fromLngLat(
    longitude,
    latitude
)
val view = mMapView.viewAnnotationManager.addViewAnnotation(
         R.layout.custom_layout,
         viewAnnotationOptions {
              geometry(point)
              allowOverlap(true)
         }
)

Anyone help me please? Thanks


问:
Granger causality test interpretation
When I ran the below code for my dataset I got the following results. I do not know how to eliminate few features based on the outcome

Code:

```<code>maxlag=12
test = 'ssr_chi2test'
def grangers_causation_matrix(data, variables, test='ssr_chi2test', verbose=False):

    df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)
    for c in df.columns:
        for r in df.index:
            test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)
            p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]
            if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')
            min_p_value = np.min(p_values)
            df.loc[r, c] = min_p_value
    df.columns = [var + '_x' for var in variables]
    df.index = [var + '_y' for var in variables]
    return df

grangers_causation_matrix(df, variables = df.columns)
</code>```

output:

The above results in the image show that AOV_x causes all other variables except for Revenue_y and ARPC_y (since p>0.05). Now I am not able to decide if i should drop AOV_x or not as it causes some and not others.

I am expecting to understand how to proceed if Granger causality test results in p values >0.05

Title: Granger causality test interpretation

Body:
When I ran the below code for my dataset I got the following results. I do not know how to eliminate few features based on the outcome

Code:

maxlag=12
test = 'ssr_chi2test'
def grangers_causation_matrix(data, variables, test='ssr_chi2test', verbose=False):

    df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)
    for c in df.columns:
        for r in df.index:
            test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)
            p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]
            if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')
            min_p_value = np.min(p_values)
            df.loc[r, c] = min_p_value
    df.columns = [var + '_x' for var in variables]
    df.index = [var + '_y' for var in variables]
    return df

grangers_causation_matrix(df, variables = df.columns)

output:

The above results in the image show that AOV_x causes all other variables except for Revenue_y and ARPC_y (since p>0.05). Now I am not able to decide if i should drop AOV_x or not as it causes some and not others.

I am expecting to understand how to proceed if Granger causality test results in p values >0.05


问:
Three.JS 3D Model has different scale on different screens
I want that the scale of my 3D Model appears the same on every screen. It should depend on the screen-width, screen-height and the resolutuion. On mobile screens it should appear a bit smaller.

Here is the Code i currently have:

```<code> //add moon model
        let moonObject = new URL("/assets/Moon.glb", import.meta.url).href;
        let moon;
        const glftLoader = new GLTFLoader();
        glftLoader.load(moonObject, (gltfScene) => {
            moon = gltfScene;
            let scale = Math.min(window.innerWidth, window.innerHeight) / 6000 - 0.13;
            if (window.innerWidth < 600) {
                scale = 0.018
            }
            moon.scene.scale.set(scale, scale, scale);
            moon.scene.position.set(1, 1, 0);
            moon.scene.rotation.y = 180;
            scene.scene.add(gltfScene.scene);
        });
</code>```

This is what it tried it looks good on some screens but on others it appears too small and on some too big:

let scale = Math.min(window.innerWidth, window.innerHeight) / 6000 - 0.13;

Body:
I want that the scale of my 3D Model appears the same on every screen. It should depend on the screen-width, screen-height and the resolutuion. On mobile screens it should appear a bit smaller.

Here is the Code i currently have:

 //add moon model
        let moonObject = new URL("/assets/Moon.glb", import.meta.url).href;
        let moon;
        const glftLoader = new GLTFLoader();
        glftLoader.load(moonObject, (gltfScene) => {
            moon = gltfScene;
            let scale = Math.min(window.innerWidth, window.innerHeight) / 6000 - 0.13;
            if (window.innerWidth < 600) {
                scale = 0.018
            }
            moon.scene.scale.set(scale, scale, scale);
            moon.scene.position.set(1, 1, 0);
            moon.scene.rotation.y = 180;
            scene.scene.add(gltfScene.scene);
        });

This is what it tried it looks good on some screens but on others it appears too small and on some too big:

let scale = Math.min(window.innerWidth, window.innerHeight) / 6000 - 0.13;


问:
Trying to create new column if a particular column has blank values (interpreted as NaN in python)
I have a Dataframe name Experian_P2 which has a column 'Work_Experience'

Work_Experience column has blank values (interpreted as NaN in Python)

Now i simply want to create a new column with name 'Blank_Work_Ex' where blank rows / records in Work_Experience column are stored as Blank/NaN in Blank_Work_Ex column and non-blanks should have result There_is_Work_Ex

This is the code i am trying

```<code>**Blank_Work_Ex = []
for row in Experian_P2['Work_Experience']:
    if row.isnull() == True : Blank_Work_Ex.append('NaN')
    else: Blank_Work_Ex.append('There_is_Work_Ex')

Experian_P2['Blank_Work_Ex'] = Blank_Work_Ex**
</code>```

Body:
I have a Dataframe name Experian_P2 which has a column 'Work_Experience'

Work_Experience column has blank values (interpreted as NaN in Python)

Now i simply want to create a new column with name 'Blank_Work_Ex' where blank rows / records in Work_Experience column are stored as Blank/NaN in Blank_Work_Ex column and non-blanks should have result There_is_Work_Ex

This is the code i am trying

**Blank_Work_Ex = []
for row in Experian_P2['Work_Experience']:
    if row.isnull() == True : Blank_Work_Ex.append('NaN')
    else: Blank_Work_Ex.append('There_is_Work_Ex')

Experian_P2['Blank_Work_Ex'] = Blank_Work_Ex**


问:
Menu type display in LCD using 4x4 Keypad in Arduino
I am trying to display two menu type in 16x2 LCD display using keypad in Arduino.

Here is the code;
`#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

```<code>byte rowPins[4]={9,8,7,6};
byte colPins [4]={5,4,3,2};

char keys[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
Keypad keypad = Keypad(makeKeymap(keys),rowPins,colPins,4,4);

LiquidCrystal_I2C lcd(0x27,16,2);
boolean present = false;
boolean next = false;
boolean final = false;
String num1, num2; //
float ans;//
char op;//

//String Line1 = "                ";
//String Line2 = "                ";
//char cursors = 0;
//
////phaseshift
//char phase_value[2];
//int phase_cursor;
//int phase_index;
//char phasesign;
//
////declare function
//void Phaseshift_Fn();
//void CV_Fn();
//void CC_Fn();
//void Remote_Fn();

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.begin (16,2);

  lcd.clear();
  lcd.setCursor(0, 0); lcd.print(Line1);
  lcd.setCursor(0, 1); lcd.print(Line2);
  delay(100);

  lcd.setCursor(5,0);
  lcd.print("HELLO");
  lcd.setCursor(0,1);
  lcd.print("PRESS FWD Button");
  delay(2000);
  lcd.clear();
  delay(1000);
}

void loop() {
  char key = keypad.getKey();
  if(key == 'B'){
      lcd.setCursor(0,0);
      lcd.print("IF NO AIR BUBBLE");
      lcd.setCursor(0,1);
      lcd.print("PRESS STOP");
     }
    if(key == 'A'){
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("PRESS MODE");
      lcd.setCursor(0,1);

       switch(mode)
{
  case Startup:
    lcd.begin(16,2);
    lcd.clear();
    lcd.setCursor(0,0);
    Line1 = "Enter Amount";
    lcd.print(Line1);
    lcd.setCursor(0,1);
    Line2 = "Enter Time";
    lcd.print(Line2);
    delay(1000);
    mode = Mainmenu;
    break;

       }

    if (key != NO_KEY &&       (key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'))
  {
    if (present != true)
    {
      num1 = num1 + key; // storing the value of key pressed in num1
      float numLength = num1.length();
      lcd.setCursor(0, 1); /* decaling the place where the first entry will be displayed*/
      lcd.print(num1); // printing the first number entered
    }
    else
    {
      num2 = num2 + key;//storing the value of second key pressed in num2
      float numLength = num2.length();
      lcd.setCursor(4, 1);/*decaling the place where the second entry will be displayed*/
      lcd.print(num2); //printing the second number entered
      final = true;
        }
  }

}`
</code>```

As a beginner of the Arduino programming I tried so many methods including switch methods also.
But it didn't display. Please anyone can help me to solve this code?

I am trying to display this;enter image description here

Here I want to display
when I click the S button there two menus are displaying. They are Stop and Start. I want to display that two in LCD and if start button click then machine is forward after that when I click the stop button it should be stopped.

Body:
I am trying to display two menu type in 16x2 LCD display using keypad in Arduino.

Here is the code;
`#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

byte rowPins[4]={9,8,7,6};
byte colPins [4]={5,4,3,2};

char keys[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
Keypad keypad = Keypad(makeKeymap(keys),rowPins,colPins,4,4);

LiquidCrystal_I2C lcd(0x27,16,2);
boolean present = false;
boolean next = false;
boolean final = false;
String num1, num2; //
float ans;//
char op;//

//String Line1 = "                ";
//String Line2 = "                ";
//char cursors = 0;
//
////phaseshift
//char phase_value[2];
//int phase_cursor;
//int phase_index;
//char phasesign;
//
////declare function
//void Phaseshift_Fn();
//void CV_Fn();
//void CC_Fn();
//void Remote_Fn();

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.begin (16,2);

  lcd.clear();
  lcd.setCursor(0, 0); lcd.print(Line1);
  lcd.setCursor(0, 1); lcd.print(Line2);
  delay(100);

  lcd.setCursor(5,0);
  lcd.print("HELLO");
  lcd.setCursor(0,1);
  lcd.print("PRESS FWD Button");
  delay(2000);
  lcd.clear();
  delay(1000);
}

void loop() {
  char key = keypad.getKey();
  if(key == 'B'){
      lcd.setCursor(0,0);
      lcd.print("IF NO AIR BUBBLE");
      lcd.setCursor(0,1);
      lcd.print("PRESS STOP");
     }
    if(key == 'A'){
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("PRESS MODE");
      lcd.setCursor(0,1);

       switch(mode)
{
  case Startup:
    lcd.begin(16,2);
    lcd.clear();
    lcd.setCursor(0,0);
    Line1 = "Enter Amount";
    lcd.print(Line1);
    lcd.setCursor(0,1);
    Line2 = "Enter Time";
    lcd.print(Line2);
    delay(1000);
    mode = Mainmenu;
    break;

       }

    if (key != NO_KEY &&       (key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'))
  {
    if (present != true)
    {
      num1 = num1 + key; // storing the value of key pressed in num1
      float numLength = num1.length();
      lcd.setCursor(0, 1); /* decaling the place where the first entry will be displayed*/
      lcd.print(num1); // printing the first number entered
    }
    else
    {
      num2 = num2 + key;//storing the value of second key pressed in num2
      float numLength = num2.length();
      lcd.setCursor(4, 1);/*decaling the place where the second entry will be displayed*/
      lcd.print(num2); //printing the second number entered
      final = true;
        }
  }

}`

As a beginner of the Arduino programming I tried so many methods including switch methods also.
But it didn't display. Please anyone can help me to solve this code?

I am trying to display this;enter image description here

Here I want to display
when I click the S button there two menus are displaying. They are Stop and Start. I want to display that two in LCD and if start button click then machine is forward after that when I click the stop button it should be stopped.


问:
Getting the first line from a 1Gb csv file in JS
my task is to read the first line from csv-file.
This code works well for the file under 500Mb size, but it does not work for bigger files. I need to go up to 1Gb. For the bigger then 500Mb files i do not get any content from reader.result. Is there any way to handle it?</p>
```<code>            const reader = new FileReader()
            reader.readAsText(file)
            const lineBreakCharacters = '\r\n'
            const rows = (reader.result as string).split(lineBreakCharacters)
            let headerLine = rows.shift()
            console.log('headerLine===>', headerLine)
</code>```

Body:
my task is to read the first line from csv-file.
This code works well for the file under 500Mb size, but it does not work for bigger files. I need to go up to 1Gb. For the bigger then 500Mb files i do not get any content from reader.result. Is there any way to handle it?

            const reader = new FileReader()
            reader.readAsText(file)
            const lineBreakCharacters = '\r\n'
            const rows = (reader.result as string).split(lineBreakCharacters)
            let headerLine = rows.shift()
            console.log('headerLine===>', headerLine)


问:
Not able to generate csv file into s3 bucket using aws glue python shell script
```<code>import sys
import boto3 ,json,sys
import psycopg2
import csv

secret_name = 'xxxx' region_name ='us-east-1' session = boto3.session.Session() client = session.client(service_name='secretsmanager',region_name=region_name) get_secret_value_response = client.get_secret_value(SecretId=secret_name) creds = json.loads(get_secret_value_response\['SecretString'\])

username = creds\['username'\] password = creds\['password'\] host = creds\['host'\]

try: connection = psycopg2.connect(user=username, password=password, host=host, port="5412", database="xxxx")

cursor = connection.cursor()

# Executing a SQL query to insert data into  table

select_query = """ SELECT * from table"""

cursor.execute(select_query)

print("Select Record successfully")

# Fetch result

record = cursor.fetchall()

print("Result ", record)

cursor = connection.cursor()

# Executing a SQL query to insert data into  table

How to generate the csv file into s3 bucket

select_query = """ SELECT * from table"""

cursor.execute(select_query)

print("Select Record successfully")

# Fetch result

record = cursor.fetchall()

print("Result ", record)]
</code>```


问:
Other Indexes not working with full text index in mysql
Here is the mysql query which i am using:

select * from `jobs` where  MATCH(jobs.name,jobs.number,jobs.alt_id) AGAINST('*keyword*' IN BOOLEAN MODE) and company_id = 1

This query is taking around 2 seconds to execute but if i run it without company_id clause then it gives result within some milliseconds, after some investigation i came to know that my company_id index is not working if i run it along with full text search index.


问:
How to use Geo locations (ST_Contains, ST_MakePolygon, ST_GeomFromText) function in elastic search?
I need to find the locations which are in particular Geobounds. so i need to use ST_Contains, ST_MakePolygon, ST_GeomFromText, LINESTRING these functions but i cannot find these functions in documentation. how to use these functions in elastic search SQL query.</p>


问:
How to check if a signal is toggling after some time in simvision TCL command
I was working in simvision environment and I was developing to script to check whether a signal is toggling after some time. Could you please let me know if there are TCL command in the simvision console.

I was using waveform values -at time signal but it was displaying one value.


问:
error processing line 1 of c in vscode terminal
**i'm trying to install django but this error keeps repeating **

Error processing line 1 of c:\python34\lib\site-packages\distutils-precedence.pth:

Traceback (most recent call last):
File "c:\python34\lib\site.py", line 167, in addpackage
exec(line)
File "", line 1, in
File "c:\python34\lib\site-packages_distutils_hack_init_.py", line 194
f'spec_for_{name}',
^
SyntaxError: invalid syntax

Remainder of file ignored

i tried updating pip but even then this showed up


问:
The advertisement for Unity admob does not appear when conducting internal tests
When I directly insert the apk file into an android mobile device

MobileAds.Initialize(initStatus => { });

code works fine.

However, when I use it in an internal test version with aab file,
it does not work. How can I debug this in internal testing version?

public class BottomBanner : MonoBehaviour
{
public static BottomBanner instance;

```<code>private BannerView bannerView;
public TextMeshProUGUI FailMSG;
public AdRequest request;

private void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
    else
    {
        Destroy(gameObject);
    }
    FailMSG.text += "\n is awake Ok "+  "\n version : " + GameStartManager.instance.version +  "\n Test : " + GameStartManager.instance.isTest;
}

public void Start()
{
    FailMSG.text += "\n Start 000 ";
    // Initialize the Google Mobile Ads SDK.
    MobileAds.Initialize(initStatus => { });
    FailMSG.text += "\n Start 111 ";
    this.RequestBanner();
    FailMSG.text += "\n Start 222 ";
}

private void RequestBanner()
{
    #if UNITY_ANDROID
    string adUnitId = null;
    if (GameStartManager.instance.isTest)
    {
        adUnitId = "ca-app-pub-3940256099942544/6300978111";
    }
    else
    {
        adUnitId = "ca-app-pub-0000000000000000/1111111111"; // bannerID
    }
    #elif UNITY_IPHONE
        string adUnitId = "unexpected_platform";
    #else
        string adUnitId = "unexpected_platform";
    #endif

    // Clean up banner ad before creating a new one.
    if (this.bannerView != null)
    {
        this.bannerView.Destroy();
    }

    AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);

    this.bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);

    // Create an empty ad request.
    request = new AdRequest.Builder().Build();

    // Load the banner with the request.
    this.bannerView.LoadAd(request);
    SceneManager.LoadScene(1);
}

public void ToggleBannerAd(bool b){
    if (b) bannerView.Show();
    else bannerView.Hide();
}
</code>```

}

Body:
When I directly insert the apk file into an android mobile device

MobileAds.Initialize(initStatus => { });

code works fine.

However, when I use it in an internal test version with aab file,
it does not work. How can I debug this in internal testing version?

public class BottomBanner : MonoBehaviour
{
public static BottomBanner instance;

private BannerView bannerView;
public TextMeshProUGUI FailMSG;
public AdRequest request;

private void Awake()
{
    if (instance == null)
    {
        instance = this;
    }
    else
    {
        Destroy(gameObject);
    }
    FailMSG.text += "\n is awake Ok "+  "\n version : " + GameStartManager.instance.version +  "\n Test : " + GameStartManager.instance.isTest;
}

public void Start()
{
    FailMSG.text += "\n Start 000 ";
    // Initialize the Google Mobile Ads SDK.
    MobileAds.Initialize(initStatus => { });
    FailMSG.text += "\n Start 111 ";
    this.RequestBanner();
    FailMSG.text += "\n Start 222 ";
}

private void RequestBanner()
{
    #if UNITY_ANDROID
    string adUnitId = null;
    if (GameStartManager.instance.isTest)
    {
        adUnitId = "ca-app-pub-3940256099942544/6300978111";
    }
    else
    {
        adUnitId = "ca-app-pub-0000000000000000/1111111111"; // bannerID
    }
    #elif UNITY_IPHONE
        string adUnitId = "unexpected_platform";
    #else
        string adUnitId = "unexpected_platform";
    #endif

    // Clean up banner ad before creating a new one.
    if (this.bannerView != null)
    {
        this.bannerView.Destroy();
    }

    AdSize adaptiveSize = AdSize.GetCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(AdSize.FullWidth);

    this.bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Bottom);

    // Create an empty ad request.
    request = new AdRequest.Builder().Build();

    // Load the banner with the request.
    this.bannerView.LoadAd(request);
    SceneManager.LoadScene(1);
}

public void ToggleBannerAd(bool b){
    if (b) bannerView.Show();
    else bannerView.Hide();
}

}


问:
Legend filtration for stacked and line plot in ggplotly R
I have shiny app to shows some line plots, and I have used ggplotly with ggplot structure, everything was nice, but I was informed that I need to add stacked barplot in addition to line, I will add what I found on internet to modify my code.

```<code>options(scipen = 999)

df <- data.frame (country  = c("Estonia", "Latvia", "Lithuania", "Estonia", "Latvia", "Lithuania"),
                  obs_week = c(0,1, 0, 1, 0, 1),
                  wbeg = c("2022-12-26","2023-01-02", "2022-12-26","2023-01-02","2022-12-26","2023-01-02"),
                  vp = c(5000000, 6000000, 7000000, 5000000, 6000000, 7000000))

filteredDataplot <- df %>%
  filter(obs_week != -1) %>%
  group_by(obs_week, wbeg, country) %>%
  summarise(vp = sum(vp, na.rm = T)) %>% ungroup()

p <- ggplotly(ggplot(filteredDataplot, aes_string(x= "obs_week", y = "vp", key = "wbeg", fill = "country")) +
           geom_bar(stat="identity", position = "stack",  color = 'white', size = 0.3) +
           stat_summary(aes(group = 1, color = "Total"), fun = sum, geom = "line", color="black") +
           stat_summary(aes(group = 1, color = "Total"), fun = sum, geom = "point", color="black") +
           geom_vline(xintercept = lubridate::week(Sys.Date()), colour = "red") +
           scale_fill_manual(values = c("Estonia" = "#009900",
                                        "Lithuania" = "#1DE6E6",
                                        "Latvia" = "#6666FF"
                                        )
           ) +
           # facet_wrap(~country + time_horizon,
           #            scales = "free_y",
           #            ncol = 3) +
           #expand_limits(y = 0) +
           scale_x_continuous(labels = comma) +
           scale_y_continuous(labels = comma) +
           theme_bw() +
           labs(
             title = "Variable profit (Euro)
    <span style='font-size:11pt'></span>",
             x = "Week", y = "VP (Euro)"
             #caption = "<b>Source</b>: "
           ) +
           th`your text`eme_minimal() +
           theme(
             plot.title = element_markdown(lineheight = 1.1, size = 25),
             text = element_text(size = 13),
             legend.text = element_markdown(size = 11),
             plot.caption = element_markdown(size = 11)
           ), source = "select", tooltip = c("vp","obs_week","key"))

for (i in 1:length(p$x$data)) {
  p$x$data[[i]]$base <- c()
  tmp <- p$x$data[[i]]
  p$x$data[[i]] <- p$x$data[[length(p$x$data) - i + 1]]
  p$x$data[[length(p$x$data) - i + 1]] <- tmp
}
p

</code>```

so I added simple data here, my main problem is that, legend filtration works well for stacked barplot but I want to make interactive filtration for barplot and line both of them together, for example if you unselect Estonia in legend, then showing sum of only Lithuania and Latvia for line plot, and respective stacked bar plot... and have some more countries and different range of numbers, if you select small range country, then Y axis should also need to be small to see more effectively.

I hope I could explain what I would like to see, thanks a lot

Body:
I have shiny app to shows some line plots, and I have used ggplotly with ggplot structure, everything was nice, but I was informed that I need to add stacked barplot in addition to line, I will add what I found on internet to modify my code.

options(scipen = 999)

df <- data.frame (country  = c("Estonia", "Latvia", "Lithuania", "Estonia", "Latvia", "Lithuania"),
                  obs_week = c(0,1, 0, 1, 0, 1),
                  wbeg = c("2022-12-26","2023-01-02", "2022-12-26","2023-01-02","2022-12-26","2023-01-02"),
                  vp = c(5000000, 6000000, 7000000, 5000000, 6000000, 7000000))

filteredDataplot <- df %>%
  filter(obs_week != -1) %>%
  group_by(obs_week, wbeg, country) %>%
  summarise(vp = sum(vp, na.rm = T)) %>% ungroup()

p <- ggplotly(ggplot(filteredDataplot, aes_string(x= "obs_week", y = "vp", key = "wbeg", fill = "country")) +
           geom_bar(stat="identity", position = "stack",  color = 'white', size = 0.3) +
           stat_summary(aes(group = 1, color = "Total"), fun = sum, geom = "line", color="black") +
           stat_summary(aes(group = 1, color = "Total"), fun = sum, geom = "point", color="black") +
           geom_vline(xintercept = lubridate::week(Sys.Date()), colour = "red") +
           scale_fill_manual(values = c("Estonia" = "#009900",
                                        "Lithuania" = "#1DE6E6",
                                        "Latvia" = "#6666FF"
                                        )
           ) +
           # facet_wrap(~country + time_horizon,
           #            scales = "free_y",
           #            ncol = 3) +
           #expand_limits(y = 0) +
           scale_x_continuous(labels = comma) +
           scale_y_continuous(labels = comma) +
           theme_bw() +
           labs(
             title = "Variable profit (Euro)
    ",
             x = "Week", y = "VP (Euro)"
             #caption = "Source: "
           ) +
           th`your text`eme_minimal() +
           theme(
             plot.title = element_markdown(lineheight = 1.1, size = 25),
             text = element_text(size = 13),
             legend.text = element_markdown(size = 11),
             plot.caption = element_markdown(size = 11)
           ), source = "select", tooltip = c("vp","obs_week","key"))

for (i in 1:length(p$x$data)) {
  p$x$data[[i]]$base <- c()
  tmp <- p$x$data[[i]]
  p$x$data[[i]] <- p$x$data[[length(p$x$data) - i + 1]]
  p$x$data[[length(p$x$data) - i + 1]] <- tmp
}
p

so I added simple data here, my main problem is that, legend filtration works well for stacked barplot but I want to make interactive filtration for barplot and line both of them together, for example if you unselect Estonia in legend, then showing sum of only Lithuania and Latvia for line plot, and respective stacked bar plot... and have some more countries and different range of numbers, if you select small range country, then Y axis should also need to be small to see more effectively.

I hope I could explain what I would like to see, thanks a lot


问:
how to include  Component in all other pages without writing it multiple times
I want to display my navbar in all other router pages, but without writing  many times because it will lead to rendering the same component many times.
my router:

```<code><Router>
  <Routes>
    <Route path="/Login" element={<Signup />} />
    <Route path="/Login/Signin" element={<Login />} />
    <Route path="/Home" element={<Home />} />
    <Route path="/Trend" element={<Search_Page />} />
    <Route path="/Popular" element={<Popular />} />
    <Route path="/Watch" element={<Watchingpage />} />
    <Route path="/Favorite" element={<Favorite />} />
  </Routes>
</Router>
</code>```

enter image description here

The problem has been solved if I include the component in all other pages but it's not efficient at all.

enter image description here

The problem with this is that it's including  in <Login/> & <SignUp/>, Which I don't want to.

Title: how to include <Nav/> Component in all other pages without writing it multiple times

Body:
I want to display my navbar in all other router pages, but without writing  many times because it will lead to rendering the same component many times.
my router:

<Router>
  <Routes>
    <Route path="/Login" element={<Signup />} />
    <Route path="/Login/Signin" element={<Login />} />
    <Route path="/Home" element={<Home />} />
    <Route path="/Trend" element={<Search_Page />} />
    <Route path="/Popular" element={<Popular />} />
    <Route path="/Watch" element={<Watchingpage />} />
    <Route path="/Favorite" element={<Favorite />} />
  </Routes>
</Router>

enter image description here

The problem has been solved if I include the component in all other pages but it's not efficient at all.

enter image description here

The problem with this is that it's including  in <Login/> & <SignUp/>, Which I don't want to.


问:
histogram overlayed inside pytorch tensor image
I have a pytorch tensor image. I want to find the histogram for each channel and overlay the histogram image on top of the original image (in a corner). It would be useful if I can get the overlayed image as a tensor itself. How can I get that?

There is a longer way of doing this by first getting the histogram, save the histogram as image, read the histogram image as tensor, then replace a region of the original tensor image with the read histogram image tensor.
There has to be an easier way than this.


问:
Chat with laravel, socket io and redis not transferring messages through private channel
I am building a website with laravel, with chat option available inside it. I am able to store the messages in database as well as display in the sender's screen. But I can't manage to display the messages in receiver side. I am providing my codes as below. I used socket io and redis for the chat option.

server.js :

```<code>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http,{
 cors: { origin: "*"}
});
const port = process.env.PORT || 6001;
var Redis = require('ioredis');
var redis = new Redis();

var users =[];

http.listen(port, function () {
    console.log(`Listening to port ${port}`);
});

redis.subscribe('private-channel', function() {
    console.log('subscribed to private channel');
});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    console.log(message);
    if (channel == 'private-channel') {
        let data = message.data.data;
        let receiver_id = data.receiver_id;
        let event = message.event;

        io.to(`${users[receiver_id]}`).emit(channel + ':' + message.event, data);
    }

});

io.on('connection', function (socket) {

    console.log('connection');

    socket.on("user_connected", function (user_id) {
        users[user_id] = socket.id;
        io.emit('updateUserStatus', users);
        console.log("user connected "+ user_id);
    });

    socket.on('disconnect', function() {
        console.log('disconnected');
        var i = users.indexOf(socket.id);
        users.splice(i, 1, 0);
        io.emit('updateUserStatus', users);
        console.log(users);
    });
});
</code>```

controller :

```<code>public function companyconversation($userId) {
        $users = \DB::table('users')->where([
            'usertype'=>'individual',
        ])->get();
        $friendInfo = User::findOrFail($userId);
        $myInfo = User::find(Session::get('loginId'));
        $company = $myInfo;
        //$groups = MessageGroup::get();
        $this->data['company'] = $company;
        $this->data['users'] = $users;
        $this->data['friendInfo'] = $friendInfo;
        $this->data['myInfo'] = $myInfo;
        $this->data['users'] = $users;
        $this->data['userId'] = $userId;
        //$this->data['groups'] = $groups;
           //dd($users);
        return view('company.convo', compact('users','friendInfo','myInfo','company'));
    }
</code>```

view :

```<code><div id="main-content">
        <div class="container-fluid">
            <div class="block-header">
                <div class="row clearfix">
                    <div class="col-md-6 col-sm-12">
                        <h1> Messages(Chat) </h1>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="#">Demo </a></li>
                             <li class="breadcrumb-item active" aria-current="page">Messages(Chat)  </li>
                            </ol>
                        </nav>
                    </div>

                </div>
            </div>

            <div class="row clearfix">
                <div class="col-lg-12 ">
                    <div class="card ">
                        <div class="body" style="height:100%; min-height:700px;">
                            <div class="chatapp_list">
                                <div class="input-group mb-3">
                                    <input type="text" class="form-control" placeholder="Search...">
                                    <div class="input-group-append">
                                        <span class="input-group-text"><i class="icon-magnifier"></i></span>
                                    </div>
                                </div>

            <div class="col-md-12">
            <div class="users">
                <h5>Users</h5>

                <ul class="list-group list-chat-item">
                    @if($users->count())
                        @foreach($users as $users)
                            <li class="chat-user-list
                                @if($users->id == $friendInfo->id) active @endif">
                                <a href="{{ route('company_conversation', $users->id) }}">
                                    <div class="chat-image media">
                                        {!! makeImageFromName($users->fname,$users->lname) !!}
                                    </div>
                                    <div class="media-body">
                                                            <span class="name chat-name">{{$users->fname}}</span>

                                                            <!-- <span class="message">offline</span> -->

                                                            <span class="badge badge-outline status user-status-icon user-icon-{{$users->id}}"></span>
                                                        </div>

                                </a>
                            </li>
                        @endforeach
                    @endif
                </ul>
            </div>
</div>

                            </div>
                            <div class="chatapp_body">

                                <div class="col-md-9 chat-section">
                                <div class="chat-header">

                <div class="chat-name font-weight-bold">
                    {{ $users->fname }}

                </div>
            </div>

            <div class="chat-body" id="chatBody">
                <div class="message-listing" id="messageWrapper" style="
   border: 1px #ccc solid;
    height: 100%;
    overflow: hidden;
    min-height: 450px;
    position: relative;
    z-index: 9;
    color:#333;
    background: #fff;
">

                </div>
            </div>
            <div class="chat-box">
                <div class="chat-input border text-secondary bg-white p-3 " id="chatInput" contenteditable="">

                </div>

                <div class="chat-input-toolbar">
                    <button title="Add File" class="btn btn-light btn-sm btn-file-upload">
                        <i class="fa fa-paperclip"></i>
                    </button> |

                    <button title="Bold" class="btn btn-light btn-sm tool-items"
                            onclick="document.execCommand('bold', false, '');">
                        <i class="fa fa-bold tool-icon"></i>
                    </button>

                    <button title="Italic" class="btn btn-light btn-sm tool-items"
                            onclick="document.execCommand('italic', false, '');">
                        <i class="fa fa-italic tool-icon"></i>
                    </button>
                </div>
            </div>

        </div>

                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

 <!-- Modal Success -->
  <div class="modal fade" id="adsuccessModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered" role="document">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="exampleModalCenterTitle">  Successfully Saved </h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">×</span>
                                            </button>
                                        </div>
                                        <div class="modal-body" style="text-align: center;">
                     <span> <i class="fa fa-check-circle-o" style="font-size: 6em; color: #060;"></i> </span>
                       <h2 style="color: #060;"> Ad Saved Successfully</h2>
                       <button type="button" class="btn btn-round btn-success">
                        <i class="fa fa-bars"> Back to Ads Lists </i> </button>
                                        </div>
                                        <span style="font-size: 10px; color: #f00; text-align: center; margin-bottom: 1em;">Note: Your Ad will be automatically expired after 30 days of posted</span>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-round btn-default" data-dismiss="modal">Close</button>

                                        </div>

                                    </div>
                                </div>
                            </div>
                             <!-- Modal END  -->

                             <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script>

<script>
    function getCurrentTime() {
    return moment().format('h:mm A');
}

function getCurrentDateTime() {
    return moment().format('MM/DD/YY h:mm A');
}

function dateFormat(datetime) {
    return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YY h:mm A');
}

function timeFormat(datetime) {
    return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('h:mm A');
}

        $(function (){

            let $chatInput = $(".chat-input");
            let $chatInputToolbar = $(".chat-input-toolbar");
            let $chatBody = $(".chat-body");
            let $messageWrapper = $("#messageWrapper");

            let user_id = "{{ Session::get('loginId') }}";
            //console.log(user_id);
            let ip_address = '127.0.0.1';
            let socket_port = '6001';
            let socket = io(ip_address + ':' + socket_port);
            let friendId = "{{ $friendInfo->id }}";

            socket.on('connection',function() {
               socket.emit('user_connected', user_id);
            });
            socket.on('updateUserStatus', (data) => {
                let $userStatusIcon = $('.user-status-icon');
                $userStatusIcon.removeClass('text-success');
                $userStatusIcon.attr('title', 'Away');
                console.log(data);
                $.each(data, function (key, val) {
                   if (val !== null && val !== 0) {
                      let $userIcon = $(".user-icon-"+key);
                      $userIcon.addClass('text-success');
                      $userIcon.attr('title','Online');
                   }
                });
            });

            $chatInput.keypress(function (e) {
               let message = $(this).html();
               if (e.which === 13) {

                   $chatInput.html("");
                   sendMessage(message);
                   return false;
               }
            });

            function sendMessage(message) {

                let url = "{{ route('send-message') }}";
                let form = $(this);
                let formData = new FormData();
                let token = "{{ csrf_token() }}";
                formData.append('message', message);
                formData.append('_token', token);
                formData.append('receiver_id', friendId);
                appendMessageToSender(message);
                $.ajax({
                   url: url,
                   type: 'POST',
                   data: formData,
                    processData: false,
                    contentType: false,
                    dataType: 'JSON',
                   success: function (response) {
                       if (response.success) {
                           console.log(response.data);
                       }
                   }
                });
            }

            function appendMessageToSender(message) {
                let name = '{{ $myInfo->fname }}';
                let image = '{!! makeImageFromName($myInfo->fname,$myInfo->lname) !!}';
                let userInfo = '<div class="col-md-12 user-info">\n' +
                    '<div class="chat-image">\n' + image +
                    '</div>\n' +
                    '\n' +
                    '<div class="chat-name font-weight-bold">\n' +
                    name +
                    '<span class="small time text-gray-500" title="'+getCurrentDateTime()+'">\n' +
                    getCurrentTime()+'</span>\n' +
                    '</div>\n' +
                    '</div>\n';
                let messageContent = '<div class="col-md-12 message-content">\n' +
                    '<div class="message-text">\n' + message +
                    '</div>\n' +
                    '</div>';
                let newMessage = '<div class="row message align-items-center mb-2">'
                    + userInfo + messageContent +
                    '</div>';
                $messageWrapper.append(newMessage);
            }

            function appendMessageToReceiver(message) {
                let name = '{{ $friendInfo->fname,$friendInfo->lname }}';
                let image = '{!! makeImageFromName($friendInfo->fname,$friendInfo->lname) !!}';
                let userInfo = '<div class="col-md-12 user-info">\n' +
                    '<div class="chat-image">\n' + image +
                    '</div>\n' +
                    '\n' +
                    '<div class="chat-name font-weight-bold">\n' +
                    name +
                    '<span class="small time text-gray-500" title="'+dateFormat(message.created_at)+'">\n' +
                    timeFormat(message.created_at)+'</span>\n' +
                    '</div>\n' +
                    '</div>\n';
                let messageContent = '<div class="col-md-12 message-content">\n' +
                    '                            <div class="message-text">\n' + message.content +
                    '                            </div>\n' +
                    '                        </div>';
                let newMessage = '<div class="row message align-items-center mb-2">'
                    +userInfo + messageContent +
                    '</div>';
                $messageWrapper.append(newMessage);
            }

            socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message)
            {
               appendMessageToReceiver(message);
            });

        });
    </script>
</code>```

Event :

```<code><?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PrivateMessageEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $data;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('private-channel');
    }

    public function handle() {

    }
}
</code>```

I am expecting the message to appear on the receiver side, but it is not happening.

Body:
I am building a website with laravel, with chat option available inside it. I am able to store the messages in database as well as display in the sender's screen. But I can't manage to display the messages in receiver side. I am providing my codes as below. I used socket io and redis for the chat option.

server.js :

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http,{
 cors: { origin: "*"}
});
const port = process.env.PORT || 6001;
var Redis = require('ioredis');
var redis = new Redis();

var users =[];

http.listen(port, function () {
    console.log(`Listening to port ${port}`);
});

redis.subscribe('private-channel', function() {
    console.log('subscribed to private channel');
});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    console.log(message);
    if (channel == 'private-channel') {
        let data = message.data.data;
        let receiver_id = data.receiver_id;
        let event = message.event;

        io.to(`${users[receiver_id]}`).emit(channel + ':' + message.event, data);
    }

});

io.on('connection', function (socket) {

    console.log('connection');

    socket.on("user_connected", function (user_id) {
        users[user_id] = socket.id;
        io.emit('updateUserStatus', users);
        console.log("user connected "+ user_id);
    });

    socket.on('disconnect', function() {
        console.log('disconnected');
        var i = users.indexOf(socket.id);
        users.splice(i, 1, 0);
        io.emit('updateUserStatus', users);
        console.log(users);
    });
});

controller :

public function companyconversation($userId) {
        $users = \DB::table('users')->where([
            'usertype'=>'individual',
        ])->get();
        $friendInfo = User::findOrFail($userId);
        $myInfo = User::find(Session::get('loginId'));
        $company = $myInfo;
        //$groups = MessageGroup::get();
        $this->data['company'] = $company;
        $this->data['users'] = $users;
        $this->data['friendInfo'] = $friendInfo;
        $this->data['myInfo'] = $myInfo;
        $this->data['users'] = $users;
        $this->data['userId'] = $userId;
        //$this->data['groups'] = $groups;
           //dd($users);
        return view('company.convo', compact('users','friendInfo','myInfo','company'));
    }

view :

 Messages(Chat)

Demo

Messages(Chat)

                                    <input type="text" class="form-control" placeholder="Search...">

Users

                    @if($users->count())
                        @foreach($users as $users)

id == $friendInfo->id) active @endif">
                                id) }}">

                                        {!! makeImageFromName($users->fname,$users->lname) !!}

                                                            {{$users->fname}}

                                                            id}}">

                        @endforeach
                    @endif

                    {{ $users->fname }}

                    <button title="Add File" class="btn btn-light btn-sm btn-file-upload">

                    </button> |

                    <button title="Bold" class="btn btn-light btn-sm tool-items"
                            onclick="document.execCommand('bold', false, '');">

                    </button>

                    <button title="Italic" class="btn btn-light btn-sm tool-items"
                            onclick="document.execCommand('italic', false, '');">

                    </button>

  Successfully Saved

                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            ×
                                            </button>

 Ad Saved Successfully

                       <button type="button" class="btn btn-round btn-success">
                         Back to Ads Lists  </button>

                                        Note: Your Ad will be automatically expired after 30 days of posted

                                            <button type="button" class="btn btn-round btn-default" data-dismiss="modal">Close</button>

Event :

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PrivateMessageEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $data;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('private-channel');
    }

    public function handle() {

    }
}

I am expecting the message to appear on the receiver side, but it is not happening.


问:
how to create dll file of created project of send email.I am getting error for 'HttpPostedFileBase '
namespace web.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(EmailModel model, List attachments)
{
using (MailMessage mm = new MailMessage(model.Email, model.To))
{
mm.Subject = model.Subject;
mm.Body = model.Body;

```<code>            foreach (HttpPostedFileBase attachment in attachments)
            {
                if (attachment != null)
                {
                    string fileName = Path.GetFileName(attachment.FileName);
                    mm.Attachments.Add(new Attachment(attachment.InputStream, fileName));
                }
            }

            mm.IsBodyHtml = false;

            using (SmtpClient smtp = new SmtpClient())
            {

                smtp.Host = "smtp-mail.outlook.com";

                smtp.EnableSsl = true;

                NetworkCredential NetworkCred = new NetworkCredential(model.Email, model.Password);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;

                smtp.Port = 587;
                smtp.Send(mm);
                ViewBag.Message = "Email sent.";
            }
        }
        return View();
    }

}
</code>```

}

Body:
namespace web.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(EmailModel model, List attachments)
{
using (MailMessage mm = new MailMessage(model.Email, model.To))
{
mm.Subject = model.Subject;
mm.Body = model.Body;

            foreach (HttpPostedFileBase attachment in attachments)
            {
                if (attachment != null)
                {
                    string fileName = Path.GetFileName(attachment.FileName);
                    mm.Attachments.Add(new Attachment(attachment.InputStream, fileName));
                }
            }

            mm.IsBodyHtml = false;

            using (SmtpClient smtp = new SmtpClient())
            {

                smtp.Host = "smtp-mail.outlook.com";

                smtp.EnableSsl = true;

                NetworkCredential NetworkCred = new NetworkCredential(model.Email, model.Password);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NetworkCred;

                smtp.Port = 587;
                smtp.Send(mm);
                ViewBag.Message = "Email sent.";
            }
        }
        return View();
    }

}

}


问:
ExoPlayer landscape mode Jetpack Compose
I have a jetpack compose app in which there's a video player. The app is forced to portrait orientation, except for the screen/composable containing the video player. That composable is forced to landscape because I want to display the videos in landscape.

When I navigate to the page containing the video player the app correctly changes the orientation to landscape, but as soon as the video starts playing it rotates back to portrait orientation.

Any help is greatly appreciated...

Here's the relevant code for my problem.

```<code>@Composable
fun LockScreenOrientation(orientation: Int) {
    val context = LocalContext.current
    DisposableEffect(Unit) {
        val activity = context.findActivity() ?: return@DisposableEffect onDispose {}
        val originalOrientation = activity.requestedOrientation
        activity.requestedOrientation = orientation
        onDispose {
            // restore original orientation when view disappears
            activity.requestedOrientation = originalOrientation
        }
    }
}

fun Context.findActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.findActivity()
    else -> null
}

@Composable
fun VideoView() {
    val exoPlayer = remember {
        ExoPlayer.Builder(context)
            .build()
            .apply {
                setMediaItem(
                    MediaItem.Builder()
                        .apply {
                            setUri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")
                            setMediaMetadata(
                                MediaMetadata.Builder()
                                    .build()
                            )
                        }
                        .build()
                )
                prepare()
                playWhenReady = true
            }
    }

    DisposableEffect(
        AndroidView(factory = {
            PlayerView(context).apply {
                player = exoPlayer
                useController = false
                layoutParams = FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            }
        })
    ) {
        onDispose { exoPlayer.release() }
    }
}

@Composable
fun VideoScreen() {
    LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

    RakeVragenTheme {
        Surface(
            modifier = Modifier
                .fillMaxSize()
            color = Color.Black
        ) {
            VideoView()
        }
    }
}
</code>```

Body:
I have a jetpack compose app in which there's a video player. The app is forced to portrait orientation, except for the screen/composable containing the video player. That composable is forced to landscape because I want to display the videos in landscape.

When I navigate to the page containing the video player the app correctly changes the orientation to landscape, but as soon as the video starts playing it rotates back to portrait orientation.

Any help is greatly appreciated...

Here's the relevant code for my problem.

@Composable
fun LockScreenOrientation(orientation: Int) {
    val context = LocalContext.current
    DisposableEffect(Unit) {
        val activity = context.findActivity() ?: return@DisposableEffect onDispose {}
        val originalOrientation = activity.requestedOrientation
        activity.requestedOrientation = orientation
        onDispose {
            // restore original orientation when view disappears
            activity.requestedOrientation = originalOrientation
        }
    }
}

fun Context.findActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.findActivity()
    else -> null
}

@Composable
fun VideoView() {
    val exoPlayer = remember {
        ExoPlayer.Builder(context)
            .build()
            .apply {
                setMediaItem(
                    MediaItem.Builder()
                        .apply {
                            setUri("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")
                            setMediaMetadata(
                                MediaMetadata.Builder()
                                    .build()
                            )
                        }
                        .build()
                )
                prepare()
                playWhenReady = true
            }
    }

    DisposableEffect(
        AndroidView(factory = {
            PlayerView(context).apply {
                player = exoPlayer
                useController = false
                layoutParams = FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            }
        })
    ) {
        onDispose { exoPlayer.release() }
    }
}

@Composable
fun VideoScreen() {
    LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

    RakeVragenTheme {
        Surface(
            modifier = Modifier
                .fillMaxSize()
            color = Color.Black
        ) {
            VideoView()
        }
    }
}