问:
new QFile("some.txt") fails with "device not open" when windows screen locked
Consider this very simple example:

```<code>for(;;){
   QFile *file = new QFile("some.txt");//this is where it fails with "device not open" when windows screen is locked
   if(file->exists()){
      file->open(QFile::ReadOnly);
      QString contents = file->readAll();
      file->close();
   }
   file->deleteLater();
   QThread::sleep(2);
}
</code>```

It was continuing to work as normal when windows screen is locked up until recently but I'm not sure if it started to act like this because I started to use Qt 5.9 or if it was a windows update that prevent file accesses while windows screen is locked.

So please advise a workaround or a solution.
Thank you.

Edit:
It turns out that QFile or file access was not the issue and the problem was where and by whom it was called. So I'm accepting @Kuba 's answer since it was informative and in the right direction.

答:
Your code leaks memory and resources: the QFile instances will never be destroyed, since you never let the event loop run in the current thread, and it's the event loop that would destroy them.

There's no reason to create the file object on the heap, and neither is there any reason to explicitly close the file: QFile is a proper C++ class that implements RAII. Destroying it is safe in any state, without resource leaks. Just destroy the file to close its underlying handle.

Incorporating the above suggestions, the code should be:

```<code>for (;;){
   QFile file("some.txt");
   if (file.exists()){
      file.open(QFile::ReadOnly);
      auto contents = file->readAll();
      qDebug() << "read, n=" << contents.size();
   }
   QThread::sleep(2);
}
</code>```

Ideally, though, you should run your code from the event loop and not block the thread. Threads are expensive resources and having a thread that does nothing most of the time is rather wasteful.

```<code>auto timer = new QTimer;
timer->start(2000);
auto reader = []{
  QFile file("some.txt");
  if (file.exists()){
    file.open(QFile::ReadOnly);
    auto contents = file->readAll();
    qDebug() << "read, n=" << contents.size();
  }
});
connect(timer, &QTimer::timeout, reader);
</code>```

To end the reading, stop or destroy the timer.

The thread should be spinning an event loop - and the default implementation of QThread::run will do that for you. Thus the code above can be wrapped in a QObject and moved to a dedicated thread, that should also be used for other things.

Alternatively, you could use the thread pool and do the reading in a worker thread, but run the timer in the GUI thread. Only the connect statement above would need to be changed to:

```<code>connect(timer, &QTimer::timeout, [reader]{ QtConcurrent::run(reader); });
</code>```

Body:
Consider this very simple example:

for(;;){
   QFile *file = new QFile("some.txt");//this is where it fails with "device not open" when windows screen is locked
   if(file->exists()){
      file->open(QFile::ReadOnly);
      QString contents = file->readAll();
      file->close();
   }
   file->deleteLater();
   QThread::sleep(2);
}

It was continuing to work as normal when windows screen is locked up until recently but I'm not sure if it started to act like this because I started to use Qt 5.9 or if it was a windows update that prevent file accesses while windows screen is locked.

So please advise a workaround or a solution.
Thank you.

Edit:
It turns out that QFile or file access was not the issue and the problem was where and by whom it was called. So I'm accepting @Kuba 's answer since it was informative and in the right direction.

Body:
Your code leaks memory and resources: the QFile instances will never be destroyed, since you never let the event loop run in the current thread, and it's the event loop that would destroy them.

There's no reason to create the file object on the heap, and neither is there any reason to explicitly close the file: QFile is a proper C++ class that implements RAII. Destroying it is safe in any state, without resource leaks. Just destroy the file to close its underlying handle.

Incorporating the above suggestions, the code should be:

for (;;){
   QFile file("some.txt");
   if (file.exists()){
      file.open(QFile::ReadOnly);
      auto contents = file->readAll();
      qDebug() << "read, n=" << contents.size();
   }
   QThread::sleep(2);
}

Ideally, though, you should run your code from the event loop and not block the thread. Threads are expensive resources and having a thread that does nothing most of the time is rather wasteful.

auto timer = new QTimer;
timer->start(2000);
auto reader = []{
  QFile file("some.txt");
  if (file.exists()){
    file.open(QFile::ReadOnly);
    auto contents = file->readAll();
    qDebug() << "read, n=" << contents.size();
  }
});
connect(timer, &QTimer::timeout, reader);

To end the reading, stop or destroy the timer.

The thread should be spinning an event loop - and the default implementation of QThread::run will do that for you. Thus the code above can be wrapped in a QObject and moved to a dedicated thread, that should also be used for other things.

Alternatively, you could use the thread pool and do the reading in a worker thread, but run the timer in the GUI thread. Only the connect statement above would need to be changed to:

connect(timer, &QTimer::timeout, [reader]{ QtConcurrent::run(reader); });


来源: stackexchange

问:
Can I optimise this further so that it runs faster?
As you can see in the following pprof output, I have these nested for loops which take most of the time of my program. Source is in golang but code is explained below:

```<code>  8.55mins    1.18hrs     20:   for k := range mapSource {
  4.41mins    1.20hrs     21:           if positions, found := mapTarget[k]; found {
         .          .     22:                   // save all matches
  1.05mins   1.05mins     23:                   for _, targetPos := range positions {
  2.25mins   2.33mins     24:                           for _, sourcePos := range mapSource[k] {
     1.28s     15.78s     25:                                   matches = append(matches, match{int32(targetPos), int32(sourcePos)})
         .          .     26:                           }
         .          .     27:                   }
         .          .     28:           }
         .          .     29:   }
</code>```

At the moment the structures I'm using are 2 map[int32][]int32, targetMap and sourceMap.

These maps contain, for a given key, an array of ints. Now I want to find the keys that match in both maps, and save the combinations of the elements in the arrays.

So for example:

```<code>sourceMap[1] = [3,4]
sourceMap[5] = [9,10]

targetMap[1] = [1,2,3]
targetMap[2] = [2,3]
targetMap[3] = [1,2]
</code>```

