text:
Q: android kotlin java.io.FileNotFoundException: /storage/emulated/0/number.txt: open failed: EACCES (Permission denied) I'm writing an app for Android 10 using kotlin.
The app has to read file named number.txt from internal storage.
But it always fails to do so:
java.io.FileNotFoundException: /storage/emulated/0/number.txt: open failed: EACCES (Permission denied)

Here what I have in my manifest:
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...

I have to only read the file, so there is no write permission in manifest.
Here is my code, as you can see I use runtime permissions:
This is the function that requests permission and if it granted, reads the file:
    private fun setupPermissions() {
        val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
        if (permission == PackageManager.PERMISSION_GRANTED) {
            val path = "/storage/emulated/0"
            val file = File("$path/number.txt")
            val pln = file.readText()
            plnText.text = pln
        }
        else{
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 101)
        }
    }

Then I call setupPermissions in my onCreate method.
That's it, I don't understand why isn't it working.
Thanks.
EDIT
I don't know what is the reason, but I just changed my code to this:
if (permission == PackageManager.PERMISSION_GRANTED) {
    val file = File("/storage/emulated/0/number.txt")
    val pln = file.readText()
    Log.i("IKO_APP", pln)
//  plnText.text = path.toString()
}

And it works without any error! I'm wondering though why?

A: For Android 10, you can add android:requestLegacyExternalStorage="true" to your <application> element in the manifest. This opts you into the legacy storage model, and your external storage code should work.
And for read operations, you should be able to still do what you are doing on Android 11+, courtesy of the "raw paths" change, even after you raise your targetSdkVersion to 30 or higher.
However, for write operations, you have until the second half of 2021 to switch to something else:

*

*Use methods on Context, such as getExternalFilesDir(), to get at directories on external storage into which your app can write. You do not need any permissions to use those directories on Android 4.4+. However, the data that you store there gets removed when your app is uninstalled.

*Use the Storage Access Framework, such as ACTION_OPEN_DOCUMENT and ACTION_CREATE_DOCUMENT.

*If your content is media, you can use MediaStore to place the media in standard media locations.


text:
Q: Spring Boot - Same repository and same entity for different databases I have a Spring Boot project with one entity and one repository associated to this entity. In the repository there is one method with a custom query and in the project controller this repository is used to return data from different postgresql databases. These databases have same tables with same columns (so the referred entity is the same), the only difference among these databases is the year (..., DB2015, DB2016, DB2017).
My questions are: How can i return data in the project controller that belong to "different" databases? Is possible to use the same query to select data initially from the first database, then from the second and so on?
In other questions i've read that i need different datasources, is this correct?
This is the entity:
@Entity(name = "REQUEST")
public class Request implements Serializable {

/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
@Column(name="IDREQUEST", nullable=false)
private BigDecimal idrequest;

@Column(name="PAYLOAD")
private String payload;

@Column(name="MITTENTE")
private String mittente;

@Column(name="SERVIZIO")
private String servizio;

@Column(name="DATARICEZIONE")
private BigDecimal dataricezione;

public BigDecimal getIdrequest() {
    return idrequest;
}

public void setIdrequest(BigDecimal idrequest) {
    this.idrequest = idrequest;
}

public String getPayload() {
    return payload;
}

public void setPayload(String payload) {
    this.payload = payload;
}

public String getMittente() {
    return mittente;
}

public void setMittente(String mittente) {
    this.mittente = mittente;
}

public String getServizio() {
    return servizio;
}

public void setServizio(String servizio) {
    this.servizio = servizio;
}

public BigDecimal getDataricezione() {
    return dataricezione;
}

public void setDataricezione(BigDecimal dataricezione) {
    this.dataricezione = dataricezione;
}

}

This is the repository:
@Repository
public interface RequestRepository extends PagingAndSortingRepository<Request, BigDecimal> {

    @Query(nativeQuery=true, value="SELECT * FROM \"REQUEST\" WHERE strpos(\"PAYLOAD\",\'?1\') > 0")
    List<Request> findByCodiceFiscale(String codiceFiscale);

}

This is the controller
@RequestMapping(value="/ricercaadesioni/{codicefiscale}", method=RequestMethod.GET)
public ResponseEntity<List<Request>> ricercaAdesioniByCodiceFIscale(@PathVariable("codicefiscale") String codicefiscale) {

    List<Request> listAdesioni = requestRepo.findByCodiceFiscale(codicefiscale);

    return new ResponseEntity<List<Request>>(listAdesioni, HttpStatus.OK);
}

This is application.properties (in this case the datasource is referred to one db only):
spring.datasource.url=jdbc:postgresql://localhost:5432/DB2017_test
spring.datasource.username=xxx
spring.datasource.password=xxx

Hope everything is clear

A: Create 2 config files with different datasource and these 2 config files will have different specifications for 2 different jpa repository class.but can have same domain class.
step1>
In your properties file have 2 datasource details.
spring.datasource.url=jdbc:postgresql://localhost:5432/DB2017_test
spring.datasource.username=xxx
spring.datasource.password=xxx

# DB2018 DB - ""
spring.datasource2.url=jdbc:postgresql://localhost:5432/DB2018_test
spring.datasource2.username=xxx
spring.datasource2.password=xxx

step2>Then create config file for first dataSource
package com.package1;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  entityManagerFactoryRef = "entityManagerFactory",
  basePackages = { "com.package1.repo" }
)
public class DB2017Config {

  @Primary
  @Bean(name = "dataSource")
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Primary
  @Bean(name = "entityManagerFactory")
  public LocalContainerEntityManagerFactoryBean
  entityManagerFactory(
    EntityManagerFactoryBuilder builder,
    @Qualifier("dataSource") DataSource dataSource
  ) {
    return builder
      .dataSource(dataSource)
      .packages("com.domain")
      .persistenceUnit("foo")
      .build();
  }

  @Primary
  @Bean(name = "transactionManager")
  public PlatformTransactionManager transactionManager(
    @Qualifier("entityManagerFactory") EntityManagerFactory
    entityManagerFactory
  ) {
    return new JpaTransactionManager(entityManagerFactory);
  }
}

step3> Similary create another config file for other dataSource,
@EnableJpaRepositories(
  entityManagerFactoryRef = "entityManagerFactory",
  basePackages = { "com.package2.repo" }

And change prefix
@ConfigurationProperties(prefix = "spring.datasource2")

Now you will have 2 similar RequestRepository1 and RequestRepository2 in package1 and package2 respectiverly as mentioned above (basePackages = { "com.package1.repo" }).
step4>All set autowire 2 different repo .
@Autowired
private final RequestRepository1  repo1;
@Autowired
private final RequestRepository2  repo2;

Then use them.
List<Request> listAdesioni = repo1.findByCodiceFiscale(codicefiscale);
List<Request> listAdesioni = repo2.findByCodiceFiscale(codicefiscale);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't bind to 'ngModel' since it isn't a known property of 'input' in VSC There are several messages on this problem in StackOverFlow, but I'm still stuck.
I have the error message
Can't bind to 'ngModel' since it isn't a known property of 'input'

On my first laptop I don't have an error message but on my second laptop "yes", I don't understand why?
the error message
HTML

  <form (ngSubmit)="login()">

      Identification de l'agent
      <input type="text" class="input" id="user" name="user" [(ngModel)]="loginForm.user" required maxlength="4">

      <input type="submit" value="Connexion" class="sign_btn">

  </form>

TS
@Component({
    selector: 'app-singin',
    templateUrl: './singin.component.html',
    styleUrls: ['./singin.component.css']
})
export class SinginComponent implements OnInit {
    loginForm: Login = new Login();
    ngUnsubscribe = new Subject < void > ();

    constructor(private log: SessionService, private store: Store, private router: Router) {

    }

    ngOnInit() {}

    login(): void {
        this.log.login(this.loginForm)
            .pipe(
                takeUntil(this.ngUnsubscribe),
            ).subscribe(
                res => {
                    if (res.islogged === true) {
                        this.store.dispatch(new SessionAction(res))
                        this.router.navigate(['/home']);
                    } else {
                        alert("L'identifiant est incorrect ! ")
                    }
                }
            )
    }
}

Here, by using [ngModelOptions]="{standalone: true}" it should work. I tried but I still have the same error message.
Can't bind to 'ngModel' since it isn't a known property of 'input'

How could I get rid of this error message, please?
EDIT
In the app.module.ts
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgxsModule } from '@ngxs/store';

import { SessionState } from './store/session/session.state';
import { CanActivateTeam } from './core/canActivateTeam.guard';
import { NgxsStoragePluginModule } from '@ngxs/storage-plugin';
import { IsActivate } from './core/isActivate.guard';

import { IdentityModule } from './views/identity/identity.module';
import { AppHttpInterceptor } from './core/interceptor/app-http.interceptor';
import { FormFollowUpModule } from './views/dashboard/views/dta/views/form-follow-up/form-follow-up.module';
import { FormCreateModule } from './views/dashboard/views/dta/views/form-create/form-create.module';
import { FormDeleteModule } from './views/dashboard/views/dta/views/form-delete/form-delete.module';

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
IdentityModule,
HttpClientModule,
FormsModule,
NgxsModule.forRoot([SessionState], {
developmentMode: true
}),
NgxsStoragePluginModule.forRoot({
key: 'session'
}),
FormFollowUpModule,
FormCreateModule,
FormDeleteModule,

],
providers: [
CanActivateTeam,
IsActivate,
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true

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

app.html
I have an error message also
enter image description here
identity.module.ts
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

import { SessionService } from '../../services/sessions.service';
import { IdentityRoutingModule } from './identity-routing.module';
import { IdentityComponent } from './identity.component';
import { SinginComponent } from './view/singin/singin.component';

@NgModule({
  declarations: [
    IdentityComponent,
    SinginComponent,

  ],
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    IdentityRoutingModule

  ],
  providers: [
    SessionService
  ]
})
export class IdentityModule { }


text:
Q: Hyperref phrase with pagebreak also makes footnotes hyperlinked With the command \hyperref[link]{text} from the hyperref package, if the text breaks across pages and the first page has a footnote, then that footnote is erroneously also made a hyperlink.
Looks like a bug to me. Any elegant suggestions for fixes?
MWE:
\documentclass[11pt,a4paper]{article}

\usepackage{hyperref,lipsum,amsmath}

\begin{document}

First an equation:
\begin{equation}
    x=y
    \label{eq}
\end{equation}
Now, a sentence.\footnote{A footnote.}

\lipsum[1-4]

\hyperref[eq]{Finally, a sentence hyperlinked to the equation above; because this hyperref-ed sentence breaks across the page, the unrelated footnote also becomes hyperlinked.}

\end{document}


text:
Q: Form submitting using jquery without ajax in rails I am new to rails.i Want to sort content using jquery by selecting value from dropdown list.
so i am having problem to submit a form to a specific controller action using jquery.
I have a category model which has many products.In my category show i have a form like bellow:
    <%= form_for(:category, :url => sort_category_path, method: 'GET', :class=> " form-inline pull-left") do |f| %>
              Sort By :
              <select id ="sort" name= "order_by">
                <option>Default</option>
                <option>Name</option>
                <option>Pirce</option>

              </select>
  <%end%>

