问:
Play Video immediately when UIView is loaded
Howdy! I'm writing an iPad app, and I need to be able to play a video when a UIView loads. However, I was getting a BAD_EXC_ACCESS if I try to message my MPMoviePlayerController anywhere after I initialize it. I removed the MPMediaPlayerController from my *.h file, then declared it entirely in the implementation file, and now I'm getting the message at the bottom below my code. There are no issues in Build and Analyze about memory leaks (or any issues, for that matter), and I cannot find any posts about this. Here's my code:

```<code>    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }

 NSString *url = [[NSBundle mainBundle] pathForResource:@"p0600c0100cmpintro" ofType:@"m4v"];
 MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
 NSLog(@"%@", movie);
 movie.view.frame = CGRectMake(5, 0, 1035, 768);
 movie.view.contentMode = UIViewContentModeScaleToFill;
 [[movie view] setCenter:CGPointMake(movie.view.center.x-10, movie.view.center.y)];
 [movie setControlStyle:MPMovieControlStyleNone];
    [movie setShouldAutoplay:YES];
 [[self view] addSubview:[movie view]];

    return self;
    }
</code>```

The NSLog of "movie" gives "MPMoviePlayerController: 0x1b77f0", but then the error message upon crash is "* -[MPMoviePlayerController playbackState]: message sent to deallocated instance 0x1473a0". Help?

答:
According to the documentation it looks like the frame of the movie view needs to match the view of its parent. Also try moving your code out of the initWithNibName:bundle: into viewDidLoad:

```<code>- (void)viewDidLoad {
     [super viewDidLoad];

     UIView *movieContainer = [[UIView alloc] initWithFrame:CGRectMake(5, 0, 300, 400)];
     //Do any other positioning of the view you would like

     NSString *path = [[NSBundle mainBundle] pathForResource:@"p0600c0100cmpintro" ofType:@"m4v"];
     NSURL *url = [NSURL fileURLWithPath:path];
     MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
     movie.view.frame = movieContainer.bounds;  //Make sure this is the bounds of its parent view
     movie.scalingMode = MPMovieScalingModeFill;
     movie.controlStyle = MPMovieControlStyleNone;
     movie.shouldAutoplay = YES;

     [movieContainer addSubview:movie.view];
     [self.view addSubview:movieContainer];

     [movieContainer release];
}
</code>```

One last suggestion would be to keep a reference of the movie so that you can dealloc it once the view controller gets deallocated

Body:
Howdy! I'm writing an iPad app, and I need to be able to play a video when a UIView loads. However, I was getting a BAD_EXC_ACCESS if I try to message my MPMoviePlayerController anywhere after I initialize it. I removed the MPMediaPlayerController from my *.h file, then declared it entirely in the implementation file, and now I'm getting the message at the bottom below my code. There are no issues in Build and Analyze about memory leaks (or any issues, for that matter), and I cannot find any posts about this. Here's my code:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }

 NSString *url = [[NSBundle mainBundle] pathForResource:@"p0600c0100cmpintro" ofType:@"m4v"];
 MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
 NSLog(@"%@", movie);
 movie.view.frame = CGRectMake(5, 0, 1035, 768);
 movie.view.contentMode = UIViewContentModeScaleToFill;
 [[movie view] setCenter:CGPointMake(movie.view.center.x-10, movie.view.center.y)];
 [movie setControlStyle:MPMovieControlStyleNone];
    [movie setShouldAutoplay:YES];
 [[self view] addSubview:[movie view]];

    return self;
    }

The NSLog of "movie" gives "MPMoviePlayerController: 0x1b77f0", but then the error message upon crash is "* -[MPMoviePlayerController playbackState]: message sent to deallocated instance 0x1473a0". Help?

Body:
According to the documentation it looks like the frame of the movie view needs to match the view of its parent. Also try moving your code out of the initWithNibName:bundle: into viewDidLoad:

- (void)viewDidLoad {
     [super viewDidLoad];

     UIView *movieContainer = [[UIView alloc] initWithFrame:CGRectMake(5, 0, 300, 400)];
     //Do any other positioning of the view you would like

     NSString *path = [[NSBundle mainBundle] pathForResource:@"p0600c0100cmpintro" ofType:@"m4v"];
     NSURL *url = [NSURL fileURLWithPath:path];
     MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
     movie.view.frame = movieContainer.bounds;  //Make sure this is the bounds of its parent view
     movie.scalingMode = MPMovieScalingModeFill;
     movie.controlStyle = MPMovieControlStyleNone;
     movie.shouldAutoplay = YES;

     [movieContainer addSubview:movie.view];
     [self.view addSubview:movieContainer];

     [movieContainer release];
}

One last suggestion would be to keep a reference of the movie so that you can dealloc it once the view controller gets deallocated


来源: stackexchange

问:
Show report in iframe with http.get() call
I'm trying to load a report with an http.get() call and show it in an iframe using angularJS 2.0.

My HTML looks like this:

```<code><div class="report-viewer">
    <button (click)="loadReport()">Call API!</button>
    <iframe src="report"></iframe>
</div>
</code>```

Klick on button calls a function in my controller, where I call the API with an http.get()

My controller looks like this:

```<code>import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-report-viewer',
    templateUrl: './report-viewer.component.html',
    styleUrls: ['./report-viewer.component.scss']
})
export class ReportViewerComponent implements OnInit {

    report: Observable<any>;
    reportUrl: "http://localhost:47503/reports/html";

    constructor(private http: Http) { }

    ngOnInit() {
    }

    loadReport() {
        this.http.get(this.reportUrl).map(repsonse => this.report);
    }
}
</code>```

I try to call the API and put my response in my variable report. After that, on the iframe in my HTML I try to show the response like this:

The problem I have is, that my API call doesn't work, when I click on the button. There are no errors in the console, no traffic. I also set a breakpoint in my backend, but it doesn't come throught. It also duplicates my buttons and iframes within (look at screenshot). When I change it like this, it showes me the HTML of my report within my iframe: . So when I put the link directly in the src of the iframe, I got some data (html, css) and also my breakpoint in the backend works (look at screenshot). So whats wrong or whats the difference? Any idea?

Call function from controller:

Call link directly in src of iframe:

答:
try this

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-report-viewer',
    templateUrl: './report-viewer.component.html',
    styleUrls: ['./report-viewer.component.scss']
})
export class ReportViewerComponent implements OnInit {

    report: Observable<any>;
    reportUrl: "http://localhost:47503/reports/html";

    constructor(private http: Http) { }

    ngOnInit() {
    }

    loadReport() {
        this.report = this.http.get(this.reportUrl)
    }
}```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to load a report with an http.get() call and show it in an iframe using angularJS 2.0.

My HTML looks like this:

    <button (click)="loadReport()">Call API!</button>

Klick on button calls a function in my controller, where I call the API with an http.get()

My controller looks like this:

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-report-viewer',
    templateUrl: './report-viewer.component.html',
    styleUrls: ['./report-viewer.component.scss']
})
export class ReportViewerComponent implements OnInit {

    report: Observable<any>;
    reportUrl: "http://localhost:47503/reports/html";

    constructor(private http: Http) { }

    ngOnInit() {
    }

    loadReport() {
        this.http.get(this.reportUrl).map(repsonse => this.report);
    }
}

I try to call the API and put my response in my variable report. After that, on the iframe in my HTML I try to show the response like this:

The problem I have is, that my API call doesn't work, when I click on the button. There are no errors in the console, no traffic. I also set a breakpoint in my backend, but it doesn't come throught. It also duplicates my buttons and iframes within (look at screenshot). When I change it like this, it showes me the HTML of my report within my iframe: . So when I put the link directly in the src of the iframe, I got some data (html, css) and also my breakpoint in the backend works (look at screenshot). So whats wrong or whats the difference? Any idea?

Call function from controller:

Call link directly in src of iframe:


问:
search for example of inconsistent behavior java-8 stream?
In java 8 documentation (doc order stream), one can see this :

if [a stream] is not ordered, repeated execution might produce different
  results.

my question is quite simple : is there an easy way to illustrate this fact in a little unit test (maybe with an HashMap or some thing like this) ?

[Edit] the whole quote is here :

For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.

Thus, my question is about a strictly sequential not parallele execution. It is this case that I'm questioning about.

答:
the documentation of Stream#forEach is already said as below:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

so the following test should be pass:

```<code>List<Integer> ordered = Arrays.asList(1, 2, 3, 4);
List<Integer> unordered = new CopyOnWriteArrayList<>();

ordered.stream().parallel().forEach(unordered::add);

assertThat(unordered, not(equalTo(ordered)));
</code>```

and the operation Stream#findAny also is nondeterministic.

Body:
the documentation of Stream#forEach is already said as below:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

so the following test should be pass:

List<Integer> ordered = Arrays.asList(1, 2, 3, 4);
List<Integer> unordered = new CopyOnWriteArrayList<>();

ordered.stream().parallel().forEach(unordered::add);

assertThat(unordered, not(equalTo(ordered)));

and the operation Stream#findAny also is nondeterministic.


问:
iOS Dev cannot delete Calendar event using eventIdentifier programmatically
I can save event into Calendar user

```<code>    do {
try self.store.save(event, span: .thisEvent, commit: true)
    self.addedEventId = event.eventIdentifier
    print("\(self.addedEventId) has been added")
  }
  catch let error as NSError {
    print("\(error.localizedDescription), userInfo: \(error.userInfo)")
  }
</code>```

it saved the event, and print eventIdentifier

```<code>61211649-CED1-4C74-A140-843AE0C38F44:8B7BDC14DD804F069D455E7B8F3534EF0
</code>```

but when I try to delete the saved event using

```<code>if let eventToRemove = self.store.event(withIdentifier: self.addedEventId)
  {
    do {
      try self.store.remove(eventToRemove, span: .thisEvent)
      print("\(self.addedEventId) removed")
    } catch let error as NSError {
      print("\(error.userInfo)")
    }
  }