The only key in common is 1 and the result will be [(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]

Is there any possible way (a more appropriate data structure or whatever) that could improve the speed of my program?

In my case, maps can contain somewhere between 1000 and 150000 keys, while the arrays inside are usually pretty small.

EDIT: Concurrency is not an option as this is already being run several times in several threads at the same time.

答:
The best optimization probably involves changing the source and target data structures to begin with so you're don't have to iterate as much, but it's hard to be sure without knowing more about what the underlying problem you're solving is, and how the maps are generated.

However, there is an optimization that should get you a roughly 2x boost (just an educated guess), depending on the exact numbers.

```<code>var sources, targets []int32

for k, srcPositions := range mapSource {
    if tgtPositions, found := mapTarget[k]; found {
        sources = append(sources, srcPositions...)
        targets = append(targets, tgtPositions...)
    }
}

matches = make([]match, len(sources) * len(targets))
i := 0
for _, s := range(sources) {
    for _, t := range(targets) {
        matches[i] = match{s, t}
        i++
    }
}
</code>```

The general idea is to minimize the amount of copying that has to be done, and improve the locality of memory references. I think this is about the best you can do with this data structure. My hunch is this isn't the best datastructure to begin with for the underlying problem, and there are much bigger gains to be had.

ContentLicense: CC BY-SA 3.0

Body:
As you can see in the following pprof output, I have these nested for loops which take most of the time of my program. Source is in golang but code is explained below:

  8.55mins    1.18hrs     20:   for k := range mapSource {
  4.41mins    1.20hrs     21:           if positions, found := mapTarget[k]; found {
         .          .     22:                   // save all matches
  1.05mins   1.05mins     23:                   for _, targetPos := range positions {
  2.25mins   2.33mins     24:                           for _, sourcePos := range mapSource[k] {
     1.28s     15.78s     25:                                   matches = append(matches, match{int32(targetPos), int32(sourcePos)})
         .          .     26:                           }
         .          .     27:                   }
         .          .     28:           }
         .          .     29:   }

At the moment the structures I'm using are 2 map[int32][]int32, targetMap and sourceMap.

These maps contain, for a given key, an array of ints. Now I want to find the keys that match in both maps, and save the combinations of the elements in the arrays.

So for example:

sourceMap[1] = [3,4]
sourceMap[5] = [9,10]

targetMap[1] = [1,2,3]
targetMap[2] = [2,3]
targetMap[3] = [1,2]

The only key in common is 1 and the result will be [(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]

Is there any possible way (a more appropriate data structure or whatever) that could improve the speed of my program?

In my case, maps can contain somewhere between 1000 and 150000 keys, while the arrays inside are usually pretty small.

EDIT: Concurrency is not an option as this is already being run several times in several threads at the same time.

Body:
The best optimization probably involves changing the source and target data structures to begin with so you're don't have to iterate as much, but it's hard to be sure without knowing more about what the underlying problem you're solving is, and how the maps are generated.

However, there is an optimization that should get you a roughly 2x boost (just an educated guess), depending on the exact numbers.

var sources, targets []int32

for k, srcPositions := range mapSource {
    if tgtPositions, found := mapTarget[k]; found {
        sources = append(sources, srcPositions...)
        targets = append(targets, tgtPositions...)
    }
}

matches = make([]match, len(sources) * len(targets))
i := 0
for _, s := range(sources) {
    for _, t := range(targets) {
        matches[i] = match{s, t}
        i++
    }
}

The general idea is to minimize the amount of copying that has to be done, and improve the locality of memory references. I think this is about the best you can do with this data structure. My hunch is this isn't the best datastructure to begin with for the underlying problem, and there are much bigger gains to be had.


问:
Fatal error php
Is there a way to make the code continue (not exit) when you get a fatal error in PHP?
For example I get a timeout fatal error and I want whenever it happens to skip this task and the continue with others.
In this case the script exits.</p>

答:
If you have a suitable PHP version (PHP>=5.2 for error_get_last) you can try the technique described here which uses register_shutdown_function and error_get_last.

This won't allow you to "continue" when you get a fatal error, but it at least allows you to log the error (and perhaps send a warning email) before displaying a custom error page to the user.

It works something like this:

```<code>function fatalErrorHandler()
{
    $lastError = error_get_last();
    if (isset($lastError["type"]) && $lastError["type"]==E_ERROR) {
      // do something with the fatal error
    }
}
...
register_shutdown_function('fatalErrorHandler');
</code>```

A few points:

you can use ob_clean() to remove any content that was generated prior to the fatal error.

it's a really bad idea to do anything to intensive in the shutdown handler, this technique is about graceful failure rather than recovery.

whatever you do, don't try to log the error to a database ... what if it was a database timeout that caused the fatal error?

for some reason I've had problems getting this technique to work 100% of the time when developing in Windows using WAMP.

ContentLicense: CC BY-SA 2.5

Title: Fatal error php

Body:
If you have a suitable PHP version (PHP>=5.2 for error_get_last) you can try the technique described here which uses register_shutdown_function and error_get_last.

This won't allow you to "continue" when you get a fatal error, but it at least allows you to log the error (and perhaps send a warning email) before displaying a custom error page to the user.

It works something like this:

function fatalErrorHandler()
{
    $lastError = error_get_last();
    if (isset($lastError["type"]) && $lastError["type"]==E_ERROR) {
      // do something with the fatal error
    }
}
...
register_shutdown_function('fatalErrorHandler');

A few points:

you can use ob_clean() to remove any content that was generated prior to the fatal error.

it's a really bad idea to do anything to intensive in the shutdown handler, this technique is about graceful failure rather than recovery.

whatever you do, don't try to log the error to a database ... what if it was a database timeout that caused the fatal error?

for some reason I've had problems getting this technique to work 100% of the time when developing in Windows using WAMP.


问:
Drop Pandas DataFrame lines according to a GropuBy property
I have some DataFrames with information about some elements, for instance:

```<code>my_df1=pd.DataFrame([[1,12],[1,15],[1,3],[1,6],[2,8],[2,1],[2,17]],columns=['Group','Value'])
my_df2=pd.DataFrame([[1,5],[1,7],[1,23],[2,6],[2,4]],columns=['Group','Value'])
</code>```

I have used something like dfGroups = df.groupby('group').apply(my_agg).reset_index(), so now I have DataFrmaes with informations on groups of the previous elements, say

```<code>my_df1_Group=pd.DataFrame([[1,57],[2,63]],columns=['Group','Group_Value'])
my_df2_Group=pd.DataFrame([[1,38],[2,49]],columns=['Group','Group_Value'])
</code>```

Now I want to clean my groups according to properties of their elements. Let's say that I want to discard groups containing an element with Value  greater than 16. So in my_df1_Group, there should only be the first group left, while both groups qualify to stay in my_df2_Group.

As I don't know how to get my_df1_Group and my_df2_Group from my_df1 and my_df2 in Python (I know other languages where it would simply be name+"_Group" with name looping in [my_df1,my_df2], but how do you do that in Python?), I build a list of lists:

```<code>SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]]
</code>```

Then, I simply try this:

```<code>my_max=16
Bad=[]
for Sample in SampleList:
    for n in Sample[1]['Group']:
        df=Sample[0].loc[Sample[0]['Group']==n] #This is inelegant, but trying to work
                                                #with Sample[1] in the for doesn't work
        if (df['Value'].max()>my_max):
            Bad.append(1)
        else:
            Bad.append(0)
    Sample[1] = Sample[1].assign(Bad_Row=pd.Series(Bad))
    Sample[1] = Sample[1].query('Bad_Row == 0')
</code>```

Which runs without errors, but doesn't work. In particular, this doesn't add the column Bad_Row to my df, nor modifies my DataFrame (but the query runs smoothly even if Bad_Rowcolumn doesn't seem to exist...). On the other hand, if I run this technique manually on a df (i.e. not in a loop), it works.

How should I do?

答:
Based on your comment below, I think you are wanting to check if a Group in your aggregated data frame has a Value in the input data greater than 16.  One solution is to perform a row-wise calculation using a criterion of the input data.  To accomplish this, my_func accepts a row from the aggregated data frame and the input data as a pandas groupby object. For each group in your grouped data frame, it will subset you initial data and use boolean logic to see if any of the 'Values' in your input data meet your specified criterion.

```<code>def my_func(row,grouped_df1):
    if (grouped_df1.get_group(row['Group'])['Value']>16).any():
        return 'Bad Row'
    else:
        return 'Good Row'

my_df1=pd.DataFrame([[1,12],[1,15],[1,3],[1,6],[2,8],[2,1],[2,17]],columns=['Group','Value'])

my_df1_Group=pd.DataFrame([[1,57],[2,63]],columns=['Group','Group_Value'])

grouped_df1 = my_df1.groupby('Group')

my_df1_Group['Bad_Row'] = my_df1_Group.apply(lambda x: my_func(x,grouped_df1), axis=1)
</code>```

Returns:

```<code>   Group  Group_Value   Bad_Row
0      1           57  Good Row
1      2           63   Bad Row
</code>```

Body:
I have some DataFrames with information about some elements, for instance:

my_df1=pd.DataFrame([[1,12],[1,15],[1,3],[1,6],[2,8],[2,1],[2,17]],columns=['Group','Value'])
my_df2=pd.DataFrame([[1,5],[1,7],[1,23],[2,6],[2,4]],columns=['Group','Value'])

I have used something like dfGroups = df.groupby('group').apply(my_agg).reset_index(), so now I have DataFrmaes with informations on groups of the previous elements, say

my_df1_Group=pd.DataFrame([[1,57],[2,63]],columns=['Group','Group_Value'])
my_df2_Group=pd.DataFrame([[1,38],[2,49]],columns=['Group','Group_Value'])

Now I want to clean my groups according to properties of their elements. Let's say that I want to discard groups containing an element with Value  greater than 16. So in my_df1_Group, there should only be the first group left, while both groups qualify to stay in my_df2_Group.

As I don't know how to get my_df1_Group and my_df2_Group from my_df1 and my_df2 in Python (I know other languages where it would simply be name+"_Group" with name looping in [my_df1,my_df2], but how do you do that in Python?), I build a list of lists:

SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]]

Then, I simply try this:

my_max=16
Bad=[]
for Sample in SampleList:
    for n in Sample[1]['Group']:
        df=Sample[0].loc[Sample[0]['Group']==n] #This is inelegant, but trying to work
                                                #with Sample[1] in the for doesn't work
        if (df['Value'].max()>my_max):
            Bad.append(1)
        else:
            Bad.append(0)
    Sample[1] = Sample[1].assign(Bad_Row=pd.Series(Bad))
    Sample[1] = Sample[1].query('Bad_Row == 0')

Which runs without errors, but doesn't work. In particular, this doesn't add the column Bad_Row to my df, nor modifies my DataFrame (but the query runs smoothly even if Bad_Rowcolumn doesn't seem to exist...). On the other hand, if I run this technique manually on a df (i.e. not in a loop), it works.

How should I do?

Body:
Based on your comment below, I think you are wanting to check if a Group in your aggregated data frame has a Value in the input data greater than 16.  One solution is to perform a row-wise calculation using a criterion of the input data.  To accomplish this, my_func accepts a row from the aggregated data frame and the input data as a pandas groupby object. For each group in your grouped data frame, it will subset you initial data and use boolean logic to see if any of the 'Values' in your input data meet your specified criterion.

def my_func(row,grouped_df1):
    if (grouped_df1.get_group(row['Group'])['Value']>16).any():
        return 'Bad Row'
    else:
        return 'Good Row'

my_df1=pd.DataFrame([[1,12],[1,15],[1,3],[1,6],[2,8],[2,1],[2,17]],columns=['Group','Value'])

my_df1_Group=pd.DataFrame([[1,57],[2,63]],columns=['Group','Group_Value'])

grouped_df1 = my_df1.groupby('Group')

my_df1_Group['Bad_Row'] = my_df1_Group.apply(lambda x: my_func(x,grouped_df1), axis=1)

Returns:

   Group  Group_Value   Bad_Row
0      1           57  Good Row
1      2           63   Bad Row


问:
Angular Hero Tutorial - Routing - Dec 2017 - Compile Error
I can't compile my code, which I've compared several times with the final code review, copy & paste...

https://angular.io/tutorial/toh-pt5

But I still get the Error

$ ERROR in C:/Users/pablues/Documents/angular-tutorial/a-t-h/src/app/heroes/heroes.component.ts (21,22): Property 'getHeroes' does not exist on type 'HeroService'.
ERROR in C:/Users/pablues/Documents/angular-tutorial/a-t-h/src/app/dashboard/dashboard.component.ts (20,22): Property 'getHeroes' does not exist on type 'HeroService'.

https://github.com/pablues/tour-of-heroes/blob/master/src/app/heroes/heroes.component.ts

https://github.com/pablues/tour-of-heroes/blob/master/src/app/dashboard/dashboard.component.ts

https://github.com/pablues/tour-of-heroes/blob/master/src/app/hero.service.ts

I can't figure it out, where the problem is right now.

Thx in advance

答:
I can not see an error in HeroComponent or DashboardComponent, but there is one issue in HeroDetailComponent.

Below is your HeroService

```<code>@Injectable()
export class HeroService {

  constructor(private messageService: MessageService) { }

  getHeroes(): Observable<Hero[]> {
    // Todo: send the message _after_ fetching the heroes
    this.messageService.add('HeroService: fetched heroes');
    return of(HEROES);
  }
}
</code>```

And below is your HeroDetailComponent

```<code>@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
  @Input() hero: Hero;

  constructor(
    private route: ActivatedRoute,
    private heroService: HeroService,
    private location: Location
  ) {}

  ngOnInit(): void {
    this.getHero();
  }

  getHero(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.heroService.getHero(id)
      .subscribe(hero => this.hero = hero);
  }

  goBack(): void {
    this.location.back();
  }
}
</code>```

Above, getHero(id) is missing in your HeroService.

```<code>this.heroService.getHero(id).subscribe(hero => this.hero = hero);
</code>```

Body:
I can not see an error in HeroComponent or DashboardComponent, but there is one issue in HeroDetailComponent.

Below is your HeroService

@Injectable()
export class HeroService {

  constructor(private messageService: MessageService) { }

  getHeroes(): Observable<Hero[]> {
    // Todo: send the message _after_ fetching the heroes
    this.messageService.add('HeroService: fetched heroes');
    return of(HEROES);
  }
}

And below is your HeroDetailComponent

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
  @Input() hero: Hero;

  constructor(
    private route: ActivatedRoute,
    private heroService: HeroService,
    private location: Location
  ) {}

  ngOnInit(): void {
    this.getHero();
  }

  getHero(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.heroService.getHero(id)
      .subscribe(hero => this.hero = hero);
  }

  goBack(): void {
    this.location.back();
  }
}

Above, getHero(id) is missing in your HeroService.

this.heroService.getHero(id).subscribe(hero => this.hero = hero);


问:
Get Child Attribute using JQUERY
I am creating a link gallery.

HTML:

```<code><div class="link">
    <header>Test Header</header>
    <a href="http://www.google.com/">Click Here</a>
</div>
</code>```

I want to go to the A element's URL when clicking anywhere in the div.

Javascript with JQUERY 3.2.1:

```<code>$(function() {
    $("div.link").click(function() {
        $url = $this.children("a").attr("href");
        alert($url);
    });
});
</code>```

It doesn't alert the URL

I have also tried:

```<code>$(function() {
    $("div.link").click(function() {
        $url = $this.find("a:first-child").attr("href");
        alert($url);
    });
});
</code>```

It returns a collection instead of a single element so I tried the following:

```<code>$function() {
    $("div.link").click(function() {
        $url = $this.find("a");
        alert($url[0].attr("href"));
    });
});
</code>```

Neither approach is working.  I have confirmed the click selector is functioning by testing it with a simple alert("hello");

EDIT: I was using $this instead of $(this).

答:
I want to goto the A element's URL when clicking anywhere in the div.

Based on the code you have shared, $this seems to be undefined

If you just want to fetch the href property of the child anchor tag, then simply

```<code>$("div.link").click(function() {
    var href = $(this).find("a").attr( "href" ); //attr will fetch the attribute of first element in the result of find
});
</code>```

If you want to click on the child anchor tag, then try using one of the following ways

```<code>$("div.link").click(function() {
    $(this).find("a").first().click();
});
</code>```

or

```<code>$("div.link").click(function() {
    $(this).find("a").click();
});
</code>```

or

```<code>$("div.link").click(function() {
    $(this).find("a").trigger( "click" );
});
</code>```

or if you just want to go the URL

```<code>$("div.link").click(function() {
    window.location.href = $(this).find("a").attr( "href" );
});
</code>```

Title: Get Child Attribute using JQUERY

Body:
I am creating a link gallery.

HTML:

    Test Header
    Click Here

I want to go to the A element's URL when clicking anywhere in the div.

Javascript with JQUERY 3.2.1:

$(function() {
    $("div.link").click(function() {
        $url = $this.children("a").attr("href");
        alert($url);
    });
});

It doesn't alert the URL

I have also tried:

$(function() {
    $("div.link").click(function() {
        $url = $this.find("a:first-child").attr("href");
        alert($url);
    });
});

It returns a collection instead of a single element so I tried the following:

$function() {
    $("div.link").click(function() {
        $url = $this.find("a");
        alert($url[0].attr("href"));
    });
});