here at this form i am not sure what does mean by :category ?
Jquery for submit the form :
  $('select#sort').change(
function(e){

    $(this).closest('form').trigger('submit');

});

Then at my category controller i have a sort_item action like this:
  def sort_item
   @category_sort = Category.find(params[:id])

   @products = @category_sort.products.order("#{params[:order_by].to_s} ASC")
  end

i dont know how to send response to the request.
the server log says :
Started GET "/en/categories/tshart/sort_item?utf8=%E2%9C%93&order_by=Pirce" for 127.0.0.1 at 2013-11-11 12:53:49 +0600
Processing by CategoriesController#sort_item as HTML
  Parameters: {"utf8"=>"✓", "order_by"=>"Pirce", "locale"=>"en", "id"=>"tshart"}
  Category Load (0.3ms)  SELECT categories.* FROM categories WHERE categories.slug = 'tshart' LIMIT 1
Redirected to http://test.com/en/categories/tshart
Filter chain halted as :find_category rendered or redirected
Completed 301 Moved Permanently in 6.7ms (ActiveRecord: 0.3ms)
keep in mind that test.com stands for localhost:3000 .
i want to know what i am doing wrong here ,why the sorting is not working or is there any better way to accomplish my sorting task?
please help me .
thanks in advance.

A: Try putting your change event in doc ready handler:
$(function(){ // <----enclosed in document ready
    $('select#sort').change(function(e){
       $(this).closest('form').trigger('submit');
    });
});

This will look for if dom has been ready for js event execution bind on elements.

A: Wow its working now.
It was a routing issue I explained earlier.The issue was:
Redirected to http://test.com/en/categories/tshart Filter chain halted as :find_category rendered or redirected Completed 301 Moved Permanently in 6.7ms (ActiveRecord: 0.3ms)
Here my request was redirected to another action then i removed the the filter chain and then added render :show to my categories controller sort_item action. now its just rocking .Everything else remain the same.
Hope this question may help others.
Thanks @jai for your help.


text:
Q: Evaluating zero set $Z_{R}(f)$ as a line, the union of a line an a surface, ... The zero set is defined as:
$$Z_{R}(f) = \{x \in \mathbb{R}^3 : f(x)=0\}$$
In this post its claimed that the zero set of $$f(x_1,x_2,x_3) = x_1^2 + x_2^2$$ is a line
while the zero set of
$$f(x_1, x_2, x_3) = x_3^2 + x_2^2 - x_2^3$$
is the union of a line and a surface.
How are these evaluated in order to see a line or the union of a line and a surface?

A: For $f(x_1,x_2,x_3) = x_1^2 + x_2^2$, we have $f(x_1,x_2,x_3) = 0$ if and only if $x_1 = x_2 = 0$ (since $x_i^2$ are non-negative). This means that
$$ Z_{\mathbb{R}}(f) = \{ (x_1, x_2, x_3) \, | \, x_1 = x_2 = 0 \} = \mathrm{span} \{ (0, 0, 1) \} $$
is indeed a line (the $z$-axis).
For $g(x_1,x_2,x_3) = x_3^2 + x_2^2 - x_2^3$, we have
$$ Z_{\mathbb{R}}(g) = \{ (x_1, x_2, x_3) \, | \, x_2^3 = x_2^2 + x_3^2 \} = \\ \{(x_1,x_2,x_3)\, | \, x_2^3 = x_2^2 + x_3^2, x_2 \neq 0 \} \cup \{(x_1,x_2,x_3)\, | \, x_2^3 = x_2^2 + x_3^2, x_2 = 0 \} = A_1 \cup A_2. $$
The $A_2$ piece is a line $A_2 = \{ (x_1, x_2, x_3) \, | \, x_2 = x_3 = 0 \}$ (the $x$-axis). To see that $A_1$ is a surface, note that
$$ \nabla g|_{(x_1,x_2,x_3)} = (0, 2x_2 - 3x_2^2, 2x_3) = (0, x_2(2 - 3x_2), 2x_3). $$
If we set $U = \{ (x_1, x_2, x_3) \, | \, x_2 \neq 0 \}$ then $g|_{U}^{-1}(0) = A_1$ and $0$ is a regular value of $g|_U$ and so by the implicit function theorem, $A_1$ is a surface.


text:
Q: What is the syntax to properly plot a list of dates and values that go over one month? I'm trying to experiment with the covid-19 data from John Hopkins as a way of learning some basic Mathematica functionality. I pulled down the CSV files and figured out how to convert them to datasets and then extra particular rows, etc.
I ended up with a small chunk of data covering part of January and February. If I use DateListPlot on the first portion of that data, just covering January, it works fine. However, if I increase the length of the data by just 1 such that the first date of February is included, I get the following error:
DateListPlot::ldata: <|1/22/20->2,1/23/20->1,1/24/20->2,1/25/20->2,1/26/20->4,1/27/20->4,1/28/20->7,1/29/20->7,1/30/20->11,1/31/20->15,2/1/20->20|> is not a valid dataset or list of datasets.
I have no idea why adding the first date of the next month produces this error and would appreciate any insights.
Thanks in advance