</code>```

Seems I cannot find the event using eventIdentifier, the error I have from the console reads

```<code>Error getting event with identifier 61211649-CED1-4C74-A140-843AE0C38F44:8B7BDC14DD804F069D455E7B8F3534EF0: Error Domain=EKCADErrorDomain Code=1010 "(null)
</code>```

答: After half day research, I finally found a way around is instead of using eventIdentifier, using calenderItemIdentifier</p>

Body:
I can save event into Calendar user

    do {
try self.store.save(event, span: .thisEvent, commit: true)
    self.addedEventId = event.eventIdentifier
    print("\(self.addedEventId) has been added")
  }
  catch let error as NSError {
    print("\(error.localizedDescription), userInfo: \(error.userInfo)")
  }

it saved the event, and print eventIdentifier

61211649-CED1-4C74-A140-843AE0C38F44:8B7BDC14DD804F069D455E7B8F3534EF0

but when I try to delete the saved event using

if let eventToRemove = self.store.event(withIdentifier: self.addedEventId)
  {
    do {
      try self.store.remove(eventToRemove, span: .thisEvent)
      print("\(self.addedEventId) removed")
    } catch let error as NSError {
      print("\(error.userInfo)")
    }
  }

Seems I cannot find the event using eventIdentifier, the error I have from the console reads

Error getting event with identifier 61211649-CED1-4C74-A140-843AE0C38F44:8B7BDC14DD804F069D455E7B8F3534EF0: Error Domain=EKCADErrorDomain Code=1010 "(null)


问:
Use external javaScript library in angular application
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

```<code>var timeline = new Timeline("timelineVisualization")
</code>```

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

答:
Just extending on the above answer by @Deblaton Jean-Philippe and as a general good practice, it might be better to include your js or other css files as part of the build instead of putting them in your index.html. </p>

<p>If you are using a bundler, use something like this. </p>

```<code>  "styles": [
    "styles.scss",
    //Other style files
  ],
  "scripts": [
    "../node_modules/jsplugin/dist/js/plugin.js",
    //Other script files
  ],
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

var timeline = new Timeline("timelineVisualization")

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

Body:
Just extending on the above answer by @Deblaton Jean-Philippe and as a general good practice, it might be better to include your js or other css files as part of the build instead of putting them in your index.html.

If you are using a bundler, use something like this.

  "styles": [
    "styles.scss",
    //Other style files
  ],
  "scripts": [
    "../node_modules/jsplugin/dist/js/plugin.js",
    //Other script files
  ],


问:
How to edit input style by using ng-pattern
I made a small js here

I also add the code to the Stack overflow snippet but for some reason it doesn't work to me

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.my_model = ''
   $scope.my_regex = '/^[A-Za-z]+(\,[A-Za-z]+)*$/';
    $scope.my_placeHolder = 'write something';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid input[name=my_input]{
  border: 2px solid red;
}

input[name=my_input] {
  border: 2px solid blue;
}</code>```

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{ 'invalid': contentForm['my_input'].$invalid }"
         ng-model="my_model"
         ng-pattern="{{my_regex}}"
         placeholder="{{my_placeHolder}}">
  </form>

```

I tried to use the code snippet but weren't working >,<

So, my goal is to edit the input border (let's make it red for purpose) if the input text doesn't pass the regex rule.

The regex should accept any comma separated string.

I tried a bunch of stuff, but I can't figure out what am i doing wrong.

UPDATE: REGEX EDITED

答:
In your code snippet, ( )*,( )*[a-zA-Z]+)* regex is not valid. you can test your regex here or other online tool. Here i tried with simple numeric regex and it is working fine.

function formCtrl($scope){
     $scope.my_model = 'test,dfsdf,dfs'
    $scope.my_placeHolder = 'write something';
    $scope.my_pattern="/^[A-Za-z]+(\,[A-Za-z]+)*$/";// here you replace your regex which you want
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid{
  border: 2px solid red;
}

.valid {
  border: 2px solid blue;
}</code>```

<form name="myForm" >
    <input type="text" ng-model="my_model" name="my_input" ng-pattern="
    {{my_pattern}}" ng-class="{'invalid': myForm.my_input.$error.pattern, 'valid': !myForm.my_input.$error.pattern }"
    placeholder="{{my_placeHolder}}"
    />
    Not a valid input!

</form>

```

Body:
I made a small js here

I also add the code to the Stack overflow snippet but for some reason it doesn't work to me

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.my_model = ''
   $scope.my_regex = '/^[A-Za-z]+(\,[A-Za-z]+)*$/';
    $scope.my_placeHolder = 'write something';
}

.invalid input[name=my_input]{
  border: 2px solid red;
}

input[name=my_input] {
  border: 2px solid blue;
}

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{ 'invalid': contentForm['my_input'].$invalid }"
         ng-model="my_model"
         ng-pattern="{{my_regex}}"
         placeholder="{{my_placeHolder}}">
  </form>

I tried to use the code snippet but weren't working >,<

So, my goal is to edit the input border (let's make it red for purpose) if the input text doesn't pass the regex rule.

The regex should accept any comma separated string.

I tried a bunch of stuff, but I can't figure out what am i doing wrong.

UPDATE: REGEX EDITED

Body:
In your code snippet, ( )*,( )*[a-zA-Z]+)* regex is not valid. you can test your regex here or other online tool. Here i tried with simple numeric regex and it is working fine.

function formCtrl($scope){
     $scope.my_model = 'test,dfsdf,dfs'
    $scope.my_placeHolder = 'write something';
    $scope.my_pattern="/^[A-Za-z]+(\,[A-Za-z]+)*$/";// here you replace your regex which you want
}

.invalid{
  border: 2px solid red;
}