Neither approach is working.  I have confirmed the click selector is functioning by testing it with a simple alert("hello");

EDIT: I was using $this instead of $(this).

Body:
I want to goto the A element's URL when clicking anywhere in the div.

Based on the code you have shared, $this seems to be undefined

If you just want to fetch the href property of the child anchor tag, then simply

$("div.link").click(function() {
    var href = $(this).find("a").attr( "href" ); //attr will fetch the attribute of first element in the result of find
});

If you want to click on the child anchor tag, then try using one of the following ways

$("div.link").click(function() {
    $(this).find("a").first().click();
});

or

$("div.link").click(function() {
    $(this).find("a").click();
});

or

$("div.link").click(function() {
    $(this).find("a").trigger( "click" );
});

or if you just want to go the URL

$("div.link").click(function() {
    window.location.href = $(this).find("a").attr( "href" );
});


问:
Copy first character from WCHAR* into LPWCSTR
I am trying to point an LPWCSTR to just the first letter of a WCHAR* in, but instead it's pointing to the entire string.

```<code>//my_string points to a string "test"
void GetFirstChar(const WCHAR* my_string)
{
    LPWCSTR str = my_string; // str returns "test", but I want just "t"
}
</code>```

How do I get str to equal just the first character of my_string?

Update:

I also tried this and str still shows the entire string.

```<code>//my_string points to a string "test"
void GetFirstChar(const WCHAR* my_string)
{
    LPWCSTR str = &my_string[0]; // str returns "test", but I want just "t"
}
</code>```

答:
```<code>void GetFirstChar(const WCHAR* my_string)
{
    wchar_t newstr[2];
    newstr[0] = *my_string;
    newstr[1] = 0;
}
</code>```

Body:
I am trying to point an LPWCSTR to just the first letter of a WCHAR* in, but instead it's pointing to the entire string.

//my_string points to a string "test"
void GetFirstChar(const WCHAR* my_string)
{
    LPWCSTR str = my_string; // str returns "test", but I want just "t"
}

How do I get str to equal just the first character of my_string?

Update:

I also tried this and str still shows the entire string.

//my_string points to a string "test"
void GetFirstChar(const WCHAR* my_string)
{
    LPWCSTR str = &my_string[0]; // str returns "test", but I want just "t"
}


问:
Perl DBI (MySQL) puts single quote instead of actual parameter in prepared statement
I'm trying to do a simple query as prepared statement but have no success. Here is the code:

```<code>package sqltest;
use DBI;

DBI->trace(2);

my $dbh = DBI->connect('dbi:mysql:database=test;host=***;port=3306','the_username', '****');
my $prep = 'SELECT me.id, me.session_data, me.expires FROM sys_session me WHERE me.id = ?';
$dbh->{RaiseError} = 1;
my $sth = $dbh->prepare($prep);
$sth->bind_param(1, 'session:06b6d2138df949524092eefc066ee5ab3598bf96');
$sth->execute;
DBI::dump_results($sth);
</code>```

The MySQL server responds with a syntax error near '''.

The output of the DBI-trace shows

```<code>  -> bind_param for DBD::mysql::st (DBI::st=HASH(0x21e35cc)~0x21e34f4 1 'session:06b6d2138df949524092eefc066ee5ab3598bf96') thr#3ccdb4
 Called: dbd_bind_ph
  <- bind_param= ( 1 ) [1 items] at perl_test_dbi_params.pl line 10
[...]
>parse_params statement SELECT me.id, me.session_data, me.expires FROM sys_session me WHERE me.id = ?
Binding parameters: SELECT me.id, me.session_data, me.expires FROM sys_session me WHERE me.id = '
[...]
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1
</code>```

So to me, it looks like the statement does not get prepared as it should.
When I send the query without the parameter it works as expected.

What do I miss here?

DBI version is DBI 1.637-ithread, MySQL version is 5.5.57-0+deb8u1

Tested with Windows perl 5, version 26, subversion 1 (v5.26.1) built for MSWin32-x86-multi-thread-64int

and Ubuntu perl 5, version 22, subversion 1 (v5.22.1) built for x86_64-linux-gnu-thread-multi

Edit1:

for context: I noticed the problem while using Catalyst with Catalyst::Plugin::Session::Store::DBIC. Here, the id-column is a Varchar(72) type, that holds a session-id.

Edit2:

DBD::mysql version is 4.043

Binding via $sth->execute('session:foo'); results in the same problem

Binding via $sth->bind_param('session:foo', SQL_VARCHAR); results in the same problem

Binding a numeric field does work, but only with explicit type definition $sth->bind_param(1, 1512407082, SQL_INTEGER);

Edit3:

I found the time to do some more testing, but not with no satisfying results:

I was able to test with an older server and it worked. The versions of DBI and DBD::mysql are the same, but I found the server using MySQL 5.5 client, reported in the DBI-trace as MYSQL_VERSION_ID 50557, whereas both my original test servers using MySQL 5.7 MYSQL_VERSION_ID 50720 and MYSQL_VERSION_ID 50716

with $dbh->{mysql_server_prepare} = 1;it works! Maybe this helps someone who finds this q., but I would rather now the real cause of the problem

答:
After some testing, I came to the conclusion that this seems to be a compatibility problem between DBD::mysql and MySQL client 5.7 (and/or MySQL server 5.5).

At least, I found a solution for Ubuntu 16 (xenial), so for others, that may run into the same issue:

downgrade to MySQL 5.6 like described here. For me, installing libmysqlclient-dev without the server/client was sufficient

reinstall DBD::MySQL sudo cpanm --reinstall DBD::mysql, so that it gets build with the now installed MySQL 5.6

I will file an issue at the DBD::mysql GitHub and will update this answer, if there are any news regarding this problem.

An alternative solution, that also worked for me:

let the server prepare your statement $dbh->{mysql_server_prepare} = 1;

Body:
I'm trying to do a simple query as prepared statement but have no success. Here is the code:

package sqltest;
use DBI;

DBI->trace(2);

my $dbh = DBI->connect('dbi:mysql:database=test;host=***;port=3306','the_username', '****');
my $prep = 'SELECT me.id, me.session_data, me.expires FROM sys_session me WHERE me.id = ?';
$dbh->{RaiseError} = 1;
my $sth = $dbh->prepare($prep);
$sth->bind_param(1, 'session:06b6d2138df949524092eefc066ee5ab3598bf96');
$sth->execute;
DBI::dump_results($sth);

The MySQL server responds with a syntax error near '''.

The output of the DBI-trace shows

  -> bind_param for DBD::mysql::st (DBI::st=HASH(0x21e35cc)~0x21e34f4 1 'session:06b6d2138df949524092eefc066ee5ab3598bf96') thr#3ccdb4
 Called: dbd_bind_ph
  <- bind_param= ( 1 ) [1 items] at perl_test_dbi_params.pl line 10
[...]
>parse_params statement SELECT me.id, me.session_data, me.expires FROM sys_session me WHERE me.id = ?
Binding parameters: SELECT me.id, me.session_data, me.expires FROM sys_session me WHERE me.id = '
[...]
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1

So to me, it looks like the statement does not get prepared as it should.
When I send the query without the parameter it works as expected.

What do I miss here?

DBI version is DBI 1.637-ithread, MySQL version is 5.5.57-0+deb8u1

Tested with Windows perl 5, version 26, subversion 1 (v5.26.1) built for MSWin32-x86-multi-thread-64int

and Ubuntu perl 5, version 22, subversion 1 (v5.22.1) built for x86_64-linux-gnu-thread-multi

Edit1:

for context: I noticed the problem while using Catalyst with Catalyst::Plugin::Session::Store::DBIC. Here, the id-column is a Varchar(72) type, that holds a session-id.

Edit2:

DBD::mysql version is 4.043

Binding via $sth->execute('session:foo'); results in the same problem

Binding via $sth->bind_param('session:foo', SQL_VARCHAR); results in the same problem

Binding a numeric field does work, but only with explicit type definition $sth->bind_param(1, 1512407082, SQL_INTEGER);

Edit3:

I found the time to do some more testing, but not with no satisfying results:

I was able to test with an older server and it worked. The versions of DBI and DBD::mysql are the same, but I found the server using MySQL 5.5 client, reported in the DBI-trace as MYSQL_VERSION_ID 50557, whereas both my original test servers using MySQL 5.7 MYSQL_VERSION_ID 50720 and MYSQL_VERSION_ID 50716

with $dbh->{mysql_server_prepare} = 1;it works! Maybe this helps someone who finds this q., but I would rather now the real cause of the problem