Here is what I did
1) Pulled down the data from Github (https://github.com/CSSEGISandData/COVID-19.git)
Then in a Notebook:
confirmed =
  Import["/Volumes/HD2/Github/COVID-19/csse_covid_19_data/csse_covid_\19_time_series/time_series_19-covid-Confirmed.csv", "Dataset",    "HeaderLines" -> 1];

(* See first image -- the plot works when the range goes from 5 to 14
but as soon as I change the end index from 14 to 15, the plot fails even though the list data displays correctly
 *)

A: It is clear now that the extra point that you add is the only one that has the date that is ambiguous to interpretation:
data=Normal[confirmed[1][[5;;15]]]

<|"1/22/20" -> 2, "1/23/20" -> 3, "1/24/20" -> 5, "1/25/20" -> 7,
   "1/26/20" -> 8, "1/27/20" -> 8, "1/28/20" -> 14, "1/29/20" -> 14,
   "1/30/20" -> 14, "1/31/20" -> 19, "2/1/20" -> 19|>

So the last point -- is it FEB 1 or JAN 2 ? DateListPlot cannot interpret that date and gives error. This is why you need exact interpretation of dates:
convert=KeyMap[DateObject[{#,{"Month","Day","YearShort"}}]&,data]

Now it obviously works, no errors:
DateListPlot[convert, PlotMarkers -> Automatic]


text:
Q: Any tools to document Java POJO transformer code? I've inherited a project which essentially maps large documents from one structure to another. The source and target documents are POJOs, and there are a number of transformer classes that map the source POJO to the target by using the getters/setters of each field.
For example, say we have:
public void transform(SourceDocument source, TargetDocument target) {
    target.setField1(source.getField1());
    target.setField2(source.getField5());
    target.setField3(source.getField2());
    target.setField4(source.getField4());
    target.setField5(source.getField3());
}

We're looking to refactor large parts of this project and as part of it, our customer has requested that we document these mappings before we look to refactor with a better implementation.
There are several hundred of these mappings and before we get one of team to go through them all by hand, does anyone know of any tools that could analyse this code and produce a simple mapping document. All mapping have been strictly performed using getters/setters with no direct property access.
We can't give the actual code to our customer due to IP restrictions, and also it's the (non-technical) business who need this information, so ideally we need a very simple output, describing the mapping from source to target.
These transformers are still occasionally updated while we work on a new version, so I'd really prefer something that could generate the documentation we're after directly from the code rather than comments/annotations that would have to be manually updated by developers.


text:
Q: Clang -Wconditional-uninitialized on struct member array assignment I've run into some unusual behavior involving Clang -Wconditional-uninitialized.  Consider the following example:
typedef struct { int x[1]; } test_t;
test_t foo(void);
test_t foo() {
    test_t t;
    for(int i = 0; i < 1; i++) t.x[i] = 0;
    return t;
}
int main() { }

Compiling with, e.g.
clang -o test -Weverything test.c

gives the following warnings:
test.c:6:12: warning: variable 't' may be uninitialized when used here [-Wconditional-uninitialized]
    return t;
           ^
test.c:4:5: note: variable 't' is declared here
    test_t t;
    ^
1 warning generated.

However, switching the line:
    for(int i = 0; i < 1; i++) t.x[i] = 0;

with
    t.x[0] = 0;

yields no warnings.  Note that it is sufficient to use -Wconditional-uninitialized and not necessary to pass -Weverything.  The -O3 optimized assembly from both cases is identical, with a single xorl %eax, %eax emitted in both cases.  This is the minimum example I could create that showed this behavior.
I take some of Clang's -Weverything output with a grain of salt, but this seems to me like a bug and I'm rather confused.  Is there some kind of  undefined behavior I'm invoking that's causing this, or is this a false positive?  Is it in general a good or bad idea to keep -Wconditional-uninitialized enabled?  I see the same behavior on Clang 3.8.1 on Linux and (Apple) 9.1.0 on macOS.

A: As @R.. suggested above in the comments, I've reported this as LLVM bug 38856.  Apparently, according to them:

-Wconditional-uninitialized is expected to have false positives: it warns in cases where a simple control flow analysis cannot prove that a variable was written to prior to each use. It is not field-sensitive nor data flow sensitive, so it cannot tell the difference between writing to one array element and writing to the whole array, and doesn't know that the loop actually always executes at least once.
-Winitialized, by contrast, only warns when we can prove your program has a bug (or contains dead code).
There are a few improvements we could make to reduce the false positive rate here (some crude field sensitivity might be relatively straightforward to add), but we don't want to recreate the full intelligence of the clang static analyser here, and keeping this warning simple enough that we can run it as part of normal compilations is a goal.

I also noted in that report that the following example gives no warnings even though one of the array members is clearly uninitialized:
#include <stdio.h>

typedef struct { int x[2]; } test_t;

test_t foo_3(void);

test_t foo_3() {
    test_t t;
    t.x[0] = 0;
    return t;
}

int main() {
    test_t t;

    t = foo_3();
    printf("%i %i\n", t.x[0], t.x[1]);
}

Which got me the reply:

As I mentioned in comment#1, the analysis we currently perform cannot tell the difference between writing to one array element and writing to the whole array. In simple cases, this should be relatively straightforward to improve, so I think for that reason this bug is valid (but of low priority, given that this warning is expected to have false positives).

So -Wconditional-uninitialized is known for giving false positives.  Apparently the static analyzer isn't as thorough as I would have expected.  I'm surprised I hadn't run into anything like this before given more complicated scenarios where the analyzer seemed to have worked better, but as @toohonestforthissite also notes in the comments above, passing arrays around by value via structs like this is not a standard thing to do in C.
-Wno-conditional-uninitialized or #pragma clang diagnostic ignored "-Wconditional-uninitialized" should silence that warning for those who want to use -Weverything in a case like this.


text:
Q: Flexible Font Size for fixed width and height I need to make each of my
 have flexible font size with fixed width and height.
Current code
CSS
p{
    width:500px;
    height:100px;
    background-color:#F0F0F0;
    margin:10px;
    padding:5px;
    font-size:24px;
}

HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros, faucibus sit amet aliquet ac, varius id eros.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.

Check and try the code in jsfiddle
http://jsfiddle.net/8GNAV/
And this the output I want to reach
http://jsfiddle.net/8GNAV/1/

A: The general idea is to get overflow:hidden, then keep shrinking the text until the scrollHeight is less than the offsetHeight. Like so:
[].forEach.call(document.getElementsByTagName('p'),function(p) {
  p.style.overflow = "hidden";
  var f = 24;
  while(f > 6 && p.scrollHeight > p.offsetHeight) {
    f--;
    p.style.fontSize = f+"px";
  }
});

Demo


text:
Q: enclose html in variable in PHP So, I have few html lines in php:
function upload_image()
{
 ?>

<?php
}

I am trying to send these data to js via ajax. I am not sure how to enclose everything into one single variable which then i can send it to js.
Could someone show me how to enclose it into a variable?
Thanks

A: Easiest (subjective) is Heredoc syntax
$string=<<<HTML

HTML;

Then you can just echo your string
echo $string;   // or return $string as need be

This keeps your code clean and also makes you free of any worries about single quotes double quotes etc. Using quotes you always have to escape codes if they are within similar quotes.
That HTML is just a marker, it can be anything at all, just that the closing placeholder should have nothing before it on its line, not even a space.
$a=<<<TESTING
Yeah that's nice. Heck with those double " or Single ' quotes :P
TESTING;

A: You can set this html data in one variable as follow:
<?php
    $variable = "";

    $variable .=  '
';
    $variable .=  '
';
    $variable .=  '
';
    $variable .=  '
';
    $variable .=  '

';
    $variable .=  '
';
    $variable .=  '
';
    $variable .=  '
';
    $variable .=  '
';
?>

A: Mixing code and template (HTML) like this is usually considered bad form. I'd suggest to either:

*

*use a templating library such as Mustache to keep your code and your layout separate

*or to use an MVC framework (such as Laravel) that helps you build a proper application structure, and which use templates and views out of the box

or, if all of that is too difficult, to at least read in the HTML from an external file, and the put it into a variable, like so
<?php
    function upload_image() {
        $var = file_get_contents(TEMPLATE_DIR . "/upload_image.html");
    }
?>

where, at some central point in a configuration file or something, you do
<?php
    define('TEMPLATE_DIR', "[[path to template dir]]");
?>

A: Like this:
function upload_image()
{
  $var = "

";
}


text:
Q: How to create a merit list in descending order according some rules? I am doing a project creating an admission system for a College. The technologies are Java and Oracle.
The College has 5 Branches across the country. The college invites Application Forms from Candidates Branch-wise but all data related to Candidates are stored and process Centrally from their Head office located in say, Delhi. There are 40% seats reserved for SC,ST,OBC,PH candidates etc and the central Head Office is responsible for creating a Branch-wise, Department-wise, category-wise merit list Order by their Total marks (for simplicity) in descending order to fill up the seats (say 30 seats for each Department). Now if the two Candidates secure the same marks then the candidate getting the higher mark in the subject applying for would be preferred. Now for simplicity, it is assumed that all required data are stored in a flat table say application_details{appl_no, form_no, branch, department, name, gender, dob, category, subject_marks, total_marks} .
Also, there will be a waiting list which will be 2 times the number of seats.
I am perplexed, as to how to deal with Ordering and comparing the whole lot of data (arround 50 thousand for all five Branches), using Oracle Procedure and functions.

A: This is just a SQL query you need, you probably won't need any procedural code (e.g. functions, procedures or java) to get the answers.
For example, given a set of applications with {appl_no, subject_marks, total_marks}, you can sort these in descending order of total_marks, and when some rows have identical total_marks, you can sort them in descending order of subject_marks, e.g.:
SELECT *
FROM   application_details
ORDER BY total_marks DESC, subject_marks DESC;

If you want to see who gets the 30 seats, you can limit the result to the first 30 results, e.g.:
SELECT *
FROM (
  SELECT *
  FROM   application_details
  ORDER BY total_marks DESC, subject_marks DESC
  )
WHERE ROWNUM <= 30;

(This could also be done using the ROW_NUMBER analytic function.)
However, this doesn't deal with the unfairness of the algorithm in that if you have 30 seats, and 2 or more people tie for the 30th seat, you will pick one of them effectively at random and the other person will lose out.
An alternative is to change the rule such that up to 30 seats will be assigned; if there are any ties for the 30th seat, it is left vacant. To do this you could use a suitable analytic clause, e.g.:
SELECT *
FROM   (
  SELECT DENSE_RANK()
         OVER (ORDER BY total_marks DESC,
                        subject_marks DESC) dr,
         ad.*
  FROM   application_details ad
  )
WHERE dr <= 30;

This will return up to 30 top results, but if there is a tie for the 30th (or indeed 29th, or 28th, etc) place, it will not return a result.
Which one you use will depend on the rules you need to abide by.

A: One approach is using mainly java language, using an ORM tool like hibernate to map your table into an entity that implements the comparable interface. Then you can sort applications and save the results into another column of the same table or a new table that has a foreign key to your table.
Of course you could use pl/sql procedures, but that would be a code much more difficult to maintain, even if it would have better runtime performance.


text:
Q: near "WHERE": syntax error - SQLite I have a method that will if check two text fields exist then retune the record ID.
My method look like this:
int getQueryMatch(String word, String meter) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT *  FROM " + TABLE_HISTORY + " WHERE " + QUERYWORD +  "= '" + word + "' AND WHERE " + DISTANCEQ + "= '"+ meter +"' "  ;
    Cursor cursor = db.rawQuery(selectQuery, null);
    int getidd = cursor.getColumnIndex(KEY_ID) ;

    Log.v("Match query ", "return? " + getidd );
    if (cursor != null)
        cursor.moveToFirst();

    // return History
    return getidd;
}

and I have my table looks like this:
    String CREATE_HISTORYS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_HISTORY + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            QUERYWORD + " TEXT," + DISTANCEQ + " TEXT" + ","  + KEY_TIMESTAMP + ")";
    db.execSQL(CREATE_HISTORYS_TABLE);

now when I run the method as if getQueryMatch(Mystr1 , Mystr2);
I got this error:
10-18 22:04:04.294: E/AndroidRuntime(13736): FATAL EXCEPTION: AsyncTask #1
10-18 22:04:04.294: E/AndroidRuntime(13736): java.lang.RuntimeException: An error occured while executing doInBackground()
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.lang.Thread.run(Thread.java:856)
10-18 22:04:04.294: E/AndroidRuntime(13736): Caused by: ****android.database.sqlite.SQLiteException: near "WHERE": syntax error (code 1): , while compiling: SELECT *  FROM history WHERE query= 'Information Pillar' AND WHERE distance= '20'****
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at com.example.phooogle.DatabaseHandler.getQueryMatch(DatabaseHandler.java:149)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at com.example.phooogle.GoogleMapsAppActivity$InitTask.doInBackground(GoogleMapsAppActivity.java:233)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at com.example.phooogle.GoogleMapsAppActivity$InitTask.doInBackground(GoogleMapsAppActivity.java:1)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-18 22:04:04.294: E/AndroidRuntime(13736):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

My select query looks like alright to me but I don't know what is the problem?

A: Remove the second WHERE, then it will work.
String selectQuery = "SELECT *  FROM " + TABLE_HISTORY + " WHERE " + QUERYWORD +  "= '" + word + "' AND WHERE " + DISTANCEQ + "= '"+ meter +"' "  ;
                                                                                ^^^^^
                                                                                here's the error

Ah, and by the way: You query building seems highly vulnerable to SQL injection! Better fix that.

A: You have 2 WHERE clauses in your query. You are only allowed to have one. Combine them like this:
String selectQuery = "SELECT *  FROM " + TABLE_HISTORY + " WHERE " + QUERYWORD +  "= '" + word + "' AND " + DISTANCEQ + "= '"+ meter +"' "  ;

So now you query would be:
SELECT *  FROM history WHERE query= 'Information Pillar' AND distance= '20'`

This is now valid.

A: No need to use WHERE second time after AND
Use this:
String selectQuery = "SELECT *  FROM " + TABLE_HISTORY + " WHERE " + QUERYWORD +  "= '" + word + "' AND " + DISTANCEQ + "= '"+ meter +"' "  ;

A: You're using 2 WHERE Statements; however, this is not allowed, you have to remove the last WHERE statement, since you already have an AND statement.


text:
Q: Ошибка NameError: free variable 'li' referenced before assignment in enclosing scope пытаюсь написать функцию с помощью генераторов списков для удаления дубликатов во входящем списке.
вместо результата выскакивает ошибка
NameError: free variable 'li' referenced before assignment in enclosing scope

Почему так происходит и как это исправить?
def del_dublicates(arr):
    li=[x for x in arr if x not in li]
    return li

    print(del_dublicates([5,9,102,5,6,78,9]))

A: у вас переменная li будет инициализирована только после завершения формирования списка через цикл, а вы уже обращаетесь к ней в цикле, когда переменная еще не существует - поэтому и ошибка
можно модернизировать и работать с проверкой по старому списку формируя новый:
def del_dublicates(arr):
    li=[x for i, x in enumerate(arr) if arr[:i].count(x) == 0]
    return li

ну или вашим способом делайте в лоб тогда:
def del_dublicates(arr):
    li = []
    for x in arr:
        if x not in li:
            li.append(x)
    return li

A: Если порядок не важен, то просто li = set(arr).


text:
Q: TPL Producer Consumer in a FIFO order C# I'm limited to .NET 3.5 and I'm using TPL.
The scenario is producer-consumer but there is no problem of blocking.
PLINQ cannot be used in this scenario (because of limitations) and what we want to achieve is the fastest way to produce many items (where each production is a long-running one, and the number of items exceeds 100,000) but each item must be consumed in a FIFO order (which means, the first item I asked to be produced must be consumed first, even if it was created after other items) and also consumed as fast as possible.
For this problem I tried using a task list, wait for the first item in the list to be completed (taskList.First().IsCompleted()) and then using the consuming function on it, but for some reason I seem to run out of memory (maybe too many items in the task list because of tasks waiting to start?) Is there any better way to do that? (I'm trying to achieve the fastest possible)
Many thanks!

A: OK after the edit - instead of adding the results in the BlockingCollection, add the Tasks in the blocking collection. This has the feature where the items are processed in order AND there is a maximum parallelism which will prevent too many threads from kicking off and you eating up all your memory.
https://dotnetfiddle.net/lUbSqB
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

public class Program
{
    private static BlockingCollection<Task<int>> BlockingCollection {get;set;}

    public static void Producer(int numTasks)
    {
        Random r = new Random(7);
        for(int i = 0 ; i < numTasks ; i++)
        {
            int closured = i;
            Task<int> task = new Task<int>(()=>
            {
                Thread.Sleep(r.Next(100));
                Console.WriteLine("Produced: " + closured);
                return closured;
            });
            BlockingCollection.Add(task);
            task.Start();
        }
        BlockingCollection.CompleteAdding();
    }

    public static void Main()
    {
        int numTasks = 20;
        int maxParallelism = 3;

        BlockingCollection = new BlockingCollection<Task<int>>(maxParallelism);

        Task.Factory.StartNew(()=> Producer(numTasks));

        foreach(var task in BlockingCollection.GetConsumingEnumerable())
        {
            task.Wait();
            Console.WriteLine("              Consumed: "+ task.Result);
            task.Dispose();
        }

    }
}

And the results:
Produced: 0
              Consumed: 0
Produced: 1
              Consumed: 1
Produced: 3
Produced: 2
              Consumed: 2
              Consumed: 3
Produced: 4
              Consumed: 4
Produced: 6
Produced: 5
              Consumed: 5
              Consumed: 6
Produced: 7
              Consumed: 7
Produced: 8
              Consumed: 8
Produced: 10
Produced: 9
              Consumed: 9
              Consumed: 10
Produced: 12
Produced: 13
Produced: 11
              Consumed: 11
              Consumed: 12
              Consumed: 13
Produced: 15
Produced: 14
              Consumed: 14
              Consumed: 15
Produced: 17
Produced: 16
Produced: 18
              Consumed: 16
              Consumed: 17
              Consumed: 18
Produced: 19
              Consumed: 19

A: I thought this was an interesting question so I spent a bit of time on it.
The scenario I understand it is this:

*

*You have a BlockingCollection that is full

*A number of threads start, each trying to add to the BlockingCollection. These calls will all block; that is why they need to occur in parallel.

*As space becomes available, the Add calls will become unblocked.

*The calls to Add need to complete in the order they were received.

First of all, let's talk about code structure. Instead of using a BlockingCollection and writing procedural code around it, I suggest extending the BlockingCollection and replacing the Add method with the functionality you need. It may look something like this:
public class QueuedBlockingCollection<T> : BlockingCollection<T>
{
    private FifoMonitor monitor = new FifoMonitor();

    public QueuedBlockingCollection(int max) : base (max) {}

    public void Enqueue(T item)
    {
        using (monitor.Lock())
        {
            base.Add(item);
        }
    }
}

Here, the trick is the use of a FifoMonitor class, which will give you the functionality of a lock but will enforce order. Unfortunately, no class like that exists in the CLR. But we can write one:
public class FifoMonitor
{
    public class FifoCriticalSection : IDisposable
    {
        private readonly FifoMonitor _parent;

        public FifoCriticalSection(FifoMonitor parent)
        {
            _parent = parent;
            _parent.Enter();
        }

        public void Dispose()
        {
            _parent.Exit();
        }
    }

    private object _innerLock = new object();
    private volatile int counter = 0;
    private volatile int current = 1;

    public FifoCriticalSection Lock()
    {
        return new FifoCriticalSection(this);
    }

    private void Enter()
    {
        int mine = Interlocked.Increment(ref counter);
        Monitor.Enter(_innerLock);
        while (current != mine) Monitor.Wait(_innerLock);
    }

    private void Exit()
    {
        Interlocked.Increment(ref current);
        Monitor.PulseAll(_innerLock);
        Monitor.Exit(_innerLock);
    }
}

Now to test. Here's my program:
public class Program
{
    public static void Main()
    {
        //Setup
        var blockingCollection = new QueuedBlockingCollection<int>(10);
        var tasks = new Task[10];

        //Block the collection by filling it up
        for (int i=1; i<=10; i++) blockingCollection.Add(99);

        //Start 10 threads all trying to add another value
        for (int i=1; i<=10; i++)
        {
            int index = i; //unclose
            tasks[index-1] = Task.Run( () => blockingCollection.Enqueue(index) );
            Task.Delay(100).Wait();  //Wait long enough for the Enqueue call to block
        }

        //Purge the collection, making room for more values
        while (blockingCollection.Count > 0)
        {
            var n = blockingCollection.Take();
            Console.WriteLine(n);
        }

        //Wait for our pending adds to complete
        Task.WaitAll(tasks);

        //Display the collection in the order read
        while (blockingCollection.Count > 0)
        {
            var n = blockingCollection.Take();
            Console.WriteLine(n);
        }

    }
}

Output:
99
99
99
99
99
99
99
99
99
99
1
2
3
4
5
6
7
8
9
10

Looks like it works! But just to be sure, I changed Enqueue back to Add, to ensure that the solution actually does something. Sure enough, it ends up out of order with the regular Add.
99
99
99
99
99
99
99
99
99
99
2
3
4
6
1
5
7
8
9
10

Check out the code on DotNetFiddle


text:
Q: Getting all CNGroups from CNContactStore It seems that there is no way to get the groups from a CNContactStore. The CNContactStore uses a predicate that requires the group identifier to get the group. CNContact does not have any way to find out what group it is in (that I can find).
Is there something I am missing in the documentation? It would really help to be able to see all the available groups in a contact store, and I find it difficult to believe that it isn't possible.

A:
Is there something I am missing in the documentation

Yes. What you are missing in the documentation is the documentation, which tells you the answer:
Pass a nil predicate to fetch all groups.


text:
Q: When we toggle between enable and disable safari extensions, where will the state go and sit on different mac os? After some research got to know that security find-generic-password -l "Safari Extensions List" -g command gives the extensions and their states. The output of the command is not in readable format. I tried saving the password as a plist and opening it, but then it is same. Can someone please guide me how to get the safari extension enable/disable state on different mac versions?

A: Ok so i looked at this and it's a total hack.
Run command with the extension installed, you will see it's name within the field.
Delete the extension from ~/Library/Extensions/Extension_you_Want
Open Safari
Close Safari
Run command again
the item is missing from the password list


text:
Q: meta tag to correct ® I'm having some trouble getting a special character properly encoded.
® keeps coming through instead of the registered trademark symbol. I've tried changing the meta tag to UTF-8 and Windows-1252, but it still comes through in the encoded format?  Can I add a meta tag to fix this?

A: Make sure to save your file with the proper encoding:
.
Here is an example; on the left side, the file is saved with Window-1252 encoding.
On the right side, it's saved with UTF-8 encoding

HTML options
For such characters, encoding with ISO-8859-1 might do it too, but UTF-8 is greatly encouraged.
Make sure your DOCTYPE is clearly defined : <!DOCTYPE HTML>.
Make sure your meta tag is written properly: <meta charset="UTF-8">.

PHP options
If you use PHP within your page, add the following at the beginning of the page:
<?php header('Content-Type: text/html; charset=utf-8'); ?>

If the content is output from a database, you might want to use utf8_encode() to encode different encodings to UTF-8

utf8_encode()
Encodes an ISO-8859-1 string to UTF-8

A: The information about encoding should correspond to the actual encoding. So instead of making guesses and trial and error, find out what the encoding really is. It seems to be UTF-8, and if declaring UTF-8 in a meta tag does not help, the probable culprit is an HTTP header that the server sends and that declares a different encoding, trumping the meta tag. Use e.g. an HTTP header viewer to check out the situation.
If the server announces iso-8859-1 or windows-1252 and if you cannot change this, then you just have to use that encoding instead of UTF-8. Then save the page in your authoring program as windows-1252 encoded.


text:
Q: Kendo combobox not show the Text corresponding to value from modal I have a partial view with a combobox. When try to render partial view with modal(contains data from database), it shows only the value field. i want to show the text field of that value field. Help me please.
@(Html.Kendo().ComboBoxFor(m => m.divCode)
    .DataTextField("Name")
    .DataValueField("ID")
    .HtmlAttributes(new { style = "width:160px" })
    .SelectedIndex(0)
    .AutoBind(false)
    .Placeholder("Select Div Code")
    .Filter(FilterType.Contains)
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetDivision", "AssetTransaction");
        });
    })
)

A: There is no fault i found with your view code. Its just looks fine to me. I think you are doing same as this sample.
I suspect your value assignment to c.divisioncode, Name = c.divisionname. Just make sure you are getting and setting value and text properly From your db service calls to view model and assigning correctly. For that you can use and see the "quick watch" while debugging the GetDivision "Action" in AssetTransaction "controller".
Sample Code i found:
@(Html.Kendo().ComboBox()
          .Name("products")
          .DataTextField("ProductName")
          .DataValueField("ProductID")
          .HtmlAttributes(new { style = "width:250px" })
          .Filter("contains")
          .AutoBind(false)
          .MinLength(3)
          .DataSource(source => {
              source.Read(read =>
              {
                  read.Action("GetProducts", "Home");
              })
              .ServerFiltering(true);
          })
    )

A: I was facing similar issue since my model has attribute for code.
I changed
AutoBind(false)

to
AutoBind(true).

Now it shows the Text instead of the Value

A: You can set AutoBind to false (which you've already done), and then use the Text property to define the text that will be displayed:
@(Html.Kendo().ComboBoxFor(m => m.divCode)
.DataTextField("Name")
.DataValueField("ID")
.HtmlAttributes(new { style = "width:160px" })
.SelectedIndex(0)
.AutoBind(false)
.Text(Model.YourTextFieldToDisplay)  // add this and modify to your needs
.Placeholder("Select Div Code")
.Filter(FilterType.Contains)
.DataSource(source =>
{
    source.Read(read =>
    {
        read.Action("GetDivision", "AssetTransaction");
    });
})


text:
Q: How can I automate Chocolatey install from a private Azure DevOps hosted feed? I've got a Chocolatey package hosted in a private Azure Devops feed. The feed requires authentication. I'm trying to run this from a PowerShell script in a build task.
choco install typewriter --source="https://o365x.pkgs.visualstudio.com/_packaging/Graph/nuget/v3/index.json" --yes --force --password=PAT
I observe that it attempts basic auth. Alternate credentials are disabled for my org. I tried to use a personal access token as the password (no username) and it doesn't work. Is there a way to do this?

A: Azure DevOps feeds are v3, but Chocolatey only supports v2.
You should try replacing /v3/index.json in the source with /v2, e.g. in your case:
https://o365x.pkgs.visualstudio.com/_packaging/Graph/nuget/v2
Microsoft has actually documented that (for nuget) in:
https://learn.microsoft.com/en-us/azure/devops/artifacts/nuget/nuget-exe?view=azure-devops#add-a-feed-to-nuget-2


text:
Q: Proving $\forall x\in \mathbb R$ and $ \forall A>0: \exists B>0 \ s.t \ \forall y\in \mathbb R, \ |y-x|\le A \Rightarrow |f(x)-f(y)|\le B$ Let $f:\mathbb R\to \mathbb R$ be a continuous function. Prove that $\forall x\in \mathbb R$ and $ \forall A>0: \exists B>0 \ s.t \ \forall y\in \mathbb R, \ |y-x|\le A \Rightarrow |f(x)-f(y)|\le B$
So I notice that it's similar to the $\epsilon - \delta$ definition, so to make things easier, let's call $B=\epsilon$ and $A=\delta$. I understand that I need to show that there's some $B$ such that for all $y$ something is true.
A continuous function is differentiable for all $x$, I tried to work with the definitions but didn't get far:
If $f$ is differentiable then from the definition of a derivative: $\displaystyle\lim_{x\to y} \frac{f(x)-f(y)}{x-y}=f'(y)$
And from the defintion of a limit of a function: $\forall \epsilon>0:\exists\delta>0:\forall0<|x-y|<\delta\Rightarrow |f(x)-L|<\epsilon$
So if $L=f'(y)$ then $|f(x)-\frac{f(x)-f(y)}{x-y}|<\epsilon $ But that is leading me nowhere.
Any other ideas? Maybe I don't understand the question correctly ?

A: This follows from the fact that every continuous real-valued function defined on a closed interval is bounded on that interval. Indeed, since $f:\mathbb{R}\to\mathbb{R}$ is continuous, for any fixed $x\in\mathbb{R}$, the function $y\mapsto |f(x)-f(y)|$ is also continuous on $\mathbb{R}$, hence bounded on any interval of the form $[x-A,x+A]$ with $A >0$. Thus, given $x$ and $A$, define
$$ B_0 = B_0(x,A) = \sup \{\,|f(x)-f(y)|\;:\; y \in [x-A,x+A]\,\}.$$
Since $|f(x)-f(y)|\geq 0$, we have $B_0 \geq 0$. Now, take e.g. $B = \max\{B_0,1\}$, or $B = B_0+1$, if you prefer so, to ensure that $B$ is strictly positive.


text:
Q: Checking the validity of an argument Please how do I use a truth table to check the validity of the following argument.
All teenagers are smart.
All smart people study hard.
Jake does not study hard.
Therefore, Jake is not a teenager.
Edit:
While the answer below is right, how to I proceed If I let
teenagers by $t$, smart by $s$, study hard by $h$ and Jake by $j$, then  'all teenagers are smart would be represented by $t→s$; Likewise, all smart people study hard, by $s→h$. How do I represent Jake does not study hard. How do I represent Jake is not a teenager?

A: There's a difference in the types of $t$ and $s$ and the type of $j$. You wanted to represent $t$ and $s$ as truth values, but in fact they are functions from the set $P$ of people to the truth values. The function $t$ assigns to a person the value true if this person is a teenager, other persons get the value false, and likewise the function $s$ gives the value true for smart people and the value false for non-smart people. Now the sentence "all teenagers are smart" can be seen as (the notation $\forall p$ means "for every person $p$")
$$
\forall p(t(p)\to s(p)),\tag{1}
$$
With a truth table, we can find that $t(p)\to s(p)$ is equivalent to $\neg s(p)\to\neg t(p)$. Note that the truth value of $t(p)\to s(p)$ is only false if $t(p)$ is true but $s(p)$ is false. Likewise, the value of $\neg s(p)\to\neg t(p)$ is only false if $\neg s(p)$ is true and $\neg t(p)$ is false. Therefore, we get the following truth table
t(p) | s(p) | t(p) -> s(p) | ~t(p) | ~s(p) | ~s(p) -> ~t(p)
-----------------------------------------------------------
 0   |  0   |  1           |  1    |  1    |  1
 0   |  1   |  1           |  1    |  0    |  1
 1   |  0   |  0           |  0    |  1    |  0
 1   |  1   |  1           |  0    |  0    |  1

and we see that the statement in (1) can be equivalently written down as
$$
\forall p(\neg s(p)\to \neg t(p)).
$$
It reads: for all persons it holds that if that person is not smart then it is not a teenager. Similarly, $h$ is a function from $P$ to $\{\mathrm{true},\mathrm{false}\}$ that sends the value true to the people who study hard and the value false to the people who do not study hard. The sentence "all smart people study hard" is then represented as
$$
\forall p(s(p)\to h(p)),
$$
which is equivalent to
$$
\forall p(\neg h(p)\to \neg s(p))
$$
by the truth table
s(p) | h(p) | s(p) -> h(p) | ~s(p) | ~h(p) | ~h(p) -> ~s(p)
-----------------------------------------------------------
 0   |  0   |  1           |  1    |  1    |  1
 0   |  1   |  1           |  1    |  0    |  1
 1   |  0   |  0           |  0    |  1    |  0
 1   |  1   |  1           |  0    |  0    |  1

Now we can look at Jake. Jake is a person $j$ for which $\neg h(j)$ is true. The statement $\neg h(j)\to \neg s(j)$ is also assumed to be true, so it follows by the above truth table that $\neg s(j)$ is true. Now we look in the first truth table and see that, because the statement $\neg s(j)\to \neg t(j)$ is assumed to be true, it follows that $\neg t(j)$ is true.


text:
Q: Azure Function App in .Net Framework 4.6.1 suddenly stops working I have an Azure Function App running .Net Framework (target framework 4.6.1) but is now failing. Per documentation, the Function was set up as .Net Core and then downgraded to v1 to support Framework. The Function worked after I initially published it from Visual Studio, but soon stopped working.
I get a 500 error when I try to hit the function from my mobile app. When I go to a function within the app in Azure Portal, the following error appears:

The function runtime is unable to start.

I have restarted the Function App, as well as actually stopping and then starting again. I tried to re-publish the code from Visual Studio, but that fails, saying:

The attempt to publish the ZIP file through https://***.scm.azurewebsites.net/api/zipdeploy failed with HTTP status code InternalServerError.

Application Insights had been working on it previously, but it isn't showing any network requests anymore.
Is there anywhere to go to get better diagnostics? Every error I've seen has been vague. Additionally, are there known issues with running Azure Function apps on .Net Framework 4.6.1 that I need to be aware of?

A:
The function runtime is unable to start.

You'd better watch log stream / use app insights to capture what is the problem. (you can also check the logs using Kudu)
I'm not 100% sure, but I believe there's a high chance you're not with runtime v1:

Additionally, are there known issues with running Azure Function apps on .Net Framework 4.6.1 that I need to be aware of?

Besides you're locked with some specific dependency versions, there are more important details to pay attention:
https://github.com/Azure/app-service-announcements/issues/129
I've been in this "hell" of making v1 to work with more recent dependency versions. It's super complex and not very stable. If you really need to stick v1, I strongly recommend you to migrate your code to Azure Container Instances and use Azure Function v1 just as a triggering mechanism.
If possible, you should migrate to core and use the latest runtime version.

A: Depolyments started failing for me with the cryptic "InternalServerError" after I updated the storage account access key used by the function app service.
You need to update the following configuration settings on your app service:

*

*AzureWebJobsDashboard

*WEBSITE_CONTENTAZUREFILECONNECTIONSTRING

*AzureWebJobsStorage


text:
Q: Trying to use Powershell to run four instances of modelling software, check if one stops and start another We have a lot of air quality modelling to do and I have been asked to write some script that will run multiple instances of the software concurrently, starting a new process if it finds there are less than four processes running already (four is the max number of instances the software allows).
I've been given the following script that someone had already and  slightly adapted it.
function waitadms($p){

do{

    $ProcessActive = Get-Process $p[0] -ErrorAction SilentlyContinue

}
until ($ProcessActive.count -lt $p[1])

    " done"

}

#waitadms("ADMSUrbanModel",4)

#break
$scn = "C:\Models\Test"

$upls = ls * -Recurse  -include *.upl  -path $scn
$upls | foreach{$_.name;waitadms("ADMSUrbanModel",4);Start-Sleep -s 10;&("C:\Program Files (x86)\CERC\ADMSRoad\ADMSUrbanModel.exe") /e2 /ADMSRoads $_.fullname}

the $upls variable is a list of the models that are needed to run and the function waitadms is supposed to run a new instance of the model for each entry in the list.
If I run the script, it opens the first four models, but then when its found one finished, it fails to open a new one. However, the Powershell window prints the next entry in the list, so its obviously finding the right file. It just doesn't open the actual software (ADMSUrbanModel.exe) like it did for the first four.
The code may be a bit dodgy, I just don't know. But it seems funny that it opens the first four instances correctly then fails when one finishes.


text:
Q: c++ [] with vector< vector > I'm having trouble with accessing elements of the last vector that is contained within a vector.
std::vector<std::vector<int>> vec1 = {{1,2,3}, {1,2,3}, {1,2,3}, {1,2,3}}.

How to get the second element of the last element of vec1 ?
I try:

*

*vec1.[vec1.end() - 1][1]

*vec1.[vec1.at(vec1.end()) - 1][1]
How can I use at when there are 2 dimensions?
please explain the use of [] and .at().

A: With back, you might simply do:
vec1.back()[1];

instead of vec1.[vec1.size() - 1][1].
or even the iterator way:
(*(vec1.end() - 1))[1]; // or (vec1.end() - 1)->at(1);

please explain the use of [] and .at().

at does bound checking contrary to operator [] or back.
So for bound checking, use at instead of above alternative:
vec1.at(vec1.size() - 1).at(1); // std::out_of_range thrown is case of out of bound access.

A: void test()
{
    std::vector<std::vector<int>> vec1 = { { 1,2,3 },{ 1,2,3 },{ 1,2,3 },{ 1,2,3 } };
    int last_sec = *(++(--vec1.end())->begin());
}

to access the second element of the last element of vec1, you can use --end() to get the last iterator of the vec1, and ++(it->begin()) return the second iterator of it, then dereference to get the element.
std::vector:operator[] return type& without bound checking.
std::vector::at()
Returns a reference to the element at specified location pos, with bounds checking.


text:
Q: Adding entity to DbSet does not mark entity as Added and thus is not commited I've created a sample repo to demo the problem.
Entities:
public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class Attributes
{
    public Person Person { get; set; }

    public string Attribs { get; set; }
}

DbContext Config
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Attributes>()
                .Property<int>("PersonId");

    modelBuilder.Entity<Attributes>()
                .HasKey("PersonId");

    modelBuilder.Entity<Attributes>()
                .HasOne(_ => _.Person)
                .WithOne()
                .IsRequired();

    modelBuilder.Entity<Attributes>()
                .Property(_ => _.Attribs)
                .HasColumnName("Attributes");
}

What works very well for Attributes?

*

*Read

*Update

*Delete

Create does not work.
Even though a new Attributes instance is added to the DbSet it's not marked as Added and thus not commited to the db. Marking the entity state explicitly as Added commits the instance correctly to the db. This explicitness is only necessary for Attributes. All other entities in my real project are correctly added through DbSet.Add().
What's wrong with my expectations?
static void Main(string[] args)
{
    using (var dbContext = new Context())
    {
        // reading works well
        var readEntity = dbContext.Set<Attributes>()
                                  .First(_ => _.Person.Id == 1);

        Console.WriteLine($"Read entity has attributes value: {readEntity.Attribs}");
    }

    using (var dbContext = new Context())
    {
        var person = dbContext.Set<Person>().First(_ => _.Id == 2);

        var attributes = new Attributes
        {
            Person  = person,
            Attribs = "some"
        };

        var state = dbContext.Set<Attributes>().Add(attributes);
        Console.WriteLine($"State: {state.State}");

        var count = dbContext.SaveChanges();
        Console.WriteLine($"Changes written: {count}");

        if (count == 0)
        {
            Console.WriteLine("Trying again with explicitly setting entity state to Added.");

            state.State = Microsoft.EntityFrameworkCore.EntityState.Added;
            count = dbContext.SaveChanges();

            Console.WriteLine($"Changes written in second try: {count}");
        }
    }

    Console.WriteLine("done");
    Console.ReadLine();
}

A: Proposed workaround by divega works for now.
public class Attributes
{
    private int personId; // workaround

    public Person Person { get; set; }

    public string Attribs { get; set; }
}

Have a look at https://github.com/aspnet/EntityFrameworkCore/issues/11919 to check if bug has been fixed.


text:
Q: Graphical Layout shows null Pointer exception I have a UI design for an application. As we know that there are two view while designing a UI for an app in android in eclipse one the xml view and other the graphical layout. i am having a problem that i cannot get graphical layout of my xml. it shows a null pointer exception when i switch to graphical layout. Any suggestions..?

A: I think you might find that the View.isInEditMode() function is what you are looking for.
Use it on any view that you have a reference to in the Activity.
If it returns true, don't attempt to get the reference that you were trying to get.
It's a little hard to tell if this will fix it for you, but you should definitely try this.

A: i think you are using some custom drawable(ie either shapes or style). it is not shown at design time but you will able to see when you run the project


text:
Q: Dynamically graph points with Highcharts How can I dynamically graph points from a table? The table has two columns dedicated to the x and y coordinates and an additional column for duration.
Example
Say I have the table shown below. The Date and Effort columns would compose the x,y coordinates (Timestamp, Effort) for a line chart. This line chart would have data-points based on cumulative totals from the Timestamp and Effort columns. The Duration column would determine how long the entry had an impact on the data-points of the line chart. So based on this table, I would want a line chart with the coordinates listed under Data-Points.
Timestamp        Effort  Duration

4/13/2016 12:13:12.15    10     100

4/13/2016 12:13:12.80    12     100

4/13/2016 12:13:13.15    30     100

4/13/2016 12:13:13.80    50     100
Data-Points:

(4/13/2016 12:13:12.15, 10)

(4/13/2016 12:13:12.80, 22)

(4/13/2016 12:13:13.15, 42)

(4/13/2016 12:13:13.80, 80)

A: One of the Highcharts demos shows precisely how you can accomplish this using a static HTML table: http://www.highcharts.com/demo/column-parsed.
I've created a fiddle using your sample data and plotted it as a line chart, per your requirement: http://jsfiddle.net/brightmatrix/qgvkp0t0/
Your data table would be coded similar to the following:

      Time
      Effort

      4/13/2016 12:13:12.15
      10

      4/13/2016 12:13:12.80
      22

      4/13/2016 12:13:13.15
      42

      4/13/2016 12:13:13.80
      80

You would then create your chart using the following code. Note the data attribute that calls to your HTML table's ID:
$(function () {
  $('#container').highcharts({
    data: {
      table: 'datatable'
    },
    chart: {
      type: 'line'
    },
    title: {
      text: 'Data extracted from a HTML table in the page'
    },
    xAxis: {
      type: 'category'
    },
    yAxis: {
      allowDecimals: false,
      title: {
        text: 'Units'
      }
    },
    tooltip: {
      formatter: function () {
        return '' + this.series.name + '
' + this.point.y;
      }
    }
  });
});

One thing to note: without any modifications, your timestamp data would be read into your x-axis as a datetime type. This would leave you with empty points for those dates or times in between.
In my example, I explicitly set the x-axis type to category, so that there is exactly one plot on the chart for each data point.
Now, to get the x-axis labels to appear in a more readable format, you can explore the xAxis.labels.formatter attribute (http://api.highcharts.com/highcharts#xAxis.labels.formatter) and the Highcharts.dateFormat() function (http://api.highcharts.com/highcharts#Highcharts.dateFormat).

Update (July 13, 2016): I've been able to solve the original poster's requirement of adding cumulative points based on data in an HTML table, but not the removal of dates that are older than the current data point's duration. My modifications are below.

In order to take the data from an HTML table and work with it prior to plotting the chart, I used the data.columns attribute (see http://api.highcharts.com/highcharts#data.columns).
Before your chart options are declared, I wrote this code to go through the HTML table and add the content to arrays.
  // read through the HTML table and calculate cumulative effort
  // solution inspired by:
  // 1. http://stackoverflow.com/questions/3248869/how-do-i-get-data-from-a-data-table-in-javascript
  // 2. http://stackoverflow.com/questions/10057226/how-to-get-html-table-td-cell-value-by-javascript

  // set the series name as the default; this is the first entry read by data.columns
  var seriesTime = ['Time'];
  var seriesEffort = ['Effort'];
  var seriesDuration = ['Duration'];

  var table = document.getElementById('datatable');
  var noRows = table.rows.length;

    // go through the table and assign values to the series arrays
  // start with the second row (r = 1) to omit the table's header
  for (var r = 1; r < noRows; r++) {
    seriesTime.push(Date.parse(table.rows[r].cells[0].innerHTML));
    seriesEffort.push(parseInt(table.rows[r].cells[1].innerHTML));
    seriesDuration.push(parseInt(table.rows[r].cells[2].innerHTML));
  }

I then use those arrays as follows:
data: {
  // refer to demo link at: http://api.highcharts.com/highcharts#data.columns
  columns: [
    seriesTime,         // categories
    seriesEffort        // first series
  ]
},

The way this works is that the first item expected in these arrays is the series name, which is why I have as the default value when the arrays are first declared.
Now, once you have the data in arrays, you would need to run through them to calculate your cumulative totals and subtract those whose duration has passed. Unfortunately, I wasn't successful on the duration piece. Here's what I wrote in my fiddle:
    // next, go through the series arrays and tally up the cumulative totals based on duration
  for (var t = 2; t < seriesTime.length; t++) {

    seriesEffort[t]+=seriesEffort[t-1];

    for (var e = 1; e < seriesEffort.length; e++) {
        if (seriesTime[e] < seriesTime[t] - seriesDuration[t]) {        // NOTE: this is where I'm getting stuck
        seriesEffort[t]-=seriesEffort[e];
      } else {
        //seriesEffort[t]+=seriesEffort[e];
      }

    }
  }

I hope this gets you closer to your solution. I apologize that I couldn't get this 100% mocked up for you.

A: I ended up preprocessing the data. First, I got all of the data points into the series cumulatively. Next, I updated the datetime x values with the durations. Finally, I subtracted each individual y value whose x value was less than the cumulative data point's x value.


text:
Q: Unresolved reference in mutableListOf jetpack compose I have the following code:
val musu = MusuButton(buttonText = "hmmm" , checkCorrect = {})
val  gridItems = mutableListOf<MusuButton>()

The musu val can see the MusuButton just fine. I am getting an unresovled reference in the mutableListOf<MusuButton>
It says the MusuButton is unresolved reference,


text:
Q: iOS App - how do people handle Internet connection downtime to provide the best UX? I'm about to begin building my 2nd React Native app and I'd like a friendlier way to handle any Internet connection downtime should it suddenly drop out. Currently I check for a connection when executing any Fetch call and then use try/catch to display a retry component if it failed. This renders a button which re-calls the function on-press. I'm Just curious to see how other people handle this and whether I can improve my users experience!

A: I would have it retry 3 times automatically. If your app can partially function offline, then you can just show that part as offline and continue to try and update every second or so.


text:
Q: Inserting into MySQL from Python using mysql.connector module - How to use executemany() to inert rows and child rows? I have a MySQL server running on a remote host. The connection to the host is fairly slow and it affects the performance of the Python code I am using. I find that using the executemany() function makes a big improvement over using an loop to insert many rows. My challenge is that for each row I insert into one table, I need to insert several rows in another table. My sample below does not contain much data, but my production data could be thousands of rows.
I know that this subject has been asked about many times in many places, but I don't see any kind of definitive answer, so I'm asking here...

*

*Is there a way to get a list of auto generated keys that were created using an executemany() call?

*If not, can I use last_insert_id() and assume that the auto generated keys will be in sequence?

*Looking at the sample code below, is there a simpler or better way do accomplish this task?

*What if my cars dictionary were empty? No rows would be inserted so what would the last_insert_id() return?

My tables...
Table: makes
 pkey bigint autoincrement primary_key
 make varchar(255) not_null

Table: models
 pkey bigint autoincrement primary_key
 make_key bigint not null
 model varchar(255) not_null

...and the code...
...
cars = {"Ford": ["F150", "Fusion", "Taurus"],
        "Chevrolet": ["Malibu", "Camaro", "Vega"],
        "Chrysler": ["300", "200"],
        "Toyota": ["Prius", "Corolla"]}

# Fill makes table with car makes
sql_data = list(cars.keys())
sql = "INSERT INTO makes (make) VALUES (%s)"
cursor.executemany(sql, sql_data)
rows_added = len(sqldata)

# Find the primary key for the first row that was just added
sql = "SELECT LAST_INSERT_ID()"
cursor.execute(sql)
rows = cursor.fetchall()
first_key = rows[0][0]

# Fill the models table with the car models, linked to their make
this_key = first_key
sql_data = []
for car in cars:
    for model in cars[car]:
        sql_data.append((this_key, car))

    this_key += 1

sql = "INSERT INTO models (make_key, model) VALUES (%s, %s)"
cursor.executemany(sql, sql_data)

cursor.execute("COMMIT")
...

A: I have, more than once, measured about 10x speedup when batching inserts.
If you are inserting 1 row in table A, then 100 rows in table B, don't worry about the speed of the 1 row; worry about the speed of the 100.
Yes, it is clumsy to get the ids generated by an insert.  I have found no straightforward way like LAST_INSERT_ID, but that works only for a single-row insert.
So, I have developed the following to do a batch of "normalization" inserts.  This is where you a have a table that maps strings to ids (where the string is likely to show up repeatedly).  It takes 2 steps:  First a batch insert of the "new" strings.  Then fetch all the needed ids and copy them into the other table.  The details are laid out here:  http://mysql.rjweb.org/doc.php/staging_table#normalization
(Sorry, I am not fluent in python or the hundred other ways to talk to MySQL, so I can't give you python code.)
Your use case example is "normalization"; I recommend doing it outside the main transaction.  Note that my code takes care of multiple connections, avoiding 'burning' ids, etc.
When you have subcategories ("make" + "model" or "city" + "state" + "country"), I recommend a single normalization table, not one for each.
In your example, pkey could be a 2-byte SMALLINT UNSIGNED (limit 64K) instead of a bulky 8-byte BIGINT.


text:
Q: Update a nested value after query I have following data structure in Mongo:
{
    _id: ObjectId('5fea5c2dcfe3920cdbe10313'),
    video_path: '/media/out_.mp4',
    frame_skip: '100',
    frame_c: '20',
    api_processed: false,
    samples: [
        {
            frame: 301,
            eroded_hu_moments: [
                [
                    0.002703944102615306
                ]
            ],
            eroded_sample_b64: '/9j/4AAQSkZJRgABA...',
            eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAA...'
            },
        {
            frame: 302,
            eroded_hu_moments: [
                [
                    0.002703944102615306
                ]
            ],
            eroded_sample_b64: '/9j/4AAQSkZJRgABAQAAAQABAAD/...',
            eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAAAQABAAD...'
            },
        {
            frame: 303,
            eroded_hu_moments: [
                [
                    0.002703944102615306
                ]
            ],
            eroded_sample_b64: '/9j/4AAQSkZJRgABAQAAAQA....',
            eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAAAQA....'
            }
    ],
    TOT_execution_time: '0:00:07.215424'
}

My goal is to:

*

*Find all the "eroded_sample_b64" in all objects where "api_processed"=false

*Do some processing

*Insert in the same nested "frame" structure the results

*update "api_processed" = true

I'd like to object something like this:
{
_id: ObjectId('5fea5c2dcfe3920cdbe10313'),
video_path: '/media/out_.mp4',
frame_skip: '100',
frame_c: '20',
api_processed: true,
samples: [
    {
        frame: 301,
        eroded_hu_moments: [
            [
                0.002703944102615306
            ]
        ],
        eroded_sample_b64: '/9j/4AAQSkZJRgABA...',
        eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAA...'
        results: 'test_OK'
        },
    {

I've tryed with following code:
client = MongoClient("mongodb://root:example@localhost:27017/")
mydb = client["image"]
mycol = mydb["samples"]

mydoc = mycol.find( { "api_processed": False},
{ "_id": 1,"samples.eroded_sample_inverted_b64": 1, "samples.frame": 1}
)
url = 'http://localhost:8000/prediction/'
for x in mydoc:
  for sample in x.get('samples', []):
    ##SOME PROCESSING

    ###SET
    doc = mycol.update_one(
             {"_id": x['_id'], "samples.frame": sample['frame']},
             {"$set": {
                 "api_processed": true,
                 "samples": { "results": "some test res" }
                 }}
             )

But unfortunately i obtain wrong results, as "results" key is not nested in the right "frame":
{
    _id: ObjectId('5fea5c2dcfe3920cdbe10313'),
    video_path: '/media/out_.mp4',
    frame_skip: '100',
    frame_c: '20',
    api_processed: false,
    samples: [
        {
            frame: 301,
            eroded_hu_moments: [
                [
                    0.002703944102615306
                ]
            ],
            eroded_sample_b64: '/9j/4AAQSkZJRgABA...',
            eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAA...'
            },
        {
            frame: 302,
            eroded_hu_moments: [
                [
                    0.002703944102615306
                ]
            ],
            eroded_sample_b64: '/9j/4AAQSkZJRgABAQAAAQABAAD/...',
            eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAAAQABAAD...'
            },
        {
            frame: 303,
            eroded_hu_moments: [
                [
                    0.002703944102615306
                ]
            ],
            eroded_sample_b64: '/9j/4AAQSkZJRgABAQAAAQA....',
            eroded_sample_inverted_b64: '/9j/4AAQSkZJRgABAQAAAQA....'
            },
        {
            results: 'test_OK'
        }
    ],
    TOT_execution_time: '0:00:07.215424'
}

I don't really understand what I'm doing wrong.
Any help/comments will be really appreciated.
Many thanks

A: In your update you need to use the $ positional operator.
    doc = mycol.update_one(
        {"_id": x['_id'], "samples.frame": sample['frame']},
        {"$set": {
            "api_processed": True,
            "samples.$.results": "some test res"
        }}
    )


text:
Q: How to integrate Android Beacon Library in my project? I found this Android Beacon Library in the net, and i found it quite good. But I want to integrate the open source project in my app with some modification in the code so as to display the alert on beacon detection and some other scenarios.
Actually i am new bee to android, so if anyone can help me out how to integrate the modified code in the app?
Thanks in advance.

A: While it is certainly possible to modify the code of the Android iBeacon Library, it is not necessary to make any modifications "so as to display the alert on beacon detection" because this ability is present out of the box.  Making modifications to a library and then using it in a custom project is also a pretty big hill to climb for somebody new to Android development.  Before attempting to do this all at once I would first do the following in order:

*

*Learn how to build a Hello World Android app and run it on your phone.

*Learn to use Android Studio.

*Build and run the sample application for the library.

*Make a new app from scratch that uses an unmodified version of the library in binary form to detect iBeacons and display an alert.

*Learn to the Gradle command line build tool and Gradle wrapper

*Build an unmodified copy of the library source code from the command line with the command ./gradlew release

*Use the newly created binary release from (6) in your custom project from (4).

Once you have done all of the above, you can try making modifications to the library source code and getting these modifications to work in your project.
EDIT: The library mentioned above has been replaced by the Android Beacon Library with a reference app here.


text:
Q: Control lost focus I have a form, and when I press a keyboard key over the form Key_Up event works fine, but when I press any button on ToolStrip, I lost Form forever and Key_Up event doesn't work anymore.
I want a solution that when I put the mouse pointer over PictureBox then give Form the focus, like VMware window.
private void frmMonitor_KeyUp(object sender, KeyEventArgs e)
{
     if (e.KeyValue == 18)
        return;
     pc.PacketSystem.Send_KeyBoardEventPacket(e.KeyValue.ToString());
}
private void picSnap_MouseMove(object sender, MouseEventArgs e)
{
     this.Focus();
}

A:  private void picSnap_MouseMove(object sender, MouseEventArgs e)
{
            this.Activate();
            this.KeyPreview=true;
}

thanks, Roman


text:
Q: Application Central Limit Theorem in Walds Confidence Intervals I use the Empirical Cumulative Distribution Function (EDCF)
$$
\hat{F}_n (x)=\frac{1}{n} \sum_{i=1}^{n} \mathbb{1}_{\{X_i \leq x\}}.
$$
I know that $Y := n \hat{F}_n (x) \sim Bin(n,p)$ with $p := F(x)$.
Let $\hat{p}_n := \frac{Y}{n}$, then it should follow by the Central Limit Theorem that
$$
\sqrt{n} \frac{\hat{p}_n-p}{\sqrt{p(1-p)}} \overset{d}{\rightarrow} N(0,1).
$$
Can somebody show me the steps how to get there?
I start of with the CLT
$$
\sqrt{n} (Y_n-np) \overset{d}{\rightarrow} N(0,np(1-p)),
$$
and after a few steps I get the result above without the root in the denominator on the left side.

A: If $(Z_n)$ is a sequence of iid random variable with mean $\mu$ and variance $\sigma^2$ then $\overline Z_n:=\frac1{n}\sum_{i=1}^nZ_i$ has mean $\mu$ and variance $\frac1{n^2}\sum_{i=1}^n\mathsf{Var}(Z_i)=\frac{\sigma^2}n$.
Then: $$U_n:=\frac{\overline{Z_n}-\mathbb E\overline{Z_n}}{\sqrt{\mathsf{Var}(\mathbb E\overline{Z}_n)}}=\frac{\sqrt{n}(\overline{Z_n}-\mu)}{\sigma}$$has mean $0$ and variance $1$ and according to the CLT we have $U_n\stackrel{d}{\to}N(0,1)$ where $N(0,1)$ has standard normal distribution.
Apply this on $Z_i=\mathbf1_{X_i\leq x}$.


text:
Q: ErrorException Undefined variable when trying to show data in view So i was trying to display a record from a database with laravel, and i have defined the variable in @foreach statement but when i run it it shows ErrorException Undefined variable , although all variable already inside the foreach statement, am i missing a method function in my controller?
this is the view
welcome.blade.php

                            @foreach ($guestbooks as $guestbook)

{{ Carbon\Carbon::parse($guestbook->created_at)->format('d-m-Y')  }} /  di Rakitan

{{ $guestbooks->name }}

{!! \Illuminate\Support\Str::words($guestbook->message, 50, '...') !!}

                             $post->id]) }}" class="read-more">Lanjutkan Baca

{{ Carbon\Carbon::parse($guestbook->created_at)->format('d-m-Y')  }} /  di Rakitan

{{ $guestbook->name }}

{!! \Illuminate\Support\Str::words($guestbook->message, 50, '...') !!}

                             $post->id]) }}" class="read-more">Lanjutkan Baca

{{ Carbon\Carbon::parse($guestbook->created_at)->format('d-m-Y')  }} /  di Rakitan

{{ $guestbook->name }}

{!! \Illuminate\Support\Str::words($guestbook->message, 50, '...') !!}

                             $post->id]) }}" class="read-more">Lanjutkan Baca
                            @endforeach

this is the controller
GuestbookController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Guestbook;

class GuestbookController extends Controller
{
    public function index()
    {
        $guestbooks = Guestbook::get();
        return view('post.post_textarea',[
            'guestbooks' => $guestbooks
        ]);
    }

    public function store(Request $request)
    {
        Guestbook::create([
            'name' => $request->name,
            'message' => $request->message
        ]);
        return redirect()->back();
    }
}

and this is the routes
Route::get('/posting','GuestbookController@index')->name('guestbook');
Route::post('/posting','GuestbookController@store')->name('guestbook.store');

A: Your GuestbookController function index() is returning a view called post.post_textarea and passing your $guestbook variable to that view, while you are trying to get that variable in your welcome.blade.php.
Change your index function to return welcome view like this:
public function index()
    {
        $guestbooks = Guestbook::get();
        return view('welcome',[
            'guestbooks' => $guestbooks
        ]);
    }

A: i figured the problem was that there are two routes routing into the same url as Route::get('/posting','GuestbookController@index')->name('guestbook'); so i delete the other one and it works thanks about that typo tough @Denis Ćerić


text:
Q: c# - what is best persistence approach/tool/library for a Directed Graph What is best persistence approach/tool/library for a Directed Graph in C#.  That is assuming I have a class model for a directed graph (e.g. Nodes & Relationships, or Vertex's and Edge's if you like), what would you recommend regarding persisting to a SQL Database?  (or if you wish a 2nd question would be where I don't specify a SQL database as a requirement)
For example I was thinking I would simply go with a Relationships table and a Nodes table.

A: I'm not familiar with the tools available in C#, but your question seems to be mostly one about storage rather than C#.
How you store a DAG will no doubt depend on the use cases you have in mind.  You can represent a DAG in two tables in a relational database, for example, where one table holds information about the nodes (A, B, C, etc.) and another holds information about the edges between the nodes (A -> B, A -> C, etc.).
A graph database such as Neo4j might also be a good way to go.
Your mileage will vary when it comes to things like horizontal scaling and concurrent access, depending on the approach you adopt.  You may want to keep a denormalized representation around for speeding up some kinds of queries, but such a strategy involves tradeoffs you'll want to understand before going with it.

A: A Nodes table and a Relationships (link) table seems the most natural to me since that's generally (always?) how you implement many-to-many relationships in a relational database, and a directed graph is basically a many-to-many relationship mapping for nodes (right?).  I suppose you could store it in an XML field, or some binary value, but that really ignores the fact that you have a database.
If you didn't have a database, and were writing directly to some type of file, I would probably still use a similar mechanism of uniquely identifying each node with a key and separately defining how the key values are related.
This all assumes that your directed graph is many-to-many and not strictly one-to-many.  If it were strictly one-to-many, without loops, I might use XML if writing to a file (utilizing the fact that child elements in the XML are related to their parent), or foreign keys if writing to a database (which would work well even if there were loops).


text:
Q: yast2 crashed at the moment of loading the install software module While trying to run a module from within yast in Tumbleweed openSUSE, the module crashed and it says in terminal
Run command: /sbin/yast2 sw_single &
terminate called after throwing an instance of 'YUIPluginException'
  what():  Couldn't load plug-in qt
YaST got signal 6 at file /usr/share/YaST2/modules/Wizard.rb:782
  sender PID: 7211
/sbin/yast2: line 440:  7211 中止                  (core dumped) $ybindir/y2base $module "$@" "$SELECTED_GUI" $Y2_GEOMETRY $Y2UI_ARGS

What this could be ?
 zypper search libyui*

is:
S | 名前                     | 概要                                 | 種類
--+--------------------------+--------------------------------------+-----------
  | libyui-devel             | Libyui header files                  | パッケージ
i | libyui-doc               | Libyui documentation                 | パッケージ
  | libyui-ncurses-devel     | Libyui-ncurses header files          | パッケージ
i | libyui-ncurses-doc       | Libyui-ncurses documentation         | パッケージ
  | libyui-ncurses-pkg-devel | Libyui-ncurses-pkg header files      | パッケージ
i | libyui-ncurses-pkg-doc   | Libyui-ncurses-pkg documentation     | パッケージ
i | libyui-ncurses-pkg7      | Libyui - yast2 package selector wi-> | パッケージ
i | libyui-ncurses7          | Libyui - Character Based User Inte-> | パッケージ
  | libyui-qt-devel          | Libyui-qt header files               | パッケージ
i | libyui-qt-doc            | Libyui-qt documentation              | パッケージ
  | libyui-qt-graph-devel    | Libyui-qt-graph header files         | パッケージ
i | libyui-qt-graph-doc      | Libyui-qt-graph documentation        | パッケージ
  | libyui-qt-graph7         | Libyui - Qt Graph Widget             | パッケージ
  | libyui-qt-pkg-devel      | Libyui-qt-pkg header files           | パッケージ
i | libyui-qt-pkg-doc        | Libyui-qt-pkg documentation          | パッケージ
i | libyui-qt-pkg7           | Libyui - Qt Package Selector         | パッケージ
i | libyui-qt7               | Libyui - Qt User Interface           | パッケージ
i | libyui7                  | Libyui - GUI-abstraction library     | パッケージ

Update, it seems to be related to a specific package/ パッケージ as cited here
but making the process listed I still dont get the UI up.
Despite the page speaks about novell linux, and Im open Suse, there is no
xorg-x11-libXrender-7.4-1.23.1
but instead is
libXrender1-0.9.10-1.1.x86_64

So what would be needed?
Thanks in advance

A: I had a similar problem
 Run command: /sbin/yast2 sw_single &
 terminate called after throwing an instance of 'YUIPluginException'
  what():  Couldn't load plug-in qt
 /sbin/yast2: line 448:  4353 Aborted                 (core dumped) $ybindir/y2start $module "$@" "$SELECTED_GUI" $Y2_GEOMETRY $Y2UI_ARGS

 zypper se libyui

was
 S  | Name                            | Summary                                                     | Type
 ---+---------------------------------+-------------------------------------------------------------+--------
    | libyui-devel                    | Libyui header files                                         | package
    | libyui-doc                      | Libyui documentation                                        | package
    | libyui-ncurses-devel            | Libyui-ncurses header files                                 | package
    | libyui-ncurses-doc              | Libyui-ncurses documentation                                | package
    | libyui-ncurses-pkg-devel        | Libyui-ncurses-pkg header files                             | package
    | libyui-ncurses-pkg-doc          | Libyui-ncurses-pkg documentation                            | package
 i+ | libyui-ncurses-pkg7             | Libyui - yast2 package selector widget for the ncurses UI   | package
 i  | libyui-ncurses-pkg8             | Libyui - yast2 package selector widget for the ncurses UI   | package
 i+ | libyui-ncurses7                 | Libyui - Character Based User Interface                     | package
 i  | libyui-ncurses8                 | Libyui - Character Based User Interface                     | package
    | libyui-qt-devel                 | Libyui-qt header files                                      | package
    | libyui-qt-doc                   | Libyui-qt documentation                                     | package
    | libyui-qt-graph-devel           | Libyui-qt-graph header files                                | package
    | libyui-qt-graph-doc             | Libyui-qt-graph documentation                               | package
 i+ | libyui-qt-graph7                | Libyui - Qt Graph Widget                                    | package
    | libyui-qt-graph8                | Libyui - Qt Graph Widget                                    | package
    | libyui-qt-pkg-devel             | Libyui-qt-pkg header files                                  | package
    | libyui-qt-pkg-doc               | Libyui-qt-pkg documentation                                 | package
 i+ | libyui-qt-pkg7                  | Libyui - Qt Package Selector                                | package
    | libyui-qt-pkg8                  | Libyui - Qt Package Selector                                | package
 i+ | libyui-qt7                      | Libyui - Qt User Interface                                  | package
    | libyui-qt8                      | Libyui - Qt User Interface                                  | package
 i+ | libyui7                         | Libyui - GUI-abstraction library                            | package
 i  | libyui8                         | Libyui - GUI-abstraction library                            | package
    | ruby2.4-rubygem-libyui-rake     | Rake tasks providing basic work-flow for libyui development | package
    | ruby2.4-rubygem-libyui-rake-doc | RDoc documentation for libyui-rake                          | package

Fixed by
 zypper in libyui-qt8 libyui-qt-graph8 libyui-qt-pkg8

A: I used an explicit command line option:
yast2 -gtk

to avoid the line 440 core dump. This is under openSUSE 42.2 for the yast2 binary of 2017-03-28.

A: I had faced with the same problem and paid attention that my system only have  libyui-qt7 but not libyui-qt8.
zypper se libyui-qt
Loading repository data...
Reading installed packages...

S  | Name              | Summary                       | Type
---+-------------------+-------------------------------+--------
i+ | libyui-qt-graph7  | Libyui - Qt Graph Widget      | package
   | libyui-qt-graph8  | Libyui - Qt Graph Widget      | package
i+ | libyui-qt-pkg7    | Libyui - Qt Package Selector  | package
   | libyui-qt-pkg8    | Libyui - Qt Package Selector  | package
i+ | libyui-qt7        | Libyui - Qt User Interface    | package
   | libyui-qt8        | Libyui - Qt User Interface    | package

I have resolved it by installing x86-64 version of the library libyui-qt8 and now any module of the Yast starts successfully.
zypper in libyui-qt8


text:
Q: Covering finite groups by unions of proper subgroups A noncyclic finite group $G$ may be expressed as a union of some of its proper subgroups. (Say the subgroups "cover" $G$ in this case.) A relatively simple exercise in some introductory algebra texts, e.g. Jacobson [Basic Algebra I, 2ed p 36 ex 14 ], is to show that no group is the union of two proper subgroups. So I thought what if one is allowed more proper subgroups? One cannot express a cyclic group as a union of proper subgroups, since one of the subgroups would containing the generator and hence fail to be proper. On the other hand, if $G$ is noncyclic it has such an expression, since one can form all the cyclic groups generated by the elements of $G$, and then their union is $G$ and each is proper since $G$ is not cyclic.
My question is about the minimal number of proper subgroups needed to cover a given noncyclic group $G.$ If this minimal number is denoted $m(G)$ then I found e.g. $m(S_3)=4$ and also $m(K)=3$ for the symmetric group $S_3$ and the Klein four-group $K.$
I would be interested if anything is known about $m(S_n)$ generally, or in what $m(G)$ turns out to be for other families of groups. (Even some more examples of $m(S_n)$ for small $n$ would be nice.) Another interesting case might be for the multiplicative groups of invertible elements mod $n$ (in cases where no primitive root exists.)

A: This is a well-studied invariant, going back to G. Scorza who, in 1926, showed that the groups $G$ with $m(G) = 3$ are those with $C_2^2$ as a homomorphic image.  But much has been done since then.  Here are some nice slides from a talk by Martino Garonzi.  It, and the references at the end, should get you started.

A: As you noted, a group cannot be the union of two of its proper subgroups. It might be interesting to know, that research has been done on how this might generalize.
Theorem (Bruckheimer, Bryan and Muir) A group is the union of three proper subgroups if and only if it has a quotient isomorphic to $C_2 \times C_2$.
The proof appeared in the American Math. Monthly $77$, no. $1 (1970)$. The theorem seems to be proved earlier by the Italian mathematician Gaetano Scorza, I gruppi che possono pensarsi come somma di tre loro sottogruppi, Boll. Un. Mat. Ital. $5 (1926), 216-218$.
 For 4, 5 or 6 subgroups a similar theorem is true and the Klein 4-group is for each of the cases replaced by some finite set of groups. For 7 subgroups however, it is not true: no group can be written as a union of 7 of its proper subgroups. This was proved by Tomkinson in 1997.
There is a nice overview paper by Mira Bhargava, Groups as unions of subgroups, The American Mathematical Monthly, $116$, no. $5, (2009)$.


text:
Q: Update rows in table A with all different data from table B I'm trying update rows in a table A, based on rows from table B. Table A looks like this:
a_id |   NAME    | VALUE |
--------------------------
1   |   n1      |  NULL  |
2   |   n2      |  NULL  |

and table B looks like this:
b_id   |   VALUE     |
----------------------
1     |   var1       |
2     |   var2       |
3     |   var3       |

How can I get the table A updated to this:
a_id |   NAME    | VALUE |
--------------------------
1   |   n1      |  var1  |
2   |   n2      |  var1  |
3   |   n1      |  var2  |
4   |   n1      |  var3  |
5   |   n2      |  var2  |
6   |   n2      |  var3  |

A: The easy way is to create a new table AA with the same structure as A
and do
Insert into AA Select A._id,a.NAME,b.Value From A, B

then drop A and rename AA to A or empty A and select into it from AA
Can't just be an update statement as records require inserting as well.
This is called a cartesian product and is usually an error. Please understand you end up with number of rows in A * number of rows in B. 2 * 3 isn't a problem, 2,000,000 * 3,000,000...