.valid {
  border: 2px solid blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<div ng-app ng-controller="formCtrl">
<form name="myForm" >
    <input type="text" ng-model="my_model" name="my_input" ng-pattern="
    {{my_pattern}}" ng-class="{'invalid': myForm.my_input.$error.pattern, 'valid': !myForm.my_input.$error.pattern }"
    placeholder="{{my_placeHolder}}"
    />
    <span ng-show="myForm.my_input.$error.pattern">Not a valid input!</span>

</form>
</div>
</html>


问:
Query with JOIN FETCH performance problem
I have problem with hibernate query performance which I can't figure out. In code snippet below I need select entities with at least one mapping and filtered mapping. I'm using FETCH JOIN for this to load only filtered mappings.
But in that case I have performance problems with query. Hibernate says warning log :

org.hibernate.hql.ast.QueryTranslatorImpl
  - firstResult/maxResults specified with collection fetch; applying in
  memory!

When I omit FETCH JOIN and left only JOIN query is nice fast. But in result I have all mappings loaded to entity which is not acceptable state for me. Is there a way to boost query performance? There are a lot rows in mapping table.

HQL query :

```<code>select distinct e from Entity
   join fetch e.mappings as mapping
where e.deleted = 0 and e.mappings is not empty
   and e = mapping.e and mapping.approval in (:approvals)
</code>```

Entities :

```<code>@Entity
@Table(name="entity")
class Entity {

   ...

   @OneToMany(mappedBy="entity", cascade=CascadeType.REMOVE, fetch=FetchType.LAZY)
   @OrderBy("created")
   private List<Mapping> mappings = new ArrayList<Mapping>();

   ...
}

@Entity
@Table(name="mapping")
class Mapping {

public static enum MappingApproval {
    WAITING, // mapping is waiting for approval
    APPROVED, // mapping was approved
    DECLINED; // mapping was declined
}

...

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="entity_id", nullable=false)
    private Entity entity;

    @Enumerated(EnumType.STRING)
    @Column(name="approval", length=20)
    private MappingApproval approval;

...

}
</code>```

Thanks

答:
If you need a firstResult/maxResults with "fetch" you can split your query in 2 queries:

Query your entity ids with firstResult/maxResults but without the "fetch" on sub-tables:

```<code>select entity.id from entity (without fetch) where .... (with firstResult/maxResults)
</code>```

Query your entities with the "fetch" on the ids returned by your first query:

```<code>select entity from entity fetch ... where id in <previous ids>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have problem with hibernate query performance which I can't figure out. In code snippet below I need select entities with at least one mapping and filtered mapping. I'm using FETCH JOIN for this to load only filtered mappings.
But in that case I have performance problems with query. Hibernate says warning log :

org.hibernate.hql.ast.QueryTranslatorImpl
  - firstResult/maxResults specified with collection fetch; applying in
  memory!

When I omit FETCH JOIN and left only JOIN query is nice fast. But in result I have all mappings loaded to entity which is not acceptable state for me. Is there a way to boost query performance? There are a lot rows in mapping table.

HQL query :

select distinct e from Entity
   join fetch e.mappings as mapping
where e.deleted = 0 and e.mappings is not empty
   and e = mapping.e and mapping.approval in (:approvals)

Entities :

@Entity
@Table(name="entity")
class Entity {

   ...

   @OneToMany(mappedBy="entity", cascade=CascadeType.REMOVE, fetch=FetchType.LAZY)
   @OrderBy("created")
   private List<Mapping> mappings = new ArrayList<Mapping>();

   ...
}

@Entity
@Table(name="mapping")
class Mapping {

public static enum MappingApproval {
    WAITING, // mapping is waiting for approval
    APPROVED, // mapping was approved
    DECLINED; // mapping was declined
}

...

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="entity_id", nullable=false)
    private Entity entity;

    @Enumerated(EnumType.STRING)
    @Column(name="approval", length=20)
    private MappingApproval approval;

...

}

Thanks

Body:
If you need a firstResult/maxResults with "fetch" you can split your query in 2 queries:

Query your entity ids with firstResult/maxResults but without the "fetch" on sub-tables:

select entity.id from entity (without fetch) where .... (with firstResult/maxResults)

Query your entities with the "fetch" on the ids returned by your first query:

select entity from entity fetch ... where id in <previous ids>


问:
How to create modules in C
I have an interface with which I want to be able to statically link modules. For example, I want to be able to call all functions (albeit in seperate files) called FOO or that match a certain prototype, ultimately make a call into a function in the file without a header in the other files. Dont say that it is impossible since I found a hack that can do it, but I want a non hacked method. (The hack is to use nm to get functions and their prototypes then I can dynamically call the function). Also, I know you can do this with dynamic linking, however, I want to statically link the files. Any ideas?</p>

答:
You really need static linking and, at the same time, to select all matching functions at runtime, right? Because the latter is a typical case for dynamic linking, i'd say.

You obviusly need some mechanism to register the available functions. Dynamic linking would provide just this.

Title: How to create modules in C


问:
What exactly is the benefit of the HTML5 async attribute on script elements?
I have some confusion around the new async attribute to the script element in HTML5 that I hope someone can give a clear answer to.

Browsers are capable of Parallel Connections, therefore images will be downloaded in parallel. But any external javascript is not downloaded in parallel with other external javascript and images. Scripts block page loading until they have been downloaded and executed.

To download a script without blocking the rest of the page loading, the most common technique is to create a script element, like Google Analytics snippet does:

```<code>var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.src = '...ga.js';
ga.async = true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
</code>```

I'm not sure of how that works exactly -
either

the browser parses and renders the page, then once it has finished it notices the DOM has changed, resulting in the ga.js script being downloaded and executed

or

the browser starts downloading the javascript in parallel with other resources.

I think it is the latter.

The new asynchronous Google Analytics snippet includes the HTML5 async attribute in the script element it creates. That will not help the page blocking problem - that has already been solved by the "Script DOM Element" technique. So what does async add to the picture? According to w3schools, "if async is present, the script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)".

And according to Steve Souders site, "the main benefit of this [async attribute] is it tells the browser that subsequent scripts can be executed immediately – they don’t have to wait for ga.js".

So are async and the Script DOM element technique both solving the same problem?

Body:
I have some confusion around the new async attribute to the script element in HTML5 that I hope someone can give a clear answer to.

Browsers are capable of Parallel Connections, therefore images will be downloaded in parallel. But any external javascript is not downloaded in parallel with other external javascript and images. Scripts block page loading until they have been downloaded and executed.

To download a script without blocking the rest of the page loading, the most common technique is to create a script element, like Google Analytics snippet does:

var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.src = '...ga.js';
ga.async = true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);

I'm not sure of how that works exactly -
either

the browser parses and renders the page, then once it has finished it notices the DOM has changed, resulting in the ga.js script being downloaded and executed

or

the browser starts downloading the javascript in parallel with other resources.

I think it is the latter.

The new asynchronous Google Analytics snippet includes the HTML5 async attribute in the script element it creates. That will not help the page blocking problem - that has already been solved by the "Script DOM Element" technique. So what does async add to the picture? According to w3schools, "if async is present, the script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)".

And according to Steve Souders site, "the main benefit of this [async attribute] is it tells the browser that subsequent scripts can be executed immediately – they don’t have to wait for ga.js".

So are async and the Script DOM element technique both solving the same problem?

Body:
According to https://www.html5rocks.com/en/tutorials/speed/script-loading/ if a <script> element is added dynamically it may not be executed until DOMContentLoaded is fired. That is, some user agents (e.g. MSIE 10) will wait until DOM is ready before running dynamically added <script> elements.

I guess Google wants to get their analytics code running faster on those user agents and as such they need to add async flag to tell the browser (e.g. MSIE 10) that it's okay to start executing the script as soon as possible. HTML5 compatible browsers would execute as if the async true even if it was not defined so the async=true has been added only to improve performance with non-HTML5 browsers.


问:
SQL invalid Identifier query
I am getting an error that grandvisit is an invalid identifier, and I am unsure if I will get it with other identifiers either. Any light shed on this would be amazing. As I cannot see why it differents from others.</p>

答:
You cannot refer the alias names in same select clause where it is generated.

```<code>SELECT Sum(aerosolvisit + hazvisit + hvvisit + hlopvisit
           + plvisit + miniloadvisit + aprvisit + apr2visit
           + aprawkvisit) AS grandvisit
</code>```

To calculate grandratio you are using the below expression which uses the alias name grandvisit

```<code>SELECT CASE
         WHEN Sum(grandtotal) = 0 THEN 0
         WHEN Sum(grandvisit) = 0 THEN 0
         ELSE Sum(grandtotal) / Sum(grandvisit)
       END AS grandratio
</code>```

You can use derived table to do this

```<code>SELECT CASE
         WHEN Sum(grandtotal) = 0 THEN 0
         WHEN Sum(grandvisit) = 0 THEN 0
         ELSE Sum(grandtotal) / Sum(grandvisit)
       END AS grandratio
From
(
SELECT Sum(aerosolvisit + hazvisit + hvvisit + hlopvisit
           + plvisit + miniloadvisit + aprvisit + apr2visit
           + aprawkvisit) AS grandvisit
 ...
) A
</code>```

Note : You are using old style outer join's(+=). It is better to use Right/Left joins which is more readable

Title: SQL invalid Identifier query

Body:
You cannot refer the alias names in same select clause where it is generated.

SELECT Sum(aerosolvisit + hazvisit + hvvisit + hlopvisit
           + plvisit + miniloadvisit + aprvisit + apr2visit
           + aprawkvisit) AS grandvisit

To calculate grandratio you are using the below expression which uses the alias name grandvisit

SELECT CASE
         WHEN Sum(grandtotal) = 0 THEN 0
         WHEN Sum(grandvisit) = 0 THEN 0
         ELSE Sum(grandtotal) / Sum(grandvisit)
       END AS grandratio

You can use derived table to do this

SELECT CASE
         WHEN Sum(grandtotal) = 0 THEN 0
         WHEN Sum(grandvisit) = 0 THEN 0
         ELSE Sum(grandtotal) / Sum(grandvisit)
       END AS grandratio
From
(
SELECT Sum(aerosolvisit + hazvisit + hvvisit + hlopvisit
           + plvisit + miniloadvisit + aprvisit + apr2visit
           + aprawkvisit) AS grandvisit
 ...
) A

Note : You are using old style outer join's(+=). It is better to use Right/Left joins which is more readable


问:
How can I get a child component's watcher's updated value from parent component in Vue 2?
I have two components that are in a parent-child relationship. In the child select component I've defined a watcher for the currently selected value and I want the parent to get the updated value whenever it changes. I tried to use events but the parent can only listen to its own vm.

In the child component

```<code>watch: {
  selected (value) {
    this.$emit('selectedYearChange', value)
  }
}
</code>```

In the parent

```<code>mounted () {
  this.$on('selectedYearChange', function (value) {
    this.selectedYear = value
  })
}
</code>```

This obviously doesn't work because of the reason I mentioned above.

I wasn't able to find relevant examples in the documentation.

答:
You can setup an event listener on the child component element itself where its used in the parent and pass it a method to be executed

```<code>//parent component
<div id="app>
    <child-comp @selected-year-change='changeYear'></child-comp>
</div>
</code>```

In your parent component use the method changeYear to change the value of `selectedYear'

```<code>methods:{
    //you get the event as the parameter
    changeYear(value){
        this.selectedYear = value
    }
}
</code>```

See the fiddle

And avoid using camelCase for event names use kebab-case instead as HTML attributes are case-insensitive and may cause problems

Body:
I have two components that are in a parent-child relationship. In the child select component I've defined a watcher for the currently selected value and I want the parent to get the updated value whenever it changes. I tried to use events but the parent can only listen to its own vm.

In the child component

watch: {
  selected (value) {
    this.$emit('selectedYearChange', value)
  }
}

In the parent

mounted () {
  this.$on('selectedYearChange', function (value) {
    this.selectedYear = value
  })
}

This obviously doesn't work because of the reason I mentioned above.

I wasn't able to find relevant examples in the documentation.

Body:
You can setup an event listener on the child component element itself where its used in the parent and pass it a method to be executed

//parent component
<div id="app>
    <child-comp @selected-year-change='changeYear'></child-comp>
</div>

In your parent component use the method changeYear to change the value of `selectedYear'

methods:{
    //you get the event as the parameter
    changeYear(value){
        this.selectedYear = value
    }
}

See the fiddle

And avoid using camelCase for event names use kebab-case instead as HTML attributes are case-insensitive and may cause problems


问:
android textsize dimen resource link changes to the value
I have added textsize attribute to the button as follows

```<code>android:textsize="@dimen/button_size"
</code>```

but if i close the content_mail.xml file and then reopen it, it automatically changes to

```<code>android:textsize="17dp"
</code>```

as i have the size for button_size as 17dp in dimens.xml file.
How to fix this?

答: If your are using Android Studio , it doesn't change to "17sp" , Android Studio show you a "preview" of value from dimen.xml in grey color. If you click the value you will see "@dimen/button_size".</p>

Body:
I have added textsize attribute to the button as follows

android:textsize="@dimen/button_size"

but if i close the content_mail.xml file and then reopen it, it automatically changes to

android:textsize="17dp"

as i have the size for button_size as 17dp in dimens.xml file.
How to fix this?


问:
Hours of Day, Days of Week Visual Screen for Web Application
I need a visual frame for my application. There will be hours of day(no need to minutes as like 1:00pm, 1:15pm, 1:30pm, 1:45pm, 2:00pm or something like that, just 1:00pm and 2:00pm is enough) and days of week(no need for weeks of month) And user will be able to select the hours of each day. In my program, it will say that Sunday 1-2 has selected, Monday 9am-1pm and 3pm-6pm have selected or something like that... How can I do that. I searched for JQuery but could find only this: http://www.webdesignbooth.com/9-useful-jquery-calendar-and-date-picker-plugins-for-web-designers/  and this are not for me or I dont can I modify one of them and suitable for my program? </p>

答: You can use simple list (or div, or option) with Timepicker addon for every list item. Timepicker lets yuo to use an hours (and even minutes if you need that).</p>


问:
How to make Twitter Bootstrap menu dropdown on hover rather than click
I'd like to have my Bootstrap menu automatically drop down on hover, rather than having to click the menu title. I'd also like to lose the little arrows next to the menu titles.</p>

答:
```<code> <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
          <ul class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      <script>
        $('ul.nav li.dropdown').hover(function() {
        $(this).find('.dropdown-menu').stop(true,
        true).delay(200).fadeIn(500);
        }, function() {
        $(this).find('.dropdown-menu').stop(true,
        true).delay(200).fadeOut(500);
        });
      </script>
</code>```


问:
Convert ImmutableListMultimap to Map using Collectors.toMap
I would like to convert a  ImmutableListMultimap<String, Character> to Map<String, List<Character>>.
I used to do it in the non-stream way as follows

```<code>    void convertMultiMaptoList(ImmutableListMultimap<String, Character> reverseImmutableMultiMap) {
            Map<String, List<Character>> result = new TreeMap<>();
          for( Map.Entry<String, Character> entry: reverseImmutableMultiMap.entries()) {
              String key = entry.getKey();
              Character t = entry.getValue();
          result.computeIfAbsent(key, x-> new ArrayList<>()).add(t);
       }
       //reverseImmutableMultiMap.entries().stream().collect(Collectors.toMap)
}
</code>```

I was wondering how to write the above same logic using java8 stream way (Collectors.toMap).

Please share your thoughts

答:
```<code>Map<String, List<Character>> result = reverseImmutableMultiMap.entries().stream()
    .collect(groupingBy(Entry::getKey, TreeMap::new, mapping(Entry::getValue, toList())));
</code>```

The important detail is mapping. It will convert the collector (toList) so that it collects List<Character> instead of List<Entry<String, Character>>. According to the mapping function Entry::getValue

groupingBy will group all entries by the String key

toList will collect all values with same key to a list

Also, passing TreeMap::new as an argument to groupingBy will make sure you get this specific type of Map instead of the default HashMap

Body:
I would like to convert a  ImmutableListMultimap<String, Character> to Map<String, List<Character>>.
I used to do it in the non-stream way as follows

    void convertMultiMaptoList(ImmutableListMultimap<String, Character> reverseImmutableMultiMap) {
            Map<String, List<Character>> result = new TreeMap<>();
          for( Map.Entry<String, Character> entry: reverseImmutableMultiMap.entries()) {
              String key = entry.getKey();
              Character t = entry.getValue();
          result.computeIfAbsent(key, x-> new ArrayList<>()).add(t);
       }
       //reverseImmutableMultiMap.entries().stream().collect(Collectors.toMap)
}

I was wondering how to write the above same logic using java8 stream way (Collectors.toMap).

Please share your thoughts

Body:
Map<String, List<Character>> result = reverseImmutableMultiMap.entries().stream()
    .collect(groupingBy(Entry::getKey, TreeMap::new, mapping(Entry::getValue, toList())));

The important detail is mapping. It will convert the collector (toList) so that it collects List<Character> instead of List<Entry<String, Character>>. According to the mapping function Entry::getValue

groupingBy will group all entries by the String key

toList will collect all values with same key to a list

Also, passing TreeMap::new as an argument to groupingBy will make sure you get this specific type of Map instead of the default HashMap


问:
Installing VC++ 6.0 on Industrial PC with Windows 7 and 64 bit system
I have an industrial PC on which I need to install Visual Studio 6.0 . The industrial PC is Windows 7 Professional , 64 bit system.
The error I am getting is "Compatibility issues with this version of Windows". This error is coming on :
1. starting VC++ (twice the msg will be prompted) ,
2. compiling the program (however,the program is compiling after this error msg) but

my program is giving "debug assertion error"

That same program is working perfectly on my laptop which is also 64 bit and Windows 7 Professional and is using Visual Studio 6.0

I have tried disabling the UAC ,  creating an empty MSJAVA.DLL file , downloading ,registering dx7vb.dll , updating command controls and then installing VC++ in Administrator mode also.

I have also tried changing the compatibility mode to WindowsXP Service Pack2 and running the setup in administrator mode.

I have tried almost all solutions online, but nothing is working for me.

Kindly help.

答:
Take a look in my tool VS6 Installer 4.8 page

http://nuke.vbcorner.net/Articles/VB60/VisualStudio6Installer/tabid/93/language/en-US/Default.aspx

Below the image, you can find then link titled:

For MSDEV.EXE see here

which refere to a tutorial of martin-moene blogspot where explain How To.

Please take note that in this tutorial refert to a very-old version of VS6 Installer 2.1, which isn't longer available and superseded by latest 4.8.

IMPORTANT: you already tried to install MS Visual Studio 6.0, therefore you need BEFORE clean your system (as explained on VS6 Installer page and others tutorials, english ed italian language)
HTH


问:
PopupMenu avoid dismiss on click of Keyboard
I'm facing an issue without being able to find an answer. I have an editText with a TextWatcher to find a list of results in a database. I display the result in a PopupMenu. It looks like this :

```<code>final List<SearchResult> searchResults = new ArrayList<>();

    final PopupMenu menu = new PopupMenu(getActivity(), binding.bottomSheetWriteNews.editTextNewsSubCategory);
    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            binding
                    .bottomSheetWriteNews
                    .editTextNewsSubCategory
                    .setText(item.getTitle());

            return false;
        }
    });

    final Realm realm = Realm.getDefaultInstance();

    binding.bottomSheetWriteNews.editTextNewsSubCategory.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            searchResults.clear();
            menu.getMenu().clear();

            RealmResults<SubCategory> subCategoriesResult = realm.where(SubCategory.class).contains("name", s.toString(), Case.INSENSITIVE).findAll();
            for(SubCategory subCategory : subCategoriesResult) {
                searchResults.add(new SearchResult(subCategory.getId(), subCategory.getName(), false));
                menu.getMenu().add(subCategory.getName());
            }
            menu.show();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