问:
Rails show posts from only users that the current user is following
I'm new to Rails and having a go at a twitter type web app.

The 'following' and 'followers' part of the app is fine. However I want to filter the Posts index to only show posts that the current user is following.

I need to do something along the lines of:

```<code>@posts = Post.where('user_id LIKE ?', current_user.friendships  )
</code>```

As I expected this throws up an error

```<code>SQLite3::SQLException: near ",": syntax error: SELECT "posts".* FROM "posts" WHERE (user_id LIKE 8,9)
</code>```

It seems close to what I want because 8,9 are the id's of the friends I am following.

Any suggestions as to the best way to get what I'm looking for?

Thanks!

答:
Try IN instead of LIKE:

```<code>@posts = Post.where("user_id IN (?)", current_user.friendships)
</code>```

Or:

```<code>@posts = Post.where(:user_id => current_user.friendships)
</code>```

Body:
I'm new to Rails and having a go at a twitter type web app.

The 'following' and 'followers' part of the app is fine. However I want to filter the Posts index to only show posts that the current user is following.

I need to do something along the lines of:

@posts = Post.where('user_id LIKE ?', current_user.friendships  )

As I expected this throws up an error

SQLite3::SQLException: near ",": syntax error: SELECT "posts".* FROM "posts" WHERE (user_id LIKE 8,9)

It seems close to what I want because 8,9 are the id's of the friends I am following.

Any suggestions as to the best way to get what I'm looking for?

Thanks!

Body:
Try IN instead of LIKE:

@posts = Post.where("user_id IN (?)", current_user.friendships)

Or:

@posts = Post.where(:user_id => current_user.friendships)


问:
Efficient way to copy or merge two ArrayList containing same objects
I have an Object like below

```<code>Product {

String name;

boolean isFiltered;

}
</code>```

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}
</code>```

Approach 2

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}
</code>```

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

答:
you could convert your main product list to a hashset which has constant time access methods.</p>

```<code>Set<Product> masterPLHS = new HashSet<Product>(masterPL); // O(n)

for (Product filterProduct: filteredPL) { //O(n)
        if (masterPLHS.contains(filterProduct)) {  //O(1)
            // do stuff
        }
    }
}
</code>```

Body:
I have an Object like below

Product {

String name;

boolean isFiltered;

}

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}

Approach 2

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

Body:
you could convert your main product list to a hashset which has constant time access methods.

Set<Product> masterPLHS = new HashSet<Product>(masterPL); // O(n)

for (Product filterProduct: filteredPL) { //O(n)
        if (masterPLHS.contains(filterProduct)) {  //O(1)
            // do stuff
        }
    }
}


答:
If you want to get the href attribute when clicking on the div element, you can consider using the selector $(".nameOfDivClass"). On the element selected you will bind a function that will get your href.