</code>```

My issue is every-time I click on the Keyboard the PopupMenu is dismiss instead of typing the character I wanted. That's annoying and unusable for users. I want the click on keyboard to not dismiss the PopupMenu. I know that in the official documentation it's written Touching outside of the popup will dismiss it, but I'm using Google Keep, and they have the same feature (typing text display a PopupMenu to filter results) without my issue.

Thanks for your help !

答:
Instead of using popup menu you can use

spinner or (list view or recycler view )

and do notifyDataSetChanged().

So that the layout won't get piling(off and on)

Hope it will help you.

Body:
I'm facing an issue without being able to find an answer. I have an editText with a TextWatcher to find a list of results in a database. I display the result in a PopupMenu. It looks like this :

final List<SearchResult> searchResults = new ArrayList<>();

    final PopupMenu menu = new PopupMenu(getActivity(), binding.bottomSheetWriteNews.editTextNewsSubCategory);
    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            binding
                    .bottomSheetWriteNews
                    .editTextNewsSubCategory
                    .setText(item.getTitle());

            return false;
        }
    });

    final Realm realm = Realm.getDefaultInstance();

    binding.bottomSheetWriteNews.editTextNewsSubCategory.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            searchResults.clear();
            menu.getMenu().clear();

            RealmResults<SubCategory> subCategoriesResult = realm.where(SubCategory.class).contains("name", s.toString(), Case.INSENSITIVE).findAll();
            for(SubCategory subCategory : subCategoriesResult) {
                searchResults.add(new SearchResult(subCategory.getId(), subCategory.getName(), false));
                menu.getMenu().add(subCategory.getName());
            }
            menu.show();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

My issue is every-time I click on the Keyboard the PopupMenu is dismiss instead of typing the character I wanted. That's annoying and unusable for users. I want the click on keyboard to not dismiss the PopupMenu. I know that in the official documentation it's written Touching outside of the popup will dismiss it, but I'm using Google Keep, and they have the same feature (typing text display a PopupMenu to filter results) without my issue.

Thanks for your help !


问:
What are the best use cases for Akka framework
I have heard lots of raving about Akka framework (Java/Scala service platform), but so far have not seen many actual examples of use cases it would be good for. So I would be interested in hearing about things developers have used it succesfully.

Only one limitation: please do not include case of writing a chat server.
(why? since this has been overused as an example for lots of similar things)

答:
Disclaimer: I am the PO for Akka

Besides offering a concurrency smorgasbord that is much simpler to reason about and to get correct (actors, agents, dataflow concurrency) and with concurrency control in the form of STM.

Here are some use-cases you might consider:

Transaction processing (online
gaming, finance, statistics,
betting, social media, telecom, ...)

scale up, scale out, fault-tolerance / HA

Service backend (any industry, any app)

service REST, SOAP, cometd etc

act as message hub / integration layer

scale up, scale out, fault-tolerance / HA

Snap-in concurrency/parallelism ( any app )

Correct

Simple to work with and understand

Just add the jars to your existing JVM project (use Scala,
Java, Groovy or JRuby)

Batch processing ( any industry )

Camel integration to hook up with batch data sources

Actors divide and conquer the batch workloads

Communications hub ( telecom, web media, mobile media )

scale up, scale out, fault-tolerance / HA

Game server (online gaming, betting)

scale up, scale out, fault-tolerance / HA

BI/datamining/general purpose crunching

scale up, scale out, fault-tolerance / HA

insert other nice use cases here


问:
Installing data science packages to vanilla python
How to download necessary python packages for data analysis (e.g. pandas,scipy,numpy etc) and machine learning packages (sci-kit learn for starter, tensorflow for deeplearning if possible etc) without using github or anaconda?

Our client has permitted us to install python 3.6 and above (32-bit) in our terminals for data analysis and machine learning projects but we cannot access github due to security restrictions and also cannot download anaconda bundle.

Please provide suitable weblinks and instructions.

答:
Install the packages using pip(Python package manager).
Simply use the following "pip" command in the terminal and install them.
For an example, if you are installing the tensorflow package enter the following command in the terminal.

```<code>pip install tensorflow
</code>```

Refer this URL for more instructions.
https://packaging.python.org/tutorials/installing-packages/

Body:
Install the packages using pip(Python package manager).
Simply use the following "pip" command in the terminal and install them.
For an example, if you are installing the tensorflow package enter the following command in the terminal.

pip install tensorflow

Refer this URL for more instructions.
https://packaging.python.org/tutorials/installing-packages/


问:
Replacing Divi Fullwidth Menu with UberMenu
I am using Divi Theme and I need a way to integrate UberMenu in the Fullwidth Menu module.

I searched header.php but I can't see any code regarding the Fullwidth Menu module.

This is what I find when I look at it with the inspector

```<code><div class="et_pb_fullwidth_menu
            et_pb_module
            et_pb_bg_layout_light
            et_pb_text_align_left
            et_dropdown_animation_fade
            et_pb_fullwidth_menu_0"
     style="background-color: #ffffff;"
     data-bg_color="#ffffff"
</code>```

I can't find something like this on the theme.

I tried to use the same theme location but it looks like the ubermenu takes no effect , I can  still see the normal Fullwidth Menu.

<link rel="stylesheet" id="dashicons-css" href="ht.tp://localhost/wordpress/wp-includes/css/dashicons.min.css?ver=4.3.1" type="text/css" media="all">
<link rel="stylesheet" id="editor-buttons-css" href="ht.tp://localhost/wordpress/wp-includes/css/editor.min.css?ver=4.3.1" type="text/css" media="all">

<button type="button" id="insert-media-button" class="button insert-media add_media" data-editor="wpined_textarea"> Add Media</button>

<button type="button" id="wpined_textarea-tmce" class="wp-switch-editor switch-tmce" data-wp-editor-id="wpined_textarea">Visual</button>
<button type="button" id="wpined_textarea-html" class="wp-switch-editor switch-html" data-wp-editor-id="wpined_textarea">Text</button>

<input id="qt_wpined_textarea_strong" class="ed_button button button-small" aria-label="Bold" value="b" type="button"><input id="qt_wpined_textarea_em" class="ed_button button button-small" aria-label="Italic" value="i" type="button"><input id="qt_wpined_textarea_link" class="ed_button button button-small" aria-label="Insert link" value="link" type="button"><input id="qt_wpined_textarea_block" class="ed_button button button-small" aria-label="Blockquote" value="b-quote" type="button"><input id="qt_wpined_textarea_del" class="ed_button button button-small" aria-label="Deleted text (strikethrough)" value="del" type="button"><input id="qt_wpined_textarea_ins" class="ed_button button button-small" aria-label="Inserted text" value="ins" type="button"><input id="qt_wpined_textarea_img" class="ed_button button button-small" aria-label="Insert image" value="img" type="button"><input id="qt_wpined_textarea_ul" class="ed_button button button-small" aria-label="Bulleted list" value="ul" type="button"><input id="qt_wpined_textarea_ol" class="ed_button button button-small" aria-label="Numbered list" value="ol" type="button"><input id="qt_wpined_textarea_li" class="ed_button button button-small" aria-label="List item" value="li" type="button"><input id="qt_wpined_textarea_code" class="ed_button button button-small" aria-label="Code" value="code" type="button"><input id="qt_wpined_textarea_more" class="ed_button button button-small" aria-label="Insert Read More tag" value="more" type="button"><input id="qt_wpined_textarea_close" class="ed_button button button-small" title="Close all open tags" value="close tags" type="button">

<textarea class="wp-editor-area" rows="20" autocomplete="off" cols="40" name="wpined_textarea" id="wpined_textarea"></textarea>

Services

Gallery

About us

Contact

Services

Gallery

About us

Contact

```

答:
Check this: http://sevenspark.com/docs/ubermenu-3/theme-integration/divi
This should works for you.</p>

Body:
I am using Divi Theme and I need a way to integrate UberMenu in the Fullwidth Menu module.

I searched header.php but I can't see any code regarding the Fullwidth Menu module.

This is what I find when I look at it with the inspector

<div class="et_pb_fullwidth_menu
            et_pb_module
            et_pb_bg_layout_light
            et_pb_text_align_left
            et_dropdown_animation_fade
            et_pb_fullwidth_menu_0"
     style="background-color: #ffffff;"
     data-bg_color="#ffffff"

I can't find something like this on the theme.

I tried to use the same theme location but it looks like the ubermenu takes no effect , I can  still see the normal Fullwidth Menu.

<link rel="stylesheet" id="dashicons-css" href="ht.tp://localhost/wordpress/wp-includes/css/dashicons.min.css?ver=4.3.1" type="text/css" media="all">
<link rel="stylesheet" id="editor-buttons-css" href="ht.tp://localhost/wordpress/wp-includes/css/editor.min.css?ver=4.3.1" type="text/css" media="all">

<button type="button" id="insert-media-button" class="button insert-media add_media" data-editor="wpined_textarea"> Add Media</button>

<button type="button" id="wpined_textarea-tmce" class="wp-switch-editor switch-tmce" data-wp-editor-id="wpined_textarea">Visual</button>
<button type="button" id="wpined_textarea-html" class="wp-switch-editor switch-html" data-wp-editor-id="wpined_textarea">Text</button>

<input id="qt_wpined_textarea_strong" class="ed_button button button-small" aria-label="Bold" value="b" type="button"><input id="qt_wpined_textarea_em" class="ed_button button button-small" aria-label="Italic" value="i" type="button"><input id="qt_wpined_textarea_link" class="ed_button button button-small" aria-label="Insert link" value="link" type="button"><input id="qt_wpined_textarea_block" class="ed_button button button-small" aria-label="Blockquote" value="b-quote" type="button"><input id="qt_wpined_textarea_del" class="ed_button button button-small" aria-label="Deleted text (strikethrough)" value="del" type="button"><input id="qt_wpined_textarea_ins" class="ed_button button button-small" aria-label="Inserted text" value="ins" type="button"><input id="qt_wpined_textarea_img" class="ed_button button button-small" aria-label="Insert image" value="img" type="button"><input id="qt_wpined_textarea_ul" class="ed_button button button-small" aria-label="Bulleted list" value="ul" type="button"><input id="qt_wpined_textarea_ol" class="ed_button button button-small" aria-label="Numbered list" value="ol" type="button"><input id="qt_wpined_textarea_li" class="ed_button button button-small" aria-label="List item" value="li" type="button"><input id="qt_wpined_textarea_code" class="ed_button button button-small" aria-label="Code" value="code" type="button"><input id="qt_wpined_textarea_more" class="ed_button button button-small" aria-label="Insert Read More tag" value="more" type="button"><input id="qt_wpined_textarea_close" class="ed_button button button-small" title="Close all open tags" value="close tags" type="button">

<textarea class="wp-editor-area" rows="20" autocomplete="off" cols="40" name="wpined_textarea" id="wpined_textarea"></textarea>

Services

Gallery

About us

Contact

Services

Gallery

About us

Contact


问:
Storing Url into Firebase -Xamarin
I am able to store my images into my database. In my image table, i want the url itself but when i save the image i get this kind of url(i can't tell if it is a url or not) which looks like "md59ff87d3098d3e76b10bcffd04c4d249f.Image@429ed2f8" but i want something like firebase.com/pet.jpg so i can call it back into my imageview. The problem seems to be in my OnSuccess(). How do i get this done please?

```<code>protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {

                uri = data.Data;

                try
                {

                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    imageViewDrop.SetImageBitmap(bitmap);

                }
                catch (FileNotFoundException e)
                {

                    e.StackTrace.ToString();
                }

                catch (IOException e)
                {
                    e.StackTrace.ToString();
                }

                if (uri != null)
                {
                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();

                    StorageReference image = storageRef.Child(FB_STORAGE_PATH +System.DateTime.Today + "." + GetImageExt(uri));

                    image.PutFile(uri).AddOnSuccessListener(this).AddOnFailureListener(this);

                    image.PutFile(uri).AddOnProgressListener(this);

               }

            }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

            ImageUpload uploads = new ImageUpload(uri.ToString());

            string uploadId = mDatabaseImage.Push().Key;
            mDatabaseImage.Child(user.Uid).Child(phId).Child(uploadId).SetValue(uploads.ToString());

        }
</code>```

update

```<code>  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {
                uri = data.Data;

                for (int i = 0; i < 5; i++){

                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();
                    StorageReference oneRef = storageRef.Child("one " + i + "png.");
                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    MemoryStream stream = new MemoryStream();
                    bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                    byte[] myData = stream.ToArray();

                    uploadTask = oneRef.PutBytes(myData);
                    uploadTask.AddOnSuccessListener(this);
                    uploadTask.AddOnFailureListener(this);
                }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            var url = snapshot.Storage.Path;
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }

        public void OnFailure(Java.Lang.Exception e)
        {
            pd.Dismiss();

            Toast.MakeText(this, e.Message, ToastLength.Short).Show();

        }
</code>```

答:
You have to cast your result to UploadTask so as to get the DownloadUrl like this</p>

```<code>public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            string url = ((UploadTask.TaskSnapshot)result).DownloadUrl.ToString();
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }
</code>```

Title: Storing Url into Firebase -Xamarin

Body:
I am able to store my images into my database. In my image table, i want the url itself but when i save the image i get this kind of url(i can't tell if it is a url or not) which looks like "md59ff87d3098d3e76b10bcffd04c4d249f.Image@429ed2f8" but i want something like firebase.com/pet.jpg so i can call it back into my imageview. The problem seems to be in my OnSuccess(). How do i get this done please?

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {

                uri = data.Data;

                try
                {

                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    imageViewDrop.SetImageBitmap(bitmap);

                }
                catch (FileNotFoundException e)
                {

                    e.StackTrace.ToString();
                }

                catch (IOException e)
                {
                    e.StackTrace.ToString();
                }

                if (uri != null)
                {
                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();

                    StorageReference image = storageRef.Child(FB_STORAGE_PATH +System.DateTime.Today + "." + GetImageExt(uri));

                    image.PutFile(uri).AddOnSuccessListener(this).AddOnFailureListener(this);

                    image.PutFile(uri).AddOnProgressListener(this);

               }

            }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

            ImageUpload uploads = new ImageUpload(uri.ToString());

            string uploadId = mDatabaseImage.Push().Key;
            mDatabaseImage.Child(user.Uid).Child(phId).Child(uploadId).SetValue(uploads.ToString());

        }

update

  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {
                uri = data.Data;

                for (int i = 0; i < 5; i++){

                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();
                    StorageReference oneRef = storageRef.Child("one " + i + "png.");
                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    MemoryStream stream = new MemoryStream();
                    bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                    byte[] myData = stream.ToArray();

                    uploadTask = oneRef.PutBytes(myData);
                    uploadTask.AddOnSuccessListener(this);
                    uploadTask.AddOnFailureListener(this);
                }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            var url = snapshot.Storage.Path;
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }

        public void OnFailure(Java.Lang.Exception e)
        {
            pd.Dismiss();

            Toast.MakeText(this, e.Message, ToastLength.Short).Show();

        }

Body:
You have to cast your result to UploadTask so as to get the DownloadUrl like this

public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            string url = ((UploadTask.TaskSnapshot)result).DownloadUrl.ToString();
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }


问:
How to filter by postal code range?
I have to do an ExecuteMultiple, using a filter on the system-field address1_postalcode.

The condition of the filter is that the postal code should be in a range.

I used these two filters, but the result doesn't take into account the condition:

```<code>filter.Conditions.Add(
  new ConditionExpression(
    "address1_postalcode",
    ConditionOperator.LessThan,
    postalcodeMax
  )
);

filter.Conditions.Add(
  new ConditionExpression(
    "address1_postalcode",
    ConditionOperator.GreaterThan,
    postalcodeMin
  )
);
</code>```

postalcodeMin and postalcodeMax are integers, and I know that postalCode field is string.

Do you have any idea?

答:
You cannot do this kind of query on a Single line of text: you have to convert the value to a number.

A solution (off the top of my head) might be to create a custom numeric field, and fill it on-the-fly through a plugin on retrieve.

Title: How to filter by postal code range?

Body:
I have to do an ExecuteMultiple, using a filter on the system-field address1_postalcode.

The condition of the filter is that the postal code should be in a range.

I used these two filters, but the result doesn't take into account the condition:

filter.Conditions.Add(
  new ConditionExpression(
    "address1_postalcode",
    ConditionOperator.LessThan,
    postalcodeMax
  )
);

filter.Conditions.Add(
  new ConditionExpression(
    "address1_postalcode",
    ConditionOperator.GreaterThan,
    postalcodeMin
  )
);

postalcodeMin and postalcodeMax are integers, and I know that postalCode field is string.

Do you have any idea?


问:
Creating SHA1 Hash from NSString
How can I create a SHA1 from a NSString.

Let's say the NSString is set up as:

```<code>NSString *message = @"Message";
</code>```

I can use PHP to create a SHA1 hash with sha($message). But unfortunately it doesn't work like that within Objective-C.

答:
I'm seeing a few different possible improvements to the answers in this post.

Never make an unprefixed category. What if you implement -[NSString sha1Hash] in your library, and another library in the same app implements the same method with slightly different semantics? Which one is used will be random, and lead to hard-to-diagnose errors.

If you want a string, there is base64-encoding in the standard library nowadays. Less work than manually building hex stringification.

Here's my solution, adapted from the excellent SocketRocket library's SRHash.m:

```<code>// NSString+Sha1Digest.h
#import <Foundation/Foundation.h>

@interface NSString (LBDigest)
- (NSString *)lb_digestString;
@end

@interface NSData (LBDigest)
- (NSString *)lb_digestString;
@end

// NSString+SHA1Digest.m
#import "NSString+Sha1Digest.h"
#import <CommonCrypto/CommonDigest.h>

static NSData *LBSHA1HashFromBytes(const char *bytes, size_t length)
{
    uint8_t outputLength = CC_SHA1_DIGEST_LENGTH;
    unsigned char output[outputLength];
    CC_SHA1(bytes, (CC_LONG)length, output);

    return [NSData dataWithBytes:output length:outputLength];
}

static NSData *LBSHA1HashFromString(NSString *string)
{
    size_t length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    return LBSHA1HashFromBytes(string.UTF8String, length);
}

@implementation NSData (LBDigest)
- (NSString *)lb_digestString;
{
    return [LBSHA1HashFromBytes(self.bytes, self.length) base64EncodedStringWithOptions:0];
}
@end

@implementation NSString (LBDigest)
- (NSString *)lb_digestString;
{
    return [LBSHA1HashFromString(self) base64EncodedStringWithOptions:0];
}
@end
</code>```

Title: Creating SHA1 Hash from NSString

Body:
How can I create a SHA1 from a NSString.

Let's say the NSString is set up as:

NSString *message = @"Message";

I can use PHP to create a SHA1 hash with sha($message). But unfortunately it doesn't work like that within Objective-C.

Body:
I'm seeing a few different possible improvements to the answers in this post.

Never make an unprefixed category. What if you implement -[NSString sha1Hash] in your library, and another library in the same app implements the same method with slightly different semantics? Which one is used will be random, and lead to hard-to-diagnose errors.

If you want a string, there is base64-encoding in the standard library nowadays. Less work than manually building hex stringification.

Here's my solution, adapted from the excellent SocketRocket library's SRHash.m:

// NSString+Sha1Digest.h
#import <Foundation/Foundation.h>

@interface NSString (LBDigest)
- (NSString *)lb_digestString;
@end

@interface NSData (LBDigest)
- (NSString *)lb_digestString;
@end

// NSString+SHA1Digest.m
#import "NSString+Sha1Digest.h"
#import <CommonCrypto/CommonDigest.h>

static NSData *LBSHA1HashFromBytes(const char *bytes, size_t length)
{
    uint8_t outputLength = CC_SHA1_DIGEST_LENGTH;
    unsigned char output[outputLength];
    CC_SHA1(bytes, (CC_LONG)length, output);

    return [NSData dataWithBytes:output length:outputLength];
}

static NSData *LBSHA1HashFromString(NSString *string)
{
    size_t length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    return LBSHA1HashFromBytes(string.UTF8String, length);
}

@implementation NSData (LBDigest)
- (NSString *)lb_digestString;
{
    return [LBSHA1HashFromBytes(self.bytes, self.length) base64EncodedStringWithOptions:0];
}
@end

@implementation NSString (LBDigest)
- (NSString *)lb_digestString;
{
    return [LBSHA1HashFromString(self) base64EncodedStringWithOptions:0];
}
@end


问:
Handling larger strings in Sql Server 2008
We have an stored procedure that we created so that user can write comma separated search tags in their software product's admin. So he can add comma-separated tags and in case if he wants to edit them, we read from the table all the tags, recreate them as comma-separated values (CSV) in stored procedure and returns that to the calling code. What happened recently, the user complained that he could not see the new CSVs he wrote. I looked into it and found out that the stored procedure is truncating the string when it reads values from database and creates CSV string. The string is of type nvarchar, and because its exceeding the max characters of 4000 limit, the values gets truncated. Any ideas on how to work out that problem.

Find my code underneath.

```<code>BEGIN
BEGIN
    Declare @Synonyms Table
    (
        RowID int Identity(1,1),
        SynonymID int,
        [Synonym] nvarchar(4000)
    );

    SET NOCOUNT ON;

    Insert @Synonyms(SynonymID, [Synonym])
    Select distinct SynonymID, [Synonym] From RF_SearchSynonyms with(nolock) Where SearchTermID = @SearchTermID And ActiveInd = 1

    If((Select COUNT(RowID) From @Synonyms) <> 0)
    BEGIN
        Declare @CurrentRow int = (Select MIN(RowID) From @Synonyms),
                @TotalRows int = (Select MAX(RowID) From @Synonyms),
                @Synonyms_CSV nvarchar(4000) = '';

        WHILE @CurrentRow <= @TotalRows
        BEGIN
            Declare @TempSyn nvarchar(500);
            Select @TempSyn = [Synonym] + ',' From @Synonyms Where RowID = @CurrentRow;
            Set @Synonyms_CSV = @Synonyms_CSV + LTRIM(RTRIM(LOWER(@TempSyn)));

            SET @CurrentRow = @CurrentRow + 1
        END
    END
    Else
    BEGIN
        Set @Synonyms_CSV = '';
    END
END

BEGIN
    Declare @SKUs Table
    (
        RowID int Identity(1,1),
        SkuID int,
        SKU nvarchar(15)
    );

    SET NOCOUNT ON;

    Insert @SKUs(SkuID, SKU)
    Select distinct SkuID, SKU From RF_SearchSkus with(nolock) Where SearchTermID = @SearchTermID And ActiveInd = 1

    If((Select COUNT(RowID) From @SKUs) <> 0)
    BEGIN
        Declare @CurrentRow1 int = (Select MIN(RowID) From @SKUs),
                @TotalRows1 int = (Select MAX(RowID) From @SKUs),
                @Skus_CSV nvarchar(4000) = '';

        WHILE @CurrentRow1 <= @TotalRows1
        BEGIN
            Declare @TempSku nvarchar(15);
            Select @TempSku = SKU + ',' From @SKUs Where RowID = @CurrentRow1;
            Set @Skus_CSV = @Skus_CSV + LTRIM(RTRIM(@TempSku));

            SET @CurrentRow1 = @CurrentRow1 + 1
        END
    END
    Else
    BEGIN
        Set @Skus_CSV = '';
    END
END

BEGIN
    Declare @Combined varchar(8000),
            @syn_len int = 0,
            @sku_len int = 0;

    Select @syn_len = LEN(@Synonyms_CSV);
    Select @sku_len = LEN(@Skus_CSV);
    Select @Combined = @Synonyms_CSV + '-_-' + @Skus_CSV;

    Select @Synonyms_CSV + '-_-' + @Skus_CSV;
END
</code>```