$(".link").on("click", function(){
 console.log($(this).children("a").attr("href"))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">
    <header>Test Header</header>
    Click Here
</div></code>```

Title: Get Child Attribute using JQUERY

Body:
If you want to get the href attribute when clicking on the div element, you can consider using the selector $(".nameOfDivClass"). On the element selected you will bind a function that will get your href.

$(".link").on("click", function(){
 console.log($(this).children("a").attr("href"))
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">
    <header>Test Header</header>
    <a href="http://www.google.com/">Click Here</a>
</div>


问:
Message 'src refspec master does not match any' when pushing commits in Git
I clone my repository with:

```<code>git clone ssh://xxxxx/xx.git
</code>```

But after I change some files and add and commit them, I want to push them to the server:

```<code>git add xxx.php
git commit -m "TEST"
git push origin master
</code>```

But the error I get back is:

error: src refspec master does not match any.
error: failed to push some refs to 'ssh://xxxxx.com/project.git'
```

答:
For users of Bash within Cmder on Windows, make sure to create a new .ssh folder in your new home directory.

Go to your home directory cd ~.

Generate ssh keys ssh-keygen.

Leave all inputs blank (keep pressing enter)

Copy the id_rsa.pub file into your Github > Settings > SSH Keys

ContentLicense: CC BY-SA 4.0

Body:
I clone my repository with:

git clone ssh://xxxxx/xx.git

But after I change some files and add and commit them, I want to push them to the server:

git add xxx.php
git commit -m "TEST"
git push origin master

But the error I get back is:

error: src refspec master does not match any.
error: failed to push some refs to 'ssh://xxxxx.com/project.git'


问:
Amazon RDS MySQL replication
I am struggling to setup replica with Amazon RDS. I want to make RDS as my master but for slave I want to setup my server outside of RDS. For now I am setting my slave at EC2. I have checked AWS doc for the information but could not find the exact answer to my question.

However I did found a blog post which have POC for doing it http://www.ruempler.eu/2013/07/07/replicating-aws-rds-mysql-databases-to-external-slaves/

But the problem that I facing is I am getting error

ERROR: Got error reading packet from server: Slave can not handle replication events with the checksum that master is configured to log

I tried to set binlog_checksum = none at RDS but RDS is not letting me change its config file.

Please suggest me folks!!

答:
It does not appear to be possible as of now (December, 2017).

Looking at @walter-heck's second link above, it is actually (another) explanation of "... replication between an external master instance and a DB instance on Amazon RDS".

It does not appear you can setup an external replica which connects to a RDS running as master.

AWS does offer this service, of course, however each replica must be within RDS.

With all the service offerings AWS has, one would think this would be possible. However, it may not work well with the AWS business model, because you don't pay based on external replicas - you pay based on RDS size.

Title: Amazon RDS MySQL replication


问:
Submit an HTML form with empty checkboxes
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.

However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.

How can I get around this? Thanks.

答:
I've used this technique from time to time:

```<code><input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
</code>```

note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.

OwnerDisplayName: Tray

LastEditorDisplayName: fmsf

Body:
I've used this technique from time to time:

<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />

note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.

OwnerDisplayName: ceejayoz


问:
Nullable bool fields in MS Access linked tables
Looks like I'm not the only one out there with this issue, but there doesn't seem to be an anwwer to this problem.

I'm working in Access 2010, using a linked table to an SQL Server 2005 database (through an SQL Server ODBC pipe). In that table, one of the boolean fields is marked as nullable, and several records in this table do in fact have a null in the field. So far so good.

In comes Access, and as soon as you open the linked table, Access shows a 0 (false) instead of a blank cell (problem #1). And if you try to modify anything in the record, you get an error message saying the record was modified by someone else and your changes cannot be saved. This last problem is due to the fact that Access doesn't tolerate nullable bool fields, and goes a bit nuts when trying to save the value.

My research shows that this could have something to do with Access using Jet in the background to connect to the SQL Server database, and Jet apparently does not support nullable bools. There doesn't seem to be a way to configure Jet to support this (although perhaps there is, if you're connecting in code). I also thought MS was replacing Jet with another technology used in Office 2010 (ACE, I think), but cannot tell if this is what's actually being used by Access. In either case, I can find no configurable options regarding nullable bools.

Finally, this issue seems to have been brought up to MS a short while ago, but there's no answer on their end: https://connect.microsoft.com/SQLServer/feedback/details/617339/null-bit-fields-produce-spurious-ms-access-errors-when-using-the-native-odbc-driver?wa=wsignin1.0#tabs

I'm wondering if anyone else out there has run into this and found a solution. And before you suggest it, taking the nullable option off and setting all nulls to 'false' is not really an option in our case. For us, null is actually a valid state and very different from 'false.

Thx!

答:
ACE is an upgrade of Jet (forked from the Jet 4.0 codebase, which is maintained by the Windows team and not seeing any further development, while ACE is under full development by the Access team). It's not significantly different from Jet, except in that it's a new version of the database engine and has features that Jet lacked.

Nullable Booleans are not one of the added features. In any case, if I'm not mistaken there are big theoretical arguments about whether Booleans should be Nullable and Jet/ACE comes down on the side that says they shouldn't be.

Non-nullable Booleans cause problems even within Access/Jet/ACE (Allen Browne has discussed one such, with LEFT JOINs). My suggestion is that you change the field to a Nullable Bit, Byte or Integer field (I'm not sure what exact data types are in SQL Server, nor what is going to be most compatible with Access/Jet/ACE).

Alternatively, you can approach it the way the BIGINT problem is dealt with by using a view to CAST() the server-side Boolean to an INT. That makes it non-editable but (as with BIGINT), you can keep the original field in the VIEW and write to that with appropriate values, while the CAST() version is for display only.

For what it's worth, the SSMA for Access upsizes Jet/ACE Booleans to nullable bit fields (not sure why they are Nullable, though -- I may need to check some of my apps to make sure they are working correctly!).


问:
Sql Server SSIS package Flat File Destination file name pattern (date, time or similar)?
I'm scheduling a SSIS package for exporting data to flat file.

But i want to generate file names with some date information, such as foo_20140606.csv

Is it possible?

Thanks

答:
If you don't have SSDT and thus can't edit this with a GUI here is how you edit the SSIS package directly:

Before:

```<code><DTS:ConnectionManager
      DTS:refId="Package.ConnectionManagers[DestinationConnectionFlatFile]"
      DTS:ObjectName="DestinationConnectionFlatFile"
      DTS:DTSID="{C69365C4-EF12-4606-980B-E8862EE997A4}"
      DTS:CreationName="FLATFILE">
      <DTS:ObjectData>
</code>```

After:

```<code><DTS:ConnectionManager
      DTS:refId="Package.ConnectionManagers[DestinationConnectionFlatFile]"
      DTS:CreationName="FLATFILE"
      DTS:DTSID="{C69365C4-EF12-4606-980B-E8862EE997A4}"
      DTS:ObjectName="DestinationConnectionFlatFile">
      <DTS:PropertyExpression
        DTS:Name="ConnectionString">"C:\\Exportdir\\Filename_"
 + (DT_WSTR,4)DATEPART("yyyy",GetDate()) +
RIGHT("0" + (DT_WSTR,2)DATEPART("mm",GetDate()) ,2) +
RIGHT("0" + (DT_WSTR,2)DATEPART("dd",GetDate()),2) + "_" +
RIGHT("0" + (DT_WSTR,2)DATEPART("hh",GetDate()),2)+
RIGHT("0" + (DT_WSTR,2)DATEPART("mi",GetDate()),2) + ".csv"
      </DTS:PropertyExpression>
        <DTS:ObjectData>
</code>```

Body:
If you don't have SSDT and thus can't edit this with a GUI here is how you edit the SSIS package directly:

Before:

<DTS:ConnectionManager
      DTS:refId="Package.ConnectionManagers[DestinationConnectionFlatFile]"
      DTS:ObjectName="DestinationConnectionFlatFile"
      DTS:DTSID="{C69365C4-EF12-4606-980B-E8862EE997A4}"
      DTS:CreationName="FLATFILE">
      <DTS:ObjectData>

After:

<DTS:ConnectionManager
      DTS:refId="Package.ConnectionManagers[DestinationConnectionFlatFile]"
      DTS:CreationName="FLATFILE"
      DTS:DTSID="{C69365C4-EF12-4606-980B-E8862EE997A4}"
      DTS:ObjectName="DestinationConnectionFlatFile">
      <DTS:PropertyExpression
        DTS:Name="ConnectionString">"C:\\Exportdir\\Filename_"
 + (DT_WSTR,4)DATEPART("yyyy",GetDate()) +
RIGHT("0" + (DT_WSTR,2)DATEPART("mm",GetDate()) ,2) +
RIGHT("0" + (DT_WSTR,2)DATEPART("dd",GetDate()),2) + "_" +
RIGHT("0" + (DT_WSTR,2)DATEPART("hh",GetDate()),2)+
RIGHT("0" + (DT_WSTR,2)DATEPART("mi",GetDate()),2) + ".csv"
      </DTS:PropertyExpression>
        <DTS:ObjectData>


问:
Youtube-DL.exe Closes After Launching Command Line
I've used YouTube-dl successfully on my mac for quite some time.

I downloaded YouTube-dl.exe (after downloading Microsoft Visual C++ I was told a newer version already exists on my computer - it also says Python is not required), but when I launch the executable, it briefly opens a command line window but then closes immediately and nothing else happens. I've tried Googling and even went to the IRC support chat (who turned out to be more rude than helpful) to no avail. Any ideas what to do?

答:
youtube-dl is a command-line application. To use it directly, start a terminal windows by pressing Win+R, and entering cmd. To get to know the command-line interface, you probably want to consult a tutorial.

If you were looking for a graphical application, use one of the graphical frontends instead; for instance, youtube-dlg.

OwnerDisplayName: anon


问:
Does Java have an equivalent to C#'s Environment.GetCommandLineArgs()?
I know that I can get the command-line arguments in the "main" method, but I need to be able to get them indirectly.

Thanks for your help.

答:
You can list the threads, find the main thread, and crawl down the stack trace until you find the call to main, and pull out the args.

update a comment points out that this won't work all by itself, and I think the comment is correct. I misremembered the capabilities of stack introspection or mentally mixed in JVMTI.

So, here's plan B. Connect to yourself with JMX. The VM Summary MBean has the args.

```<code>Connection name:
pid: 77090 com.basistech.jdd.JDDLauncher -config src/main/config/benson-laptop-config.xml
</code>```

All this having been said, what you should do is call System.getProperty and live with the need to use -D to pass parameters from the outside world down into your cave.

Body:
You can list the threads, find the main thread, and crawl down the stack trace until you find the call to main, and pull out the args.

update a comment points out that this won't work all by itself, and I think the comment is correct. I misremembered the capabilities of stack introspection or mentally mixed in JVMTI.

So, here's plan B. Connect to yourself with JMX. The VM Summary MBean has the args.

Connection name:
pid: 77090 com.basistech.jdd.JDDLauncher -config src/main/config/benson-laptop-config.xml

All this having been said, what you should do is call System.getProperty and live with the need to use -D to pass parameters from the outside world down into your cave.


问:
Attaching files stopped working octobercms email ajax form
The below setup has worked until it stopped and right now I'm perplexed why.
I've created a contact form with file attachment in OctoberCMS as below

```<code>{{ form_ajax('ContactForm::onSend', { files: 'true',  flash: 'true', 'data-request-files':true, 'data-request-validate': true }) }}
    <input type="hidden" name="handler" value='onSave'>
    <fieldset class="form">
        <input type="name" name="name" placeholder="Imię i nazwisko" required>
        <input type="email" name="email" placeholder="E-mail" required>
        <input type="phone" name="phone" placeholder="Telefon">
        <input type="text" name="subject" placeholder="Temat" >
        <textarea name="theMessage" placeholder="Zapytanie" required style="width: 100%; height: 140px;"></textarea>
        <input type="file" name="fileAttachment" id="fileAttachment" class="inputfile"  data-multiple-caption="wybrano {count}" /><label for="fileAttachment">wybierz plik </label><span class='attachmentName'></span>

    </fieldset>
        <button type="submit" class="send" data-attach-loading>Wyślij</button>
    </fieldset>

{{ form_close() }}
</code>```

The component for sending email

```<code><?php namespace Depcore\Parts\Components;
use Cms\Classes\ComponentBase;

use Mail;
use Lang;
use Flash;
use Input;
use Validator;
use ValidationException;
use Redirect;
use System\Models\File;

class ContactForm extends ComponentBase
{
    public function componentDetails()
    {
        return [
            'name'        => 'depcore.parts::lang.components.contactFormTitle',
            'description' => 'depcore.parts::lang.components.contactFormDescription'
        ];
    }

    public function defineProperties()
    {
        return [
              'emailTo' => [
                    'title' => 'depcore.parts::components.emailAddress',
                    'description' => 'depcore.parts::components.destinationEmailDescription',
                    'default' => 'zamowienia@kludi.pl',
                    'validationPattern' => "\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z",
                    'ValidationMessage' => ''
            ]
        ];
    }

    public function onSend(){

        $data = post();
        $vars = [
            'name' => Input::get('name'),
            'subject' => Input::get('subject'),
            'phone' => Input::get('phone'),
            'theMessage' => Input::get('theMessage'),
            'fileAttachment' => Input::file('fileAttachment'),
        ];

        $rules = [
                'name' => 'required',
                'email' => 'required|email'
            ];

        $validator = Validator::make($data, $rules);

        if ($validator->fails())
            throw new ValidationException( $validator );
        else {

        Mail::send('depcore.parts::mail.message', $vars, function( $message )  use  ( $vars )  {

            // $message->to($this->property('emailTo'));
            $message->to('adam@depcore.pl');

            if ($vars['fileAttachment']) {
                $file = (new File())->fromPost($vars['fileAttachment']);
                $message->attach($file['path']);
            }

            $message->subject($vars['subject']);
            Flash::success('Wiadomość została wysłana.');
        });

      }
    }

}
</code>```

From what I can tell is that the Input::file('fileAttachemnt') is always returning null so I think It could be a problem with the JavaScript framework (?).

This is a weird thing that got me by surprise when working with the project an now Im stuck.

答:
From your code it looks like by mistake you used wrong method

```<code> $vars = [
        'name' => Input::get('name'),
        'subject' => Input::get('subject'),
        'phone' => Input::get('phone'),
        'theMessage' => Input::get('theMessage'),
        'fileAttachment' => Input::get('fileAttachment'), <-- here
 ];
</code>```

your code is using this

Input::get('fileAttachemnt');

In Reality it should be this

Input::file('fileAttachemnt');

may be you updated your code and didn't notice that ;)

UPDATE

ok I guess there is some issue with File facade code (new File())
let not use that instead we can directly use file as also you are not saving that file so,

can you replace your code and check it once

```<code>$file = (new File())->fromPost($vars['fileAttachment']);
$message->attach($file['path']);
</code>```

TO

```<code>$file = $vars['fileAttachment'];
$pathToFile = $file->getPathname();
$fileName = $file->getClientOriginalName();
$mime = $file->getMimeType()
$message->attach($pathToFile, ['as' => $fileName, 'mime' => $mime]);
</code>```

then check it, it should work.

MORE UPDATE

I added modified version of ajax framework (added js snippet), code is taken from October cms official git repo, and just removed some part of it so it can override existing code without conflicts.

I would suggest, take this code and create ajax-fw-override.js file then include file on your page or just duplicate layout and add it at very bottom, any how it should come after October default ajax {% framework %}, so it can override its Request.

This is not good solution but considering that you can't update your cms version we can use this. (also by making duplicate layout we make sure it won't affect anywhere else).

I tested it on your site using console and it worked. so just check it out and let me know.

+ function($) {
  "use strict";

  var Request = function(element, handler, options) {
    var $el = this.$el = $(element);
    this.options = options || {};

    /*
     * Validate handler name
     */
    if (handler === undefined) {
      throw new Error('The request handler name is not specified.')
    }

    if (!handler.match(/^(?:\w+\:{2})?on*/)) {
      throw new Error('Invalid handler name. The correct handler name format is: "onEvent".')
    }

    /*
     * Prepare the options and execute the request
     */
    var $form = options.form ? $(options.form) : $el.closest('form'),
      $triggerEl = !!$form.length ? $form : $el,
      context = {
        handler: handler,
        options: options
      }

    $el.trigger('ajaxSetup', [context])
    var _event = jQuery.Event('oc.beforeRequest')
    $triggerEl.trigger(_event, context)
    if (_event.isDefaultPrevented()) return

    var loading = options.loading !== undefined ? options.loading : null,
      isRedirect = options.redirect !== undefined && options.redirect.length,
      useFlash = options.flash !== undefined,
      useFiles = options.files !== undefined

    if (useFiles && typeof FormData === 'undefined') {
      console.warn('This browser does not support file uploads via FormData')
      useFiles = false
    }

    if ($.type(loading) == 'string') {
      loading = $(loading)
    }

    /*
     * Request headers
     */
    var requestHeaders = {
      'X-OCTOBER-REQUEST-HANDLER': handler,
      'X-OCTOBER-REQUEST-PARTIALS': this.extractPartials(options.update)
    }

    if (useFlash) {
      requestHeaders['X-OCTOBER-REQUEST-FLASH'] = 1
    }

    /*
     * Request data
     */
    var requestData,
      inputName,
      data = {}

    $.each($el.parents('[data-request-data]').toArray().reverse(), function extendRequest() {
      $.extend(data, paramToObj('data-request-data', $(this).data('request-data')))
    })

    if ($el.is(':input') && !$form.length) {
      inputName = $el.attr('name')
      if (inputName !== undefined && options.data[inputName] === undefined) {
        options.data[inputName] = $el.val()
      }
    }

    if (options.data !== undefined && !$.isEmptyObject(options.data)) {
      $.extend(data, options.data)
    }

    if (useFiles) {
      requestData = new FormData($form.length ? $form.get(0) : null)

      if ($el.is(':file') && inputName) {
        $.each($el.prop('files'), function() {
          requestData.append(inputName, this)
        })

        delete data[inputName]
      }

      $.each(data, function(key) {
        requestData.append(key, this)
      })
    } else {
      requestData = [$form.serialize(), $.param(data)].filter(Boolean).join('&')
    }

    /*
     * Request options
     */
    var requestOptions = {
      url: window.location.href,
      crossDomain: false,
      context: context,
      headers: requestHeaders,
      success: function(data, textStatus, jqXHR) {
        /*
         * Halt here if beforeUpdate() or data-request-before-update returns false
         */
        if (this.options.beforeUpdate.apply(this, [data, textStatus, jqXHR]) === false) return
        if (options.evalBeforeUpdate && eval('(function($el, context, data, textStatus, jqXHR) {' + options.evalBeforeUpdate + '}.call($el.get(0), $el, context, data, textStatus, jqXHR))') === false) return

        /*
         * Trigger 'ajaxBeforeUpdate' on the form, halt if event.preventDefault() is called
         */
        var _event = jQuery.Event('ajaxBeforeUpdate')
        $triggerEl.trigger(_event, [context, data, textStatus, jqXHR])
        if (_event.isDefaultPrevented()) return

        if (useFlash && data['X_OCTOBER_FLASH_MESSAGES']) {
          $.each(data['X_OCTOBER_FLASH_MESSAGES'], function(type, message) {
            requestOptions.handleFlashMessage(message, type)
          })
        }

        /*
         * Proceed with the update process
         */
        var updatePromise = requestOptions.handleUpdateResponse(data, textStatus, jqXHR)

        updatePromise.done(function() {
          $triggerEl.trigger('ajaxSuccess', [context, data, textStatus, jqXHR])
          options.evalSuccess && eval('(function($el, context, data, textStatus, jqXHR) {' + options.evalSuccess + '}.call($el.get(0), $el, context, data, textStatus, jqXHR))')
        })

        return updatePromise
      },
      error: function(jqXHR, textStatus, errorThrown) {
        var errorMsg,
          updatePromise = $.Deferred()

        if ((window.ocUnloading !== undefined && window.ocUnloading) || errorThrown == 'abort')
          return

        /*
         * Disable redirects
         */
        isRedirect = false
        options.redirect = null

        /*
         * Error 406 is a "smart error" that returns response object that is
         * processed in the same fashion as a successful response.
         */
        if (jqXHR.status == 406 && jqXHR.responseJSON) {
          errorMsg = jqXHR.responseJSON['X_OCTOBER_ERROR_MESSAGE']
          updatePromise = requestOptions.handleUpdateResponse(jqXHR.responseJSON, textStatus, jqXHR)
        }
        /*
         * Standard error with standard response text
         */
        else {
          errorMsg = jqXHR.responseText ? jqXHR.responseText : jqXHR.statusText
          updatePromise.resolve()
        }

        updatePromise.done(function() {
          $el.data('error-message', errorMsg)

          /*
           * Trigger 'ajaxError' on the form, halt if event.preventDefault() is called
           */
          var _event = jQuery.Event('ajaxError')
          $triggerEl.trigger(_event, [context, errorMsg, textStatus, jqXHR])
          if (_event.isDefaultPrevented()) return

          /*
           * Halt here if the data-request-error attribute returns false
           */
          if (options.evalError && eval('(function($el, context, errorMsg, textStatus, jqXHR) {' + options.evalError + '}.call($el.get(0), $el, context, errorMsg, textStatus, jqXHR))') === false)
            return

          requestOptions.handleErrorMessage(errorMsg)
        })

        return updatePromise
      },
      complete: function(data, textStatus, jqXHR) {
        $triggerEl.trigger('ajaxComplete', [context, data, textStatus, jqXHR])
        options.evalComplete && eval('(function($el, context, data, textStatus, jqXHR) {' + options.evalComplete + '}.call($el.get(0), $el, context, data, textStatus, jqXHR))')
      },

      /*
       * Custom function, requests confirmation from the user
       */
      handleConfirmMessage: function(message) {
        var _event = jQuery.Event('ajaxConfirmMessage')

        _event.promise = $.Deferred()
        if ($(window).triggerHandler(_event, [message]) !== undefined) {
          _event.promise.done(function() {
            options.confirm = null
            new Request(element, handler, options)
          })
          return false
        }

        if (_event.isDefaultPrevented()) return
        if (message) return confirm(message)
      },

      /*
       * Custom function, display an error message to the user
       */
      handleErrorMessage: function(message) {
        var _event = jQuery.Event('ajaxErrorMessage')
        $(window).trigger(_event, [message])
        if (_event.isDefaultPrevented()) return
        if (message) alert(message)
      },

      /*
       * Custom function, focus fields with errors
       */
      handleValidationMessage: function(message, fields) {
        $triggerEl.trigger('ajaxValidation', [context, message, fields])

        var isFirstInvalidField = true
        $.each(fields, function focusErrorField(fieldName, fieldMessages) {
          fieldName = fieldName.replace(/\.(\w+)/g, '[$1]')

          var fieldElement = $form.find('[name="' + fieldName + '"], [name="' + fieldName + '[]"], [name$="[' + fieldName + ']"], [name$="[' + fieldName + '][]"]').filter(':enabled').first()
          if (fieldElement.length > 0) {

            var _event = jQuery.Event('ajaxInvalidField')
            $(window).trigger(_event, [fieldElement.get(0), fieldName, fieldMessages, isFirstInvalidField])

            if (isFirstInvalidField) {
              if (!_event.isDefaultPrevented()) fieldElement.focus()
              isFirstInvalidField = false
            }
          }
        })
      },

      /*
       * Custom function, display a flash message to the user
       */
      handleFlashMessage: function(message, type) {},

      /*
       * Custom function, redirect the browser to another location
       */
      handleRedirectResponse: function(url) {
        window.location.href = url
      },

      /*
       * Custom function, handle any application specific response values
       * Using a promisary object here in case injected assets need time to load
       */
      handleUpdateResponse: function(data, textStatus, jqXHR) {

        /*
         * Update partials and finish request
         */
        var updatePromise = $.Deferred().done(function() {
          for (var partial in data) {
            /*
             * If a partial has been supplied on the client side that matches the server supplied key, look up
             * it's selector and use that. If not, we assume it is an explicit selector reference.
             */
            var selector = (options.update[partial]) ? options.update[partial] : partial
            if ($.type(selector) == 'string' && selector.charAt(0) == '@') {
              $(selector.substring(1)).append(data[partial]).trigger('ajaxUpdate', [context, data, textStatus, jqXHR])
            } else if ($.type(selector) == 'string' && selector.charAt(0) == '^') {
              $(selector.substring(1)).prepend(data[partial]).trigger('ajaxUpdate', [context, data, textStatus, jqXHR])
            } else {
              $(selector).trigger('ajaxBeforeReplace')
              $(selector).html(data[partial]).trigger('ajaxUpdate', [context, data, textStatus, jqXHR])
            }
          }

          /*
           * Wait for .html() method to finish rendering from partial updates
           */
          setTimeout(function() {
            $(window)
              .trigger('ajaxUpdateComplete', [context, data, textStatus, jqXHR])
              .trigger('resize')
          }, 0)
        })

        /*
         * Handle redirect
         */
        if (data['X_OCTOBER_REDIRECT']) {
          options.redirect = data['X_OCTOBER_REDIRECT']
          isRedirect = true
        }

        if (isRedirect) {
          requestOptions.handleRedirectResponse(options.redirect)
        }

        /*
         * Handle validation
         */
        if (data['X_OCTOBER_ERROR_FIELDS']) {
          requestOptions.handleValidationMessage(data['X_OCTOBER_ERROR_MESSAGE'], data['X_OCTOBER_ERROR_FIELDS'])
        }

        /*
         * Handle asset injection
         */
        if (data['X_OCTOBER_ASSETS']) {
          assetManager.load(data['X_OCTOBER_ASSETS'], $.proxy(updatePromise.resolve, updatePromise))
        } else {
          updatePromise.resolve()
        }

        return updatePromise
      }
    }

    if (useFiles) {
      requestOptions.processData = requestOptions.contentType = false
    }

    /*
     * Allow default business logic to be called from user functions
     */
    context.success = requestOptions.success
    context.error = requestOptions.error
    context.complete = requestOptions.complete
    requestOptions = $.extend(requestOptions, options)
    requestOptions.data = requestData

    /*
     * Initiate request
     */
    if (options.confirm && !requestOptions.handleConfirmMessage(options.confirm)) {
      return
    }

    if (loading) loading.show()
    $(window).trigger('ajaxBeforeSend', [context])
    $el.trigger('ajaxPromise', [context])

    return $.ajax(requestOptions)
      .fail(function(jqXHR, textStatus, errorThrown) {
        if (!isRedirect) {
          $el.trigger('ajaxFail', [context, textStatus, jqXHR])
        }
        if (loading) loading.hide()
      })
      .done(function(data, textStatus, jqXHR) {
        if (!isRedirect) {
          $el.trigger('ajaxDone', [context, data, textStatus, jqXHR])
        }
        if (loading) loading.hide()
      })
      .always(function(dataOrXhr, textStatus, xhrOrError) {
        $el.trigger('ajaxAlways', [context, dataOrXhr, textStatus, xhrOrError])
      })
  }

  Request.DEFAULTS = {
    update: {},
    type: 'POST',
    beforeUpdate: function(data, textStatus, jqXHR) {},
    evalBeforeUpdate: null,
    evalSuccess: null,
    evalError: null,
    evalComplete: null
  }

  /*
   * Internal function, build a string of partials and their update elements.
   */
  Request.prototype.extractPartials = function(update) {
    var result = []

    for (var partial in update)
      result.push(partial)

    return result.join('&')
  }

  // REQUEST PLUGIN DEFINITION
  // ============================

  var old = $.fn.request

  $.fn.request = function(handler, option) {
    var args = arguments

    var $this = $(this).first()
    var data = {
      evalBeforeUpdate: $this.data('request-before-update'),
      evalSuccess: $this.data('request-success'),
      evalError: $this.data('request-error'),
      evalComplete: $this.data('request-complete'),
      confirm: $this.data('request-confirm'),
      redirect: $this.data('request-redirect'),
      loading: $this.data('request-loading'),
      flash: $this.data('request-flash'),
      files: $this.data('request-files'),
      form: $this.data('request-form'),
      update: paramToObj('data-request-update', $this.data('request-update')),
      data: paramToObj('data-request-data', $this.data('request-data'))
    }
    if (!handler) handler = $this.data('request')
    var options = $.extend(true, {}, Request.DEFAULTS, data, typeof option == 'object' && option)
    return new Request($this, handler, options)
  }

  $.fn.request.Constructor = Request

  $.request = function(handler, option) {
    return $(document).request(handler, option)
  }

  // REQUEST NO CONFLICT
  // =================

  $.fn.request.noConflict = function() {
    $.fn.request = old
    return this
  }

  // REQUEST DATA-API
  // ==============

  function paramToObj(name, value) {
    if (value === undefined) value = ''
    if (typeof value == 'object') return value

    try {
      return JSON.parse(JSON.stringify(eval("({" + value + "})")))
    } catch (e) {
      throw new Error('Error parsing the ' + name + ' attribute value. ' + e)
    }
  }

}(window.jQuery);```

Body:
The below setup has worked until it stopped and right now I'm perplexed why.
I've created a contact form with file attachment in OctoberCMS as below

{{ form_ajax('ContactForm::onSend', { files: 'true',  flash: 'true', 'data-request-files':true, 'data-request-validate': true }) }}
    <input type="hidden" name="handler" value='onSave'>
    <fieldset class="form">
        <input type="name" name="name" placeholder="Imię i nazwisko" required>
        <input type="email" name="email" placeholder="E-mail" required>
        <input type="phone" name="phone" placeholder="Telefon">
        <input type="text" name="subject" placeholder="Temat" >
        <textarea name="theMessage" placeholder="Zapytanie" required style="width: 100%; height: 140px;"></textarea>
        <input type="file" name="fileAttachment" id="fileAttachment" class="inputfile"  data-multiple-caption="wybrano {count}" />wybierz plik

    </fieldset>
        <button type="submit" class="send" data-attach-loading>Wyślij</button>
    </fieldset>

{{ form_close() }}

The component for sending email

<?php namespace Depcore\Parts\Components;
use Cms\Classes\ComponentBase;

use Mail;
use Lang;
use Flash;
use Input;
use Validator;
use ValidationException;
use Redirect;
use System\Models\File;

class ContactForm extends ComponentBase
{
    public function componentDetails()
    {
        return [
            'name'        => 'depcore.parts::lang.components.contactFormTitle',
            'description' => 'depcore.parts::lang.components.contactFormDescription'
        ];
    }

    public function defineProperties()
    {
        return [
              'emailTo' => [
                    'title' => 'depcore.parts::components.emailAddress',
                    'description' => 'depcore.parts::components.destinationEmailDescription',
                    'default' => 'zamowienia@kludi.pl',
                    'validationPattern' => "\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z",
                    'ValidationMessage' => ''
            ]
        ];
    }

    public function onSend(){

        $data = post();
        $vars = [
            'name' => Input::get('name'),
            'subject' => Input::get('subject'),
            'phone' => Input::get('phone'),
            'theMessage' => Input::get('theMessage'),
            'fileAttachment' => Input::file('fileAttachment'),
        ];

        $rules = [
                'name' => 'required',
                'email' => 'required|email'
            ];

        $validator = Validator::make($data, $rules);

        if ($validator->fails())
            throw new ValidationException( $validator );
        else {

        Mail::send('depcore.parts::mail.message', $vars, function( $message )  use  ( $vars )  {

            // $message->to($this->property('emailTo'));
            $message->to('adam@depcore.pl');

            if ($vars['fileAttachment']) {
                $file = (new File())->fromPost($vars['fileAttachment']);
                $message->attach($file['path']);
            }

            $message->subject($vars['subject']);
            Flash::success('Wiadomość została wysłana.');
        });

      }
    }

}

From what I can tell is that the Input::file('fileAttachemnt') is always returning null so I think It could be a problem with the JavaScript framework (?).

This is a weird thing that got me by surprise when working with the project an now Im stuck.

Body:
From your code it looks like by mistake you used wrong method

 $vars = [
        'name' => Input::get('name'),
        'subject' => Input::get('subject'),
        'phone' => Input::get('phone'),
        'theMessage' => Input::get('theMessage'),
        'fileAttachment' => Input::get('fileAttachment'), <-- here
 ];

your code is using this

Input::get('fileAttachemnt');

In Reality it should be this

Input::file('fileAttachemnt');

may be you updated your code and didn't notice that ;)

UPDATE

ok I guess there is some issue with File facade code (new File())
let not use that instead we can directly use file as also you are not saving that file so,

can you replace your code and check it once

$file = (new File())->fromPost($vars['fileAttachment']);
$message->attach($file['path']);

TO

$file = $vars['fileAttachment'];
$pathToFile = $file->getPathname();
$fileName = $file->getClientOriginalName();
$mime = $file->getMimeType()
$message->attach($pathToFile, ['as' => $fileName, 'mime' => $mime]);

then check it, it should work.

MORE UPDATE

I added modified version of ajax framework (added js snippet), code is taken from October cms official git repo, and just removed some part of it so it can override existing code without conflicts.

I would suggest, take this code and create ajax-fw-override.js file then include file on your page or just duplicate layout and add it at very bottom, any how it should come after October default ajax {% framework %}, so it can override its Request.

This is not good solution but considering that you can't update your cms version we can use this. (also by making duplicate layout we make sure it won't affect anywhere else).

I tested it on your site using console and it worked. so just check it out and let me know.

+ function($) {
  "use strict";

  var Request = function(element, handler, options) {
    var $el = this.$el = $(element);
    this.options = options || {};

    /*
     * Validate handler name
     */
    if (handler === undefined) {
      throw new Error('The request handler name is not specified.')
    }

    if (!handler.match(/^(?:\w+\:{2})?on*/)) {
      throw new Error('Invalid handler name. The correct handler name format is: "onEvent".')
    }

    /*
     * Prepare the options and execute the request
     */
    var $form = options.form ? $(options.form) : $el.closest('form'),
      $triggerEl = !!$form.length ? $form : $el,
      context = {
        handler: handler,
        options: options
      }

    $el.trigger('ajaxSetup', [context])
    var _event = jQuery.Event('oc.beforeRequest')
    $triggerEl.trigger(_event, context)
    if (_event.isDefaultPrevented()) return

    var loading = options.loading !== undefined ? options.loading : null,
      isRedirect = options.redirect !== undefined && options.redirect.length,
      useFlash = options.flash !== undefined,
      useFiles = options.files !== undefined

    if (useFiles && typeof FormData === 'undefined') {
      console.warn('This browser does not support file uploads via FormData')
      useFiles = false
    }

    if ($.type(loading) == 'string') {
      loading = $(loading)
    }

    /*
     * Request headers
     */
    var requestHeaders = {
      'X-OCTOBER-REQUEST-HANDLER': handler,
      'X-OCTOBER-REQUEST-PARTIALS': this.extractPartials(options.update)
    }

    if (useFlash) {
      requestHeaders['X-OCTOBER-REQUEST-FLASH'] = 1
    }

    /*
     * Request data
     */
    var requestData,
      inputName,
      data = {}

    $.each($el.parents('[data-request-data]').toArray().reverse(), function extendRequest() {
      $.extend(data, paramToObj('data-request-data', $(this).data('request-data')))
    })

    if ($el.is(':input') && !$form.length) {
      inputName = $el.attr('name')
      if (inputName !== undefined && options.data[inputName] === undefined) {
        options.data[inputName] = $el.val()
      }
    }

    if (options.data !== undefined && !$.isEmptyObject(options.data)) {
      $.extend(data, options.data)
    }

    if (useFiles) {
      requestData = new FormData($form.length ? $form.get(0) : null)

      if ($el.is(':file') && inputName) {
        $.each($el.prop('files'), function() {
          requestData.append(inputName, this)
        })

        delete data[inputName]
      }

      $.each(data, function(key) {
        requestData.append(key, this)
      })
    } else {
      requestData = [$form.serialize(), $.param(data)].filter(Boolean).join('&')
    }

    /*
     * Request options
     */
    var requestOptions = {
      url: window.location.href,
      crossDomain: false,
      context: context,
      headers: requestHeaders,
      success: function(data, textStatus, jqXHR) {
        /*
         * Halt here if beforeUpdate() or data-request-before-update returns false
         */
        if (this.options.beforeUpdate.apply(this, [data, textStatus, jqXHR]) === false) return
        if (options.evalBeforeUpdate && eval('(function($el, context, data, textStatus, jqXHR) {' + options.evalBeforeUpdate + '}.call($el.get(0), $el, context, data, textStatus, jqXHR))') === false) return

        /*
         * Trigger 'ajaxBeforeUpdate' on the form, halt if event.preventDefault() is called
         */
        var _event = jQuery.Event('ajaxBeforeUpdate')
        $triggerEl.trigger(_event, [context, data, textStatus, jqXHR])
        if (_event.isDefaultPrevented()) return

        if (useFlash && data['X_OCTOBER_FLASH_MESSAGES']) {
          $.each(data['X_OCTOBER_FLASH_MESSAGES'], function(type, message) {
            requestOptions.handleFlashMessage(message, type)
          })
        }

        /*
         * Proceed with the update process
         */
        var updatePromise = requestOptions.handleUpdateResponse(data, textStatus, jqXHR)

        updatePromise.done(function() {
          $triggerEl.trigger('ajaxSuccess', [context, data, textStatus, jqXHR])
          options.evalSuccess && eval('(function($el, context, data, textStatus, jqXHR) {' + options.evalSuccess + '}.call($el.get(0), $el, context, data, textStatus, jqXHR))')
        })

        return updatePromise
      },
      error: function(jqXHR, textStatus, errorThrown) {
        var errorMsg,
          updatePromise = $.Deferred()

        if ((window.ocUnloading !== undefined && window.ocUnloading) || errorThrown == 'abort')
          return

        /*
         * Disable redirects
         */
        isRedirect = false
        options.redirect = null

        /*
         * Error 406 is a "smart error" that returns response object that is
         * processed in the same fashion as a successful response.
         */
        if (jqXHR.status == 406 && jqXHR.responseJSON) {
          errorMsg = jqXHR.responseJSON['X_OCTOBER_ERROR_MESSAGE']
          updatePromise = requestOptions.handleUpdateResponse(jqXHR.responseJSON, textStatus, jqXHR)
        }
        /*
         * Standard error with standard response text
         */
        else {
          errorMsg = jqXHR.responseText ? jqXHR.responseText : jqXHR.statusText
          updatePromise.resolve()
        }

        updatePromise.done(function() {
          $el.data('error-message', errorMsg)

          /*
           * Trigger 'ajaxError' on the form, halt if event.preventDefault() is called
           */
          var _event = jQuery.Event('ajaxError')
          $triggerEl.trigger(_event, [context, errorMsg, textStatus, jqXHR])
          if (_event.isDefaultPrevented()) return

          /*
           * Halt here if the data-request-error attribute returns false
           */
          if (options.evalError && eval('(function($el, context, errorMsg, textStatus, jqXHR) {' + options.evalError + '}.call($el.get(0), $el, context, errorMsg, textStatus, jqXHR))') === false)
            return

          requestOptions.handleErrorMessage(errorMsg)
        })

        return updatePromise
      },
      complete: function(data, textStatus, jqXHR) {
        $triggerEl.trigger('ajaxComplete', [context, data, textStatus, jqXHR])
        options.evalComplete && eval('(function($el, context, data, textStatus, jqXHR) {' + options.evalComplete + '}.call($el.get(0), $el, context, data, textStatus, jqXHR))')
      },

      /*
       * Custom function, requests confirmation from the user
       */
      handleConfirmMessage: function(message) {
        var _event = jQuery.Event('ajaxConfirmMessage')

        _event.promise = $.Deferred()
        if ($(window).triggerHandler(_event, [message]) !== undefined) {
          _event.promise.done(function() {
            options.confirm = null
            new Request(element, handler, options)
          })
          return false
        }

        if (_event.isDefaultPrevented()) return
        if (message) return confirm(message)
      },

      /*
       * Custom function, display an error message to the user
       */
      handleErrorMessage: function(message) {
        var _event = jQuery.Event('ajaxErrorMessage')
        $(window).trigger(_event, [message])
        if (_event.isDefaultPrevented()) return
        if (message) alert(message)
      },

      /*
       * Custom function, focus fields with errors
       */
      handleValidationMessage: function(message, fields) {
        $triggerEl.trigger('ajaxValidation', [context, message, fields])

        var isFirstInvalidField = true
        $.each(fields, function focusErrorField(fieldName, fieldMessages) {
          fieldName = fieldName.replace(/\.(\w+)/g, '[$1]')

          var fieldElement = $form.find('[name="' + fieldName + '"], [name="' + fieldName + '[]"], [name$="[' + fieldName + ']"], [name$="[' + fieldName + '][]"]').filter(':enabled').first()
          if (fieldElement.length > 0) {

            var _event = jQuery.Event('ajaxInvalidField')
            $(window).trigger(_event, [fieldElement.get(0), fieldName, fieldMessages, isFirstInvalidField])

            if (isFirstInvalidField) {
              if (!_event.isDefaultPrevented()) fieldElement.focus()
              isFirstInvalidField = false
            }
          }
        })
      },

      /*
       * Custom function, display a flash message to the user
       */
      handleFlashMessage: function(message, type) {},

      /*
       * Custom function, redirect the browser to another location
       */
      handleRedirectResponse: function(url) {
        window.location.href = url
      },

      /*
       * Custom function, handle any application specific response values
       * Using a promisary object here in case injected assets need time to load
       */
      handleUpdateResponse: function(data, textStatus, jqXHR) {

        /*
         * Update partials and finish request
         */
        var updatePromise = $.Deferred().done(function() {
          for (var partial in data) {
            /*
             * If a partial has been supplied on the client side that matches the server supplied key, look up
             * it's selector and use that. If not, we assume it is an explicit selector reference.
             */
            var selector = (options.update[partial]) ? options.update[partial] : partial
            if ($.type(selector) == 'string' && selector.charAt(0) == '@') {
              $(selector.substring(1)).append(data[partial]).trigger('ajaxUpdate', [context, data, textStatus, jqXHR])
            } else if ($.type(selector) == 'string' && selector.charAt(0) == '^') {
              $(selector.substring(1)).prepend(data[partial]).trigger('ajaxUpdate', [context, data, textStatus, jqXHR])
            } else {
              $(selector).trigger('ajaxBeforeReplace')
              $(selector).html(data[partial]).trigger('ajaxUpdate', [context, data, textStatus, jqXHR])
            }
          }

          /*
           * Wait for .html() method to finish rendering from partial updates
           */
          setTimeout(function() {
            $(window)
              .trigger('ajaxUpdateComplete', [context, data, textStatus, jqXHR])
              .trigger('resize')
          }, 0)
        })

        /*
         * Handle redirect
         */
        if (data['X_OCTOBER_REDIRECT']) {
          options.redirect = data['X_OCTOBER_REDIRECT']
          isRedirect = true
        }

        if (isRedirect) {
          requestOptions.handleRedirectResponse(options.redirect)
        }

        /*
         * Handle validation
         */
        if (data['X_OCTOBER_ERROR_FIELDS']) {
          requestOptions.handleValidationMessage(data['X_OCTOBER_ERROR_MESSAGE'], data['X_OCTOBER_ERROR_FIELDS'])
        }

        /*
         * Handle asset injection
         */
        if (data['X_OCTOBER_ASSETS']) {
          assetManager.load(data['X_OCTOBER_ASSETS'], $.proxy(updatePromise.resolve, updatePromise))
        } else {
          updatePromise.resolve()
        }

        return updatePromise
      }
    }

    if (useFiles) {
      requestOptions.processData = requestOptions.contentType = false
    }

    /*
     * Allow default business logic to be called from user functions
     */
    context.success = requestOptions.success
    context.error = requestOptions.error
    context.complete = requestOptions.complete
    requestOptions = $.extend(requestOptions, options)
    requestOptions.data = requestData

    /*
     * Initiate request
     */
    if (options.confirm && !requestOptions.handleConfirmMessage(options.confirm)) {
      return
    }

    if (loading) loading.show()
    $(window).trigger('ajaxBeforeSend', [context])
    $el.trigger('ajaxPromise', [context])

    return $.ajax(requestOptions)
      .fail(function(jqXHR, textStatus, errorThrown) {
        if (!isRedirect) {
          $el.trigger('ajaxFail', [context, textStatus, jqXHR])
        }
        if (loading) loading.hide()
      })
      .done(function(data, textStatus, jqXHR) {
        if (!isRedirect) {
          $el.trigger('ajaxDone', [context, data, textStatus, jqXHR])
        }
        if (loading) loading.hide()
      })
      .always(function(dataOrXhr, textStatus, xhrOrError) {
        $el.trigger('ajaxAlways', [context, dataOrXhr, textStatus, xhrOrError])
      })
  }

  Request.DEFAULTS = {
    update: {},
    type: 'POST',
    beforeUpdate: function(data, textStatus, jqXHR) {},
    evalBeforeUpdate: null,
    evalSuccess: null,
    evalError: null,
    evalComplete: null
  }

  /*
   * Internal function, build a string of partials and their update elements.
   */
  Request.prototype.extractPartials = function(update) {
    var result = []

    for (var partial in update)
      result.push(partial)

    return result.join('&')
  }

  // REQUEST PLUGIN DEFINITION
  // ============================

  var old = $.fn.request

  $.fn.request = function(handler, option) {
    var args = arguments

    var $this = $(this).first()
    var data = {
      evalBeforeUpdate: $this.data('request-before-update'),
      evalSuccess: $this.data('request-success'),
      evalError: $this.data('request-error'),
      evalComplete: $this.data('request-complete'),
      confirm: $this.data('request-confirm'),
      redirect: $this.data('request-redirect'),
      loading: $this.data('request-loading'),
      flash: $this.data('request-flash'),
      files: $this.data('request-files'),
      form: $this.data('request-form'),
      update: paramToObj('data-request-update', $this.data('request-update')),
      data: paramToObj('data-request-data', $this.data('request-data'))
    }
    if (!handler) handler = $this.data('request')
    var options = $.extend(true, {}, Request.DEFAULTS, data, typeof option == 'object' && option)
    return new Request($this, handler, options)
  }

  $.fn.request.Constructor = Request

  $.request = function(handler, option) {
    return $(document).request(handler, option)
  }

  // REQUEST NO CONFLICT
  // =================

  $.fn.request.noConflict = function() {
    $.fn.request = old
    return this
  }

  // REQUEST DATA-API
  // ==============

  function paramToObj(name, value) {
    if (value === undefined) value = ''
    if (typeof value == 'object') return value

    try {
      return JSON.parse(JSON.stringify(eval("({" + value + "})")))
    } catch (e) {
      throw new Error('Error parsing the ' + name + ' attribute value. ' + e)
    }
  }

}(window.jQuery);


问:
How to add progress bar until loop execution is finished?
I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.

here is my java code

```<code>    public class Image_Recognition extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image__recognition);

        Button btnNextPage = (Button) findViewById(R.id.btnNextPage);

            btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                        SparseArray<TextBlock> items = textRecognizer.detect(frame);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < items.size(); ++i) {
                            TextBlock item = items.valueAt(i);
                            stringBuilder.append(item.getValue());
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append('.');
                        txtResult.setText(stringBuilder.toString());

                        str = stringBuilder.toString();
                        Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                        myintent.putExtra("translate", str);
                        startActivity(myintent);

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

答:
You could use Async Task and run your loop in doInBackground()

```<code>class MyTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog pd;
    public MyTask(ProgressDialog pd){
        this.pd=pd;
    }
    @Override
    protected void onPreExecute () {
        super.onPreExecute();
        pd.setMessage("Uploading . . .");
        pd.show();
        pd.setCancelable(false);
    }

    @Override
    protected Void doInBackground (Void...voids){
        for(int i=0;i<10000000;i++){
            System.out.print(i);
        }
        return null;//download file
    }

    @Override
    protected void onPostExecute (Void aVoid){
        super.onPostExecute(aVoid);
        pd.dismiss();
    }
}
</code>```

and in activity call new MyTask(pd).execute();

Body:
I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.

here is my java code

    public class Image_Recognition extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image__recognition);

        Button btnNextPage = (Button) findViewById(R.id.btnNextPage);

            btnNextPage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();

                        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                        SparseArray<TextBlock> items = textRecognizer.detect(frame);
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < items.size(); ++i) {
                            TextBlock item = items.valueAt(i);
                            stringBuilder.append(item.getValue());
                            stringBuilder.append("\n");
                        }
                        stringBuilder.append('.');
                        txtResult.setText(stringBuilder.toString());

                        str = stringBuilder.toString();
                        Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
                        myintent.putExtra("translate", str);
                        startActivity(myintent);

                }
            });
        }
    //}
}

Body:
You could use Async Task and run your loop in doInBackground()

class MyTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog pd;
    public MyTask(ProgressDialog pd){
        this.pd=pd;
    }
    @Override
    protected void onPreExecute () {
        super.onPreExecute();
        pd.setMessage("Uploading . . .");
        pd.show();
        pd.setCancelable(false);
    }

    @Override
    protected Void doInBackground (Void...voids){
        for(int i=0;i<10000000;i++){
            System.out.print(i);
        }
        return null;//download file
    }

    @Override
    protected void onPostExecute (Void aVoid){
        super.onPostExecute(aVoid);
        pd.dismiss();
    }
}

and in activity call new MyTask(pd).execute();