END

I can't use text and ntext as they do not play nice with concatenation operations.

Thanks.

答:
How are your declaring the string parameter?

```<code>nvarchar(max)
</code>```

supports up to 2^32-1 (2GB)

See this link.

Body:
We have an stored procedure that we created so that user can write comma separated search tags in their software product's admin. So he can add comma-separated tags and in case if he wants to edit them, we read from the table all the tags, recreate them as comma-separated values (CSV) in stored procedure and returns that to the calling code. What happened recently, the user complained that he could not see the new CSVs he wrote. I looked into it and found out that the stored procedure is truncating the string when it reads values from database and creates CSV string. The string is of type nvarchar, and because its exceeding the max characters of 4000 limit, the values gets truncated. Any ideas on how to work out that problem.

Find my code underneath.

BEGIN
BEGIN
    Declare @Synonyms Table
    (
        RowID int Identity(1,1),
        SynonymID int,
        [Synonym] nvarchar(4000)
    );

    SET NOCOUNT ON;

    Insert @Synonyms(SynonymID, [Synonym])
    Select distinct SynonymID, [Synonym] From RF_SearchSynonyms with(nolock) Where SearchTermID = @SearchTermID And ActiveInd = 1

    If((Select COUNT(RowID) From @Synonyms) <> 0)
    BEGIN
        Declare @CurrentRow int = (Select MIN(RowID) From @Synonyms),
                @TotalRows int = (Select MAX(RowID) From @Synonyms),
                @Synonyms_CSV nvarchar(4000) = '';

        WHILE @CurrentRow <= @TotalRows
        BEGIN
            Declare @TempSyn nvarchar(500);
            Select @TempSyn = [Synonym] + ',' From @Synonyms Where RowID = @CurrentRow;
            Set @Synonyms_CSV = @Synonyms_CSV + LTRIM(RTRIM(LOWER(@TempSyn)));

            SET @CurrentRow = @CurrentRow + 1
        END
    END
    Else
    BEGIN
        Set @Synonyms_CSV = '';
    END
END

BEGIN
    Declare @SKUs Table
    (
        RowID int Identity(1,1),
        SkuID int,
        SKU nvarchar(15)
    );

    SET NOCOUNT ON;

    Insert @SKUs(SkuID, SKU)
    Select distinct SkuID, SKU From RF_SearchSkus with(nolock) Where SearchTermID = @SearchTermID And ActiveInd = 1

    If((Select COUNT(RowID) From @SKUs) <> 0)
    BEGIN
        Declare @CurrentRow1 int = (Select MIN(RowID) From @SKUs),
                @TotalRows1 int = (Select MAX(RowID) From @SKUs),
                @Skus_CSV nvarchar(4000) = '';

        WHILE @CurrentRow1 <= @TotalRows1
        BEGIN
            Declare @TempSku nvarchar(15);
            Select @TempSku = SKU + ',' From @SKUs Where RowID = @CurrentRow1;
            Set @Skus_CSV = @Skus_CSV + LTRIM(RTRIM(@TempSku));

            SET @CurrentRow1 = @CurrentRow1 + 1
        END
    END
    Else
    BEGIN
        Set @Skus_CSV = '';
    END
END

BEGIN
    Declare @Combined varchar(8000),
            @syn_len int = 0,
            @sku_len int = 0;

    Select @syn_len = LEN(@Synonyms_CSV);
    Select @sku_len = LEN(@Skus_CSV);
    Select @Combined = @Synonyms_CSV + '-_-' + @Skus_CSV;

    Select @Synonyms_CSV + '-_-' + @Skus_CSV;
END

END

I can't use text and ntext as they do not play nice with concatenation operations.

Thanks.

Body:
How are your declaring the string parameter?

nvarchar(max)

supports up to 2^32-1 (2GB)

See this link.


问:
SQL error while converting varchar to int by joining two tables
I need to find missing numbers in my database. I am comparing two databases, tempdb created in query with numbers 1 - 999 and MYDAT.

MYDAT looks like:

```<code>+-------+
|  id   |
+-------+
| A-001 |
| A-002 |
| A-004 |
| A-... |
| A-952 |
| A-... |
+-------+
</code>```

I am running this query:

```<code>declare @tempid int

set @tempid = 1

create table tempdb (tempid int)

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT)
where
MYDAT.ID IS NULL and
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

drop table tempdb
</code>```

Without droping temdb, select * from tempdb looks good and i am getting what i want.

The part with selecting and converting data from MYDAT works good and i am getting only integers

```<code>select CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT) fom MYDAT
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'
</code>```

I am getting an error "converting varchar to int" but i have no idea why. When i change left join to right join, i get no errors.

I also checked both databases manually and there are no strings or characters, only integers.

I also tried the CONVERT() but with same result.

Any suggestions or ideas what is the problem?

Edit:

1 - I see one mistake as i tried it on rextester. I added MYDAT.ID IS NULL to the query so i get correct results.

2 - Examples
I need this: http://rextester.com/KFG73206

But CAST or CONVERT just does not seems to work http://rextester.com/WJIAH52304

答:
Cannot clearly state the cause , may be an issue with data. You can try for some workaround to avoid casting,</p>

```<code> create table tempdb (tempid varchar(3))

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = SUBSTRING(MYDAT.ID, 3, 3)
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'
</code>```

Body:
I need to find missing numbers in my database. I am comparing two databases, tempdb created in query with numbers 1 - 999 and MYDAT.

MYDAT looks like:

+-------+
|  id   |
+-------+
| A-001 |
| A-002 |
| A-004 |
| A-... |
| A-952 |
| A-... |
+-------+

I am running this query:

declare @tempid int

set @tempid = 1

create table tempdb (tempid int)

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT)
where
MYDAT.ID IS NULL and
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

drop table tempdb

Without droping temdb, select * from tempdb looks good and i am getting what i want.

The part with selecting and converting data from MYDAT works good and i am getting only integers

select CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT) fom MYDAT
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

I am getting an error "converting varchar to int" but i have no idea why. When i change left join to right join, i get no errors.

I also checked both databases manually and there are no strings or characters, only integers.

I also tried the CONVERT() but with same result.

Any suggestions or ideas what is the problem?

Edit:

1 - I see one mistake as i tried it on rextester. I added MYDAT.ID IS NULL to the query so i get correct results.

2 - Examples
I need this: http://rextester.com/KFG73206

But CAST or CONVERT just does not seems to work http://rextester.com/WJIAH52304

Body:
Cannot clearly state the cause , may be an issue with data. You can try for some workaround to avoid casting,

 create table tempdb (tempid varchar(3))

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = SUBSTRING(MYDAT.ID, 3, 3)
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'


问:
How to achieve inheritance in javascript using OLOO pattern
I am trying to achieve inheritance of this code snippet

function parent(name) {
  this.name = name;

}

function child(childname) {
  parent.call(this, "cde");
  this.childname = childname;
}

var p1 = new parent("abc");
child.prototype = Object.create(parent.prototype);
var p2 = new child("def");

console.log(p1.name);

console.log(p2.name);```
</div>
</div>
</p>

<p>Using OLOO patternOLOO pattern</p>

<p>Here is my try for it</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function person(name) {
  this.name = name;
}

var p1 = new person("abc");

var p2;

p2 = Object.create(person);

console.log(p2.name);
p2.childname = "def";</code>```

While creating p2 object here im not sending name to it. How can send name to it while creating p2 object .

Can some one please explain is this the right approach to achieve inheritance using OLOO pattern

Thanks

答:
There are some misconceptions both in the question and answer, so I feel the need to clarify first a few things:

There is no inheritance in the patterns you are referring to in js : in the OLOO pattern but also in the "fake" Class object pattern. The reason is inheritance implies copying (you make new copies from the class everytime you call the constructor) and in both patterns or whenever you use new or Object.create() it's all about linking. In your case, what you are trying to do is to link two objects so that one works as a "fallback" for the other (through the [[prototype]] mecanism). And I repeat, this is NOT inheritance.

Also, there are no "constructors" in js, only "constructor calls" (which are made using a function + new)... From  chapter 4 of this & Object prototypes book of Kyle Simpson's You Don't Know JS series :

In the above snippet, it's tempting to think that Foo is a "constructor", because we call it with new and we observe that it "constructs" an object.

In reality, Foo is no more a "constructor" than any other function in your program. Functions themselves are not constructors. However, when you put the new keyword in front of a normal function call, that makes that function call a "constructor call". In fact, new sort of hijacks any normal function and calls it in a fashion that constructs an object, in addition to whatever else it was going to do.

Also it is not necessary to use Object.prototype in the OLOO pattern as any object is normally "falling back" on it as you can see on the copy of page 127 of Kyle Simpson's YDKJS book.

Finally, here is my answer (though it is not easy to understand what you really want to achieve...):

// a "parent" object with an "init" function
let Parent = {
    define: function (name) {
        this.name = name;
    }
};
// a child object with another "init" function
let Child = Object.create(Parent);
// different name for init() : useful to differentiate with Parent
Child.create = function (childname) {
    this.define("cde");
    this.childname = childname;

};
let p1 = Object.create(Parent);
p1.define("abc");
let p2 = Object.create(Child);
p2.create("def");
console.log(p1.name);
console.log(p2.name);```

Body:
I am trying to achieve inheritance of this code snippet

function parent(name) {
  this.name = name;

}

function child(childname) {
  parent.call(this, "cde");
  this.childname = childname;
}

var p1 = new parent("abc");
child.prototype = Object.create(parent.prototype);
var p2 = new child("def");

console.log(p1.name);

console.log(p2.name);

Using OLOO patternOLOO pattern

Here is my try for it

function person(name) {
  this.name = name;
}

var p1 = new person("abc");

var p2;

p2 = Object.create(person);

console.log(p2.name);
p2.childname = "def";

While creating p2 object here im not sending name to it. How can send name to it while creating p2 object .

Can some one please explain is this the right approach to achieve inheritance using OLOO pattern

Thanks


答: It from the IDE it shows you the actual values referred to by the property. double click on it and it will shows you the reference </p>

Title: android textsize dimen resource link changes to the value


问:
Difference between passing as int and the pointer inside class gives me segmentation fault
I am trying to implement a simple linkedlist insertion in C++. Now, my code looks like in the first attempt, the code itself is self-explanatory but I have added some obvious comment as stackoverflow is not allowing me to post the question without putting some comments:

```<code>// Simple class and struct node
struct node {
        int data;
        struct node *next;
};

class list {
     // Member functions
     private:
        // Defining struct object
        node *root;

    public:
        bool insertNode(node *root); // Insertion function
        void print_list();
};

bool list::insertNode(node *n){
    root->next = n;
    return true;
    /*
     node *temp = new node;
     temp->data = data;

    if(root == NULL){
        root->next = new node;`enter code here`
        root->next->data = data;
        root->next->next = NULL;
        cout << "Coming" << "\n";
        return true;
    } else {
        temp->next = root;
        root = temp;
        return true;
    } */

}

void list::print_list(){

    node *p = root;
    // . Iterating the list
    p = p->next;
    while(p != NULL){
        cout << p->data << "\n";
        p = p->next;
    }
}

int main(){

    class list l;
    node *n = new node;
    n->data = 5;
    n->next = NULL;
    if(!l.insertNode(n)){
        cout << "Failed" << "\n";
        return 1;
    }
    l.print_list();

    return 1;
}
</code>```

The thing is that when i try to modify my program as below, difference is that instead of having a node as argument in insert function, if I have an int as argument then it gives me segmentation fault.

==========================================================================

include

```<code>#include <string>

using namespace std;

struct node {
        int data;
        struct node *next;
};

class list {

     private:
        node *root;

    public:
        bool insertNode(int data);
        void print_list();
};

// Insertion function
bool list::insertNode(int data){

    if(root == NULL){
        root = new node;
        root->data = data;
        root->next = NULL;
        return true;
    } else {
        node *temp = new node;
        temp->data = data;
        temp->next = root;
        root = temp;
        return true;
    }

    return false;
}

// Print function
void list::print_list(){

    node *p = root;

    p = p->next;
    while(p != NULL){
        cout << p->data << "\n";
        p = p->next;
    }
}

// Main driver code
int main(){

    class list l;

    if(!l.insertNode(5)){
        cout << "Failed" << "\n";`enter code here`
        return 1;
    }
    l.print_list();

    return 1;
}

</code>```

output:./p

```<code>5
0
Segmentation fault: 11
</code>```

Which means that in insertion function I pass an integer instead of a node then why I get segmentation fault? Since root defined in the list class has never been allocated memory and in my insertion function if I detect that root is null so I simply do root = new node; whats wrong with it? On the other hand if I insert a node instead of "int" in the insertion function then I get correct output? What is the difference?

答:
For a list to work at all, it needs to be initialized properly.  You have a naked pointer, yet you do not have a contructor.  You do not have a destructor, either.</p>

```<code>class list
{
    private:
        node *root;

    public:
        List() { root = NULL; }
        ~List() { clear(); }

        void clear()
        {
            node *p = root, *q;
            while (p)
            {
               q = p->next;
               delete p;
               p = q;
            }
            root = NULL;
        }

        bool insertNode(node* p)
        {
            if (!p)
               return false;

            p->next = root;
            root = p;
            return true;
        }

        bool insertNode(int data)
        {
            node* p = new node;
            if (!p)
               return false;
            p->data = data;
            return insertNode(p);
        }
        // ...
};
</code>```

Body:
I am trying to implement a simple linkedlist insertion in C++. Now, my code looks like in the first attempt, the code itself is self-explanatory but I have added some obvious comment as stackoverflow is not allowing me to post the question without putting some comments:

// Simple class and struct node
struct node {
        int data;
        struct node *next;
};

class list {
     // Member functions
     private:
        // Defining struct object
        node *root;

    public:
        bool insertNode(node *root); // Insertion function
        void print_list();
};

bool list::insertNode(node *n){
    root->next = n;
    return true;
    /*
     node *temp = new node;
     temp->data = data;

    if(root == NULL){
        root->next = new node;`enter code here`
        root->next->data = data;
        root->next->next = NULL;
        cout << "Coming" << "\n";
        return true;
    } else {
        temp->next = root;
        root = temp;
        return true;
    } */

}

void list::print_list(){

    node *p = root;
    // . Iterating the list
    p = p->next;
    while(p != NULL){
        cout <
data << "\n";
        p = p->next;
    }
}

int main(){

    class list l;
    node *n = new node;
    n->data = 5;
    n->next = NULL;
    if(!l.insertNode(n)){
        cout << "Failed" << "\n";
        return 1;
    }
    l.print_list();

    return 1;
}

The thing is that when i try to modify my program as below, difference is that instead of having a node as argument in insert function, if I have an int as argument then it gives me segmentation fault.

==========================================================================

include

#include <string>

using namespace std;

struct node {
        int data;
        struct node *next;
};

class list {

     private:
        node *root;

    public:
        bool insertNode(int data);
        void print_list();
};

// Insertion function
bool list::insertNode(int data){

    if(root == NULL){
        root = new node;
        root->data = data;
        root->next = NULL;
        return true;
    } else {
        node *temp = new node;
        temp->data = data;
        temp->next = root;
        root = temp;
        return true;
    }

    return false;
}

// Print function
void list::print_list(){

    node *p = root;

    p = p->next;
    while(p != NULL){
        cout <
data << "\n";
        p = p->next;
    }
}

// Main driver code
int main(){

    class list l;

    if(!l.insertNode(5)){
        cout << "Failed" << "\n";`enter code here`
        return 1;
    }
    l.print_list();

    return 1;
}

output:./p

5
0
Segmentation fault: 11

Which means that in insertion function I pass an integer instead of a node then why I get segmentation fault? Since root defined in the list class has never been allocated memory and in my insertion function if I detect that root is null so I simply do root = new node; whats wrong with it? On the other hand if I insert a node instead of "int" in the insertion function then I get correct output? What is the difference?

Body:
For a list to work at all, it needs to be initialized properly.  You have a naked pointer, yet you do not have a contructor.  You do not have a destructor, either.

class list
{
    private:
        node *root;

    public:
        List() { root = NULL; }
        ~List() { clear(); }

        void clear()
        {
            node *p = root, *q;
            while (p)
            {
               q = p->next;
               delete p;
               p = q;
            }
            root = NULL;
        }

        bool insertNode(node* p)
        {
            if (!p)
               return false;

            p->next = root;
            root = p;
            return true;
        }

        bool insertNode(int data)
        {
            node* p = new node;
            if (!p)
               return false;
            p->data = data;
            return insertNode(p);
        }
        // ...
};


问:
Encrypting a string in Java and decrypting it in C++
I need to encrypt a string in Java and decrypt it in C++. I've seen C++ has a Crypto++ library and Java has JCE, Jasypt, BouncyCastle etc. but I'm getting more and more confused...

I'm searching for something simple. High security it's not required for this use case. It's important for the encryption algorithm on one side to be analogous to the one on the other side, configuring them in the simplest way.

EDIT (improved explanation):

I would like to do this:

in Java: take an input string, encrypt it with a string password (and not other things like byte arrays or initialization vectors), obtaining an encrypted string

in C++: receive the above encrypted string and decrypt it with the same string password as above, obtaining the original input string

For the Java part I know this Jasypt code:

```<code>StandardPBEStringEncryptor hexEncryptor = new StandardPBEStringEncryptor() ;
hexEncryptor.setStringOutputType("hexadecimal");
hexEncryptor.setPassword(ENCRYPTION_PASSWORD);
String encryptedString = hexEncryptor.encrypt(inputString);
</code>```

It would be great, but I don't know wich algorithm it uses and what's the analogous in C++ for decrypting it.

答:
If security is not important, just XOR it on one end with, say, 70, then XOR again on the other. This will take about 10 minutes for any cracker to figure out by hand. Or a grandma who's good at solving the cryptoquotes in the newspaper.

If you really want secure+easy and "slow" doesn't matter (processing <1x per sec on average or 10x/sec if you have the machine to yourself), do this:

implement encrypt/decrypt with a common Java library

have the C++ do a process.start to the Java decryptor

Pass something unique, say the process ID of the C# program, as a parameter to the Java program, you can share a file that includes that ID. Or if you can make the Java program run as a console program, have it read/write the console and the C# use the Process.StandardInput/StandardOutput. Or... etc. etc.

Ugly hack, yes. If you want to work fast and complete more work in your day, figure out if your customers or users are going to care.

Body:
I need to encrypt a string in Java and decrypt it in C++. I've seen C++ has a Crypto++ library and Java has JCE, Jasypt, BouncyCastle etc. but I'm getting more and more confused...

I'm searching for something simple. High security it's not required for this use case. It's important for the encryption algorithm on one side to be analogous to the one on the other side, configuring them in the simplest way.

EDIT (improved explanation):

I would like to do this:

in Java: take an input string, encrypt it with a string password (and not other things like byte arrays or initialization vectors), obtaining an encrypted string

in C++: receive the above encrypted string and decrypt it with the same string password as above, obtaining the original input string

For the Java part I know this Jasypt code:

StandardPBEStringEncryptor hexEncryptor = new StandardPBEStringEncryptor() ;
hexEncryptor.setStringOutputType("hexadecimal");
hexEncryptor.setPassword(ENCRYPTION_PASSWORD);
String encryptedString = hexEncryptor.encrypt(inputString);

It would be great, but I don't know wich algorithm it uses and what's the analogous in C++ for decrypting it.