问:
Is there a better way to add class items to entry cell in Xamarin and have a placeholder if null?
I want to have a page that has a Table View with just Entry Cells. It's an "Update Details" feature inside the app. I want to make it more user friendly as in I separate the entry cells into two parts and fill the top ones with the data that's already in the object, and what's null I put a placeholder instead.

So far I just have ifs and elses everywhere. I check every single attribute and see if it's null. If not, I put its value inside the entry cell. If it is, I add a placeholder instead.

```<code>            if (car.Make != null)
                Weknow.Add(new EntryCell {Label = "Make", Text = car.Make});
            else
                Wedont.Add(new EntryCell {Label = "Make", Placeholder = "Eg. Ford"});

            if (car.Manufacturer != null)
                Weknow.Add(new EntryCell {Label = "Manufacturer", Text = car.Manufacturer});
            else
                Wedont.Add(new EntryCell {Label = "Manufacturer", Placeholder = "Eg. Ford Werke AG"});

            if (car.Plant != null)
                Weknow.Add(new EntryCell {Label = "Plant", Text = car.Plant});
            else
                Wedont.Add(new EntryCell {Label = "Plant", Placeholder = "Eg. Koeln-Niehl"});

            if (car.ModelYear != null)
                Weknow.Add(new EntryCell {Label = "ModelYear", Text = car.ModelYear});
            else
                Wedont.Add(new EntryCell {Label = "ModelYear", Placeholder = "Eg. 2010"});

            if (car.SequentialNumber != null)
                Weknow.Add(new EntryCell {Label = "SequentialNumber", Text = car.SequentialNumber});
            else
                Wedont.Add(new EntryCell {Label = "SequentialNumber", Placeholder = ""});

            if (car.Model != null)
                Weknow.Add(new EntryCell {Label = "Model", Text = car.Model});
            else
                Wedont.Add(new EntryCell {Label = "Model", Placeholder = "Eg. Focus"});
</code>```

Weknow is the table section containing the Entry cells that have values, and Wedont is the section with the ones that are null, and have a placeholder.

The end result is this:
https://imgur.com/pr2ezQr

Everything works, but I'm wondering if there is any simpler way to go through an object and see if properties are null and if they are, then there should be a placeholder instead. I was thinking of having a Binding Context but I wanted to do all of this in code rather than XAML. But if it can be done that way, I could try.

Thanks!

答:
The way the Placeholder Property works in Xamarin Forms is to only display if the Text Property is null or empty. If Text is not null or empty, then Text will be displayed and Placeholder will not. Given this you could update your calls to something like:

```<code>Weknow.Add(new EntryCell {Label = "Make", Placeholder = "Eg. Ford", Text = car.Make});
Weknow.Add(new EntryCell {Label = "Manufacturer", Placeholder = "Eg. Ford Werke AG", Text = car.Manufacturer});
Weknow.Add(new EntryCell {Label = "Plant", Placeholder = "Eg. Koeln-Niehl", Text = car.Plant});

// Continue with other cells.
</code>```

This allows you to drop the conditional statements.

Body:
I want to have a page that has a Table View with just Entry Cells. It's an "Update Details" feature inside the app. I want to make it more user friendly as in I separate the entry cells into two parts and fill the top ones with the data that's already in the object, and what's null I put a placeholder instead.

So far I just have ifs and elses everywhere. I check every single attribute and see if it's null. If not, I put its value inside the entry cell. If it is, I add a placeholder instead.

            if (car.Make != null)
                Weknow.Add(new EntryCell {Label = "Make", Text = car.Make});
            else
                Wedont.Add(new EntryCell {Label = "Make", Placeholder = "Eg. Ford"});

            if (car.Manufacturer != null)
                Weknow.Add(new EntryCell {Label = "Manufacturer", Text = car.Manufacturer});
            else
                Wedont.Add(new EntryCell {Label = "Manufacturer", Placeholder = "Eg. Ford Werke AG"});

            if (car.Plant != null)
                Weknow.Add(new EntryCell {Label = "Plant", Text = car.Plant});
            else
                Wedont.Add(new EntryCell {Label = "Plant", Placeholder = "Eg. Koeln-Niehl"});

            if (car.ModelYear != null)
                Weknow.Add(new EntryCell {Label = "ModelYear", Text = car.ModelYear});
            else
                Wedont.Add(new EntryCell {Label = "ModelYear", Placeholder = "Eg. 2010"});

            if (car.SequentialNumber != null)
                Weknow.Add(new EntryCell {Label = "SequentialNumber", Text = car.SequentialNumber});
            else
                Wedont.Add(new EntryCell {Label = "SequentialNumber", Placeholder = ""});

            if (car.Model != null)
                Weknow.Add(new EntryCell {Label = "Model", Text = car.Model});
            else
                Wedont.Add(new EntryCell {Label = "Model", Placeholder = "Eg. Focus"});

Weknow is the table section containing the Entry cells that have values, and Wedont is the section with the ones that are null, and have a placeholder.

The end result is this:
https://imgur.com/pr2ezQr

Everything works, but I'm wondering if there is any simpler way to go through an object and see if properties are null and if they are, then there should be a placeholder instead. I was thinking of having a Binding Context but I wanted to do all of this in code rather than XAML. But if it can be done that way, I could try.

Thanks!

Body:
The way the Placeholder Property works in Xamarin Forms is to only display if the Text Property is null or empty. If Text is not null or empty, then Text will be displayed and Placeholder will not. Given this you could update your calls to something like:

Weknow.Add(new EntryCell {Label = "Make", Placeholder = "Eg. Ford", Text = car.Make});
Weknow.Add(new EntryCell {Label = "Manufacturer", Placeholder = "Eg. Ford Werke AG", Text = car.Manufacturer});
Weknow.Add(new EntryCell {Label = "Plant", Placeholder = "Eg. Koeln-Niehl", Text = car.Plant});

// Continue with other cells.

This allows you to drop the conditional statements.


来源: stackexchange

问:
Why does using *ngIf = "authService.getUser()" in my top level app component html break my login component?
I am new to Angular so please bear with my naivety. I created a login component, which I use to prevent access to router navigation links in the main app-component html until the user logs in. The login component itself is another routed page, and I wanted to instead add the login component to my mainpage, and hide the routing navigation links until the user logs in.

To hide the user navigation links in the app-component html I tried using
*ngIf="authService.getUser()".

*ngIf="authService.getUser()" hides the navigation components until the user is logged in as expected, but it unexpectedly also didn't render the entirety of the login component (the user and password fields and submit button), except the first text which simply says "LOGIN". So the user has no way to login.
this is app.component.html:

```<code>  <app-login>

  </app-login>

<div class="page-header" >
   <div class="container">

      <div *ngIf="authService.getUser()" class="navLinks">
        <a  [routerLink]="['/home']"> Home</a>
        <a [routerLink]="['/about']"> About App</a>

        <a [routerLink]="['/login']">Login</a>
        <a [routerLink]="['/protected']">Protected</a>
    </div>

  </div>
</div>

<div id="content">
  <div class="container">
   <router-outlet></router-outlet>
  </div>
</div>
</code>```

and these are my login component files

login.component.ts:

```<code>import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  message: string;

  constructor(public authService: AuthService) {
    this.message = '';
  }

  login(username: string, password: string): boolean {
    this.message = '';
    if (!this.authService.login(username, password)) {
      this.message = 'Incorrect credentials.';
      setTimeout(function() {
        this.message = '';
      }.bind(this), 2500);
    }
    return false;
  }

  logout(): boolean {
    this.authService.logout();
    return false;
  }

}
</code>```

login.component.html:

```<code><h1>Login</h1>

<div class="alert alert-danger" role="alert" *ngIf="message">
  {{ message }}
</div>

<form class="form-inline" *ngIf="!authService.getUser()">
  <div class="form-group">
    <label for="username">User: (type <em>user</em>)</label>
    <input class="form-control" name="username" #username>
  </div>

  <div class="form-group">
    <label for="password">Password: (type <em>password</em>)</label>
    <input class="form-control" type="password" name="password" #password>
  </div>

  <a class="btn btn-default" (click)="login(username.value, password.value)">
    Submit
  </a>
</form>

<div class="well" *ngIf="authService.getUser()">
  Logged in as <b>{{ authService.getUser() }}</b>
  <a href (click)="logout()">Log out</a>
</div>
</code>```

答:
I don't understand why are you using *ngIf="!authService.getUser()" inside your login component like this.

Semantically the purpose of this component is to be used when you're not logged.
So simply try to wrap your <app-login></app-login> in your app.component.html into a div wich have the *ngIf="!authService.getUser()"

Like this :

```<code><div *ngIf="!authService.getUser()">
    <app-login></app-login>
</div>
</code>```

Also I recommand you to not use directly the service method like this in the html but a flag instead for example isLogged init to false and update it when the user successfully logged.

Your ng-if will be : *ngIf="!isLogged | async"

ContentLicense: CC BY-SA 4.0

Body:
I am new to Angular so please bear with my naivety. I created a login component, which I use to prevent access to router navigation links in the main app-component html until the user logs in. The login component itself is another routed page, and I wanted to instead add the login component to my mainpage, and hide the routing navigation links until the user logs in.

To hide the user navigation links in the app-component html I tried using
*ngIf="authService.getUser()".

*ngIf="authService.getUser()" hides the navigation components until the user is logged in as expected, but it unexpectedly also didn't render the entirety of the login component (the user and password fields and submit button), except the first text which simply says "LOGIN". So the user has no way to login.
this is app.component.html:

  <app-login>

  </app-login>

         Home
         About App

        Login
        Protected

   <router-outlet></router-outlet>

and these are my login component files

login.component.ts:

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  message: string;

  constructor(public authService: AuthService) {
    this.message = '';
  }

  login(username: string, password: string): boolean {
    this.message = '';
    if (!this.authService.login(username, password)) {
      this.message = 'Incorrect credentials.';
      setTimeout(function() {
        this.message = '';
      }.bind(this), 2500);
    }
    return false;
  }

  logout(): boolean {
    this.authService.logout();
    return false;
  }

}

login.component.html:

Login

  {{ message }}

<form class="form-inline" *ngIf="!authService.getUser()">

    User: (type user)
    <input class="form-control" name="username" #username>

    Password: (type password)
    <input class="form-control" type="password" name="password" #password>

    Submit

</form>

  Logged in as {{ authService.getUser() }}
  Log out

Body:
I don't understand why are you using *ngIf="!authService.getUser()" inside your login component like this.

Semantically the purpose of this component is to be used when you're not logged.
So simply try to wrap your <app-login></app-login> in your app.component.html into a div wich have the *ngIf="!authService.getUser()"

Like this :

<div *ngIf="!authService.getUser()">
    <app-login></app-login>
</div>

Also I recommand you to not use directly the service method like this in the html but a flag instead for example isLogged init to false and update it when the user successfully logged.

Your ng-if will be : *ngIf="!isLogged | async"


问:
What is the difference between an abstract class and typescript interface?
I'm new to programming. and can't understand the difference between the abstract class and typescript interface?</p>

答:
Abstract class available at runtime and interface at compile time. For example we cannot use instanceof with interfaces.</p>

```<code>let u: any;
var IsExpressionValid = x instanceof IUser; //This will give error.
var IsExpressionValid = x instanceof User; //This will not.
</code>```

Body:
Abstract class available at runtime and interface at compile time. For example we cannot use instanceof with interfaces.

let u: any;
var IsExpressionValid = x instanceof IUser; //This will give error.
var IsExpressionValid = x instanceof User; //This will not.


问:
Make image inside div take the always the same amount of space
```<code><div id=“parent”>
    <div id = "child1">
       <img src="123"/>
   </div>
   <div id = "child2">
      <p> Some text1 </p>
      <p> Some text2 </p>
   </div>
</div>
</code>```

I have parent div with fixed height. Parent div always have 2 child containers:

1 clild - div with image

2 child - div with some data

The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1 and my #child2 with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".

How can I make my image inside #child1 take always same % of space inside #parent? (Probably, by zooming it in)

答:
Flexbox is awesome for this. I have included comments in the CSS that explain what each line does.

* {
  box-sizing: border-box;
  /* border & padding are included in calculation of width */
}

.parent {
  display: flex;
  /* flexbox layout! */
  background: papayawhip;
}

.child {
  flex: 0 0 50%;
  /* this is the layout of the child elements realtive to the flex container .parent, shorthand for flex-grow: 0; flex-shrink: 0; flex-basis: 50%; Think of flex-basis as the width you want the items to start at */
  border: 1px solid dodgerblue;
  padding: 20px;
  /* some space around the edges inside */
}

#child1 {
  display: flex;
  /* give the child1 wrapper flexbox layout as well */
  align-items: center;
  /* vertical alignment */
  justify-content: center;
  /* horizontal alignment */
}

#child1 img {
  max-width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div id="child1" class="child">
    <img src="https://picsum.photos/200/300" />
  </div>
  <div id="child2" class="child">
    <p> Some text1 </p>
    <p> Some text2 </p>
  </div>
</div></code>```

Body:
 Some text1

 Some text2

I have parent div with fixed height. Parent div always have 2 child containers:

1 clild - div with image

2 child - div with some data

The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1 and my #child2 with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".

How can I make my image inside #child1 take always same % of space inside #parent? (Probably, by zooming it in)

Body:
Flexbox is awesome for this. I have included comments in the CSS that explain what each line does.

* {
  box-sizing: border-box;
  /* border & padding are included in calculation of width */
}

.parent {
  display: flex;
  /* flexbox layout! */
  background: papayawhip;
}

.child {
  flex: 0 0 50%;
  /* this is the layout of the child elements realtive to the flex container .parent, shorthand for flex-grow: 0; flex-shrink: 0; flex-basis: 50%; Think of flex-basis as the width you want the items to start at */
  border: 1px solid dodgerblue;
  padding: 20px;
  /* some space around the edges inside */
}

#child1 {
  display: flex;
  /* give the child1 wrapper flexbox layout as well */
  align-items: center;
  /* vertical alignment */
  justify-content: center;
  /* horizontal alignment */
}

#child1 img {
  max-width: 100%;
  height: auto;
}

<div class="parent">
  <div id="child1" class="child">
    <img src="https://picsum.photos/200/300" />
  </div>
  <div id="child2" class="child">
    <p> Some text1 </p>
    <p> Some text2 </p>
  </div>
</div>


问:
tf.group_by_reducer example with list in the reducer
I have the following code which sums up values of each key. I am trying to use the list in the reducer since my actual use case is to sample values of each key. I get the error I show below? How do I achieve with a list(or tuple). I always get my data in the form of tensors and need to use tensorflow to achieve the reduction.

Raw data

```<code>ids | features
--------------
1   | 1
2   | 2.2
3   | 7
1   | 3.0
2   | 2
3   | 3
</code>```

Desired data

```<code>ids | features
--------------
1   | 4
2   | 4.2
3   | 10
</code>```

Tensorflow code

```<code>import tensorflow as tf
tf.enable_eager_execution()

# this is a toy example. My inputs are always passed as tensors.
ids = tf.constant([1, 2, 3, 1, 2, 3])
features = tf.constant([1, 2.2, 7, 3.0, 2, 3])

# Define reducer
# Reducer requires 3 functions - init_func, reduce_func, finalize_func.
# init_func - to define initial value
# reducer_func - operation to perform on values with same key
# finalize_func - value to return in the end.
def init_func(_):
    return []

def reduce_func(state, value):
    # I actually want to sample 2 values from list but for simplicity here I return sum
    return state + value['features']

def finalize_func(state):
    return np.sum(state)

reducer = tf.contrib.data.Reducer(init_func, reduce_func, finalize_func)

# Group by reducer
# Group the data by id
def key_f(row):
    return tf.to_int64(row['ids'])

t = tf.contrib.data.group_by_reducer(
        key_func = key_f,
        reducer = reducer)

ds = tf.data.Dataset.from_tensor_slices({'ids':ids, 'features' : features})
ds = ds.apply(t)
ds = ds.batch(6)

iterator = ds.make_one_shot_iterator()
data = iterator.get_next()
print(data)
</code>```

Following is the error I get

```<code>/home/lyft/venv/local/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.pyc in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, defun_kwargs)
   2122     self._function = tf_data_structured_function_wrapper
   2123     if add_to_graph:
-> 2124       self._function.add_to_graph(ops.get_default_graph())
   2125     else:
   2126       # Use the private method that will execute
AttributeError: '_OverloadedFunction' object has no attribute 'add_to_graph'
</code>```

Body:
I have the following code which sums up values of each key. I am trying to use the list in the reducer since my actual use case is to sample values of each key. I get the error I show below? How do I achieve with a list(or tuple). I always get my data in the form of tensors and need to use tensorflow to achieve the reduction.

Raw data

ids | features
--------------
1   | 1
2   | 2.2
3   | 7
1   | 3.0
2   | 2
3   | 3

Desired data

ids | features
--------------
1   | 4
2   | 4.2
3   | 10

Tensorflow code

import tensorflow as tf
tf.enable_eager_execution()

# this is a toy example. My inputs are always passed as tensors.
ids = tf.constant([1, 2, 3, 1, 2, 3])
features = tf.constant([1, 2.2, 7, 3.0, 2, 3])

# Define reducer
# Reducer requires 3 functions - init_func, reduce_func, finalize_func.
# init_func - to define initial value
# reducer_func - operation to perform on values with same key
# finalize_func - value to return in the end.
def init_func(_):
    return []

def reduce_func(state, value):
    # I actually want to sample 2 values from list but for simplicity here I return sum
    return state + value['features']

def finalize_func(state):
    return np.sum(state)

reducer = tf.contrib.data.Reducer(init_func, reduce_func, finalize_func)

# Group by reducer
# Group the data by id
def key_f(row):
    return tf.to_int64(row['ids'])

t = tf.contrib.data.group_by_reducer(
        key_func = key_f,
        reducer = reducer)

ds = tf.data.Dataset.from_tensor_slices({'ids':ids, 'features' : features})
ds = ds.apply(t)
ds = ds.batch(6)

iterator = ds.make_one_shot_iterator()
data = iterator.get_next()
print(data)

Following is the error I get

/home/lyft/venv/local/lib/python2.7/site-packages/tensorflow/python/data/ops/dataset_ops.pyc in __init__(self, func, transformation_name, dataset, input_classes, input_shapes, input_types, input_structure, add_to_graph, defun_kwargs)
   2122     self._function = tf_data_structured_function_wrapper
   2123     if add_to_graph:
-> 2124       self._function.add_to_graph(ops.get_default_graph())
   2125     else:
   2126       # Use the private method that will execute
AttributeError: '_OverloadedFunction' object has no attribute 'add_to_graph'

Body:
you can use pandas to group by in ids and get sum.

>>> df = pd.DataFrame({'ids':[1,2,3,1,2,3], 'features':[1,2.2,7,3.0,2,3]})
>>> df
   features  ids
0       1.0    1
1       2.2    2
2       7.0    3
3       3.0    1
4       2.0    2
5       3.0    3
>>> df.groupby('ids')['features'].sum()
ids
1     4.0
2     4.2
3    10.0


问:
awk ignore quoted delimiters `echo 'a "b1 b2" c'| awk '{print $2}'`
The following will output "b1 as it recognizes the quoted space as a field delimiter. How do I tell awk to ignore quoted delimiters so that this would output b1 b2 or "b1 b2"

echo 'a "b1 b2" c'| awk '{print $2}'
```

I see the following two related posts, but I'm having trouble getting the solutions to work. I was hoping to find a simple solution. Field parsing is awk's specialty, right?

awk ignore delimiter inside single quote within a parenthesis
What's the most robust way to efficiently parse CSV using awk?

答:
Shortest answer:

```<code>echo 'a "b1 b2" c'| awk -F\" '{print $2}'
</code>```

will output:  b1 b2

Body:
The following will output "b1 as it recognizes the quoted space as a field delimiter. How do I tell awk to ignore quoted delimiters so that this would output b1 b2 or "b1 b2"

echo 'a "b1 b2" c'| awk '{print $2}'

I see the following two related posts, but I'm having trouble getting the solutions to work. I was hoping to find a simple solution. Field parsing is awk's specialty, right?

awk ignore delimiter inside single quote within a parenthesis
What's the most robust way to efficiently parse CSV using awk?

Body:
Shortest answer:

echo 'a "b1 b2" c'| awk -F\" '{print $2}'

will output:  b1 b2


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
All I can say is that I have had code break when I changed the toString of my class to display some additional debug information.

The code in question was a GUI library that decided to use the value of toString as some internal thing (it was a couple of years ago... I forget what it was exactly).  The end result was that I didn't use that library anymore.

I would say that since a large group of people see toString as being used for debugging (regardless of your opinion of what it you think it should be used for) that it is problematic to make use of the value returned from it to do anything programmatic (like parse it) or display it to a user.

If you are 100% in control of the toString methods then by all means do what you want.

So, to answer the question, no toString is not only useful for debugging, you can do anything you want with it.  However, don't be surprised if toString changes in ways that make you unhappy.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: TofuBeer


问:
Is it possible to obtain a human-readable record of all transactions on a SQL Server database?
For example, a log that shows when which value was changed from what to what in which table, row and field?</p>

答:
you are free to roll your own.

perhaps build a log table, and add triggers to record relevant transactions.

ContentLicense: CC BY-SA 3.0


问:
SChannel/SSL implementation?
I can implement HTTP using "win sockets" easily , but I've been struggling to implement HTTPS using "SChannel" which is pretty much poorly documented "at least for me". How can I establish a secure connection for HTTPS communication and is there any security or performance considerations I should be aware of?</p>

答:
SChannel integrated quite well with Windows and allows you to perform authentication without asking the user's credentials. Schannel works on a lower level than HTTP. It allows you to open secure tcp connections (ssl socket). You need to implement you own HTTP stack to send HTTPS requests or find a library. To get used to Schannel the best place to start is to understand Microsoft's samples which is a client-server example:

Client

Server

They are pretty simple examples but enough to understand the basics.

Curl has been using Schannel for a while and you can find some very useful code for your exercise https://github.com/curl/curl/blob/master/lib/vtls/schannel.c.

Security is a big topic and that's the purpose of Schannel. You will inherit the security risks of the operating system. Microsoft usually patches security issues quickly. If you are targeting Windows only, it is a good choice because of the deep integration to the Windows ecosystem. For example, you don't have to deploy your own ssl certificates like you do with openssl, Schannel will read the system certs automatically. You can also implement NTLM and Kerberos authentication easily without having to ask for credentials, Schannel will get a credentials handle from the user running your software. In general, it is pretty good library and as far as I know there is no performance penalty compared to other SSL libraries. It well tested and deployed to millions of machines around the world.

Title: SChannel/SSL implementation?


问:
flask search bar using postgres
I'm doing a flask project and I want to enable a a search bar. Usually I would create a route but the search bar takes the url to ?query= and bypasses the route that I created. I tried to make a route similar to the one created by the search bar but didn't have success. I'm trying to implement this with postgresql using psycopg2.

```<code>@newsbeta.route("/newsbeta/<query>")
def get_query(query):
    cur.execute(f"SELECT * FROM test WHERE to_tsvector('english',title) @@ to_tsquery('english','{query}');")
    searchquery = []
    for i in range(10):
        searchquery.append(cur.fetchone())
        return render_template('search.html', title='News', searchquery=searchquery)
</code>```

expected code is that when I write a query in the search bar it would fetch it from the postgres database and return a render template with the information. this works when I query something in the search bar then if I go to /newsbeta/query manually.

user @roy said something that could be the answer toward other question but I don't know how to change this said patter if someone else could enlighten me please. 'You'll have to change the pattern so that it redirects to a different view i.e. def show_results():. It's also the reason you aren't able to share a url i.e. example.com/search?query='some text' by @roy

答:
```<code>@newsbeta.route("/search")
def get_query():
    query = request.args.get("search")
    cur.execute(f"SELECT * FROM test WHERE to_tsvector('english',title) @@ to_tsquery('english','{query}');")
    searchquery = []
    for i in range(10):
        searchquery.append(cur.fetchone())
    return render_template('search.html', title='News', searchquery=searchquery)

#set html
form action="/search" methods=['GET'] name= "search" id="query"
</code>```

Title: flask search bar using postgres

Body:
I'm doing a flask project and I want to enable a a search bar. Usually I would create a route but the search bar takes the url to ?query= and bypasses the route that I created. I tried to make a route similar to the one created by the search bar but didn't have success. I'm trying to implement this with postgresql using psycopg2.

@newsbeta.route("/newsbeta/<query>")
def get_query(query):
    cur.execute(f"SELECT * FROM test WHERE to_tsvector('english',title) @@ to_tsquery('english','{query}');")
    searchquery = []
    for i in range(10):
        searchquery.append(cur.fetchone())
        return render_template('search.html', title='News', searchquery=searchquery)

expected code is that when I write a query in the search bar it would fetch it from the postgres database and return a render template with the information. this works when I query something in the search bar then if I go to /newsbeta/query manually.

user @roy said something that could be the answer toward other question but I don't know how to change this said patter if someone else could enlighten me please. 'You'll have to change the pattern so that it redirects to a different view i.e. def show_results():. It's also the reason you aren't able to share a url i.e. example.com/search?query='some text' by @roy


问:
getting error "Expected false to be true"
i have function called sunset that copies the existing array sunsetColors by reference and then changes the first element to "blue". sunset should return the copy of the array.</p>

```<code>
function sunset(){
  let clone =sunsetColors;
clone.splice(0,0,"blue");
  return clone;
}
sunset()
</code>```

答:
try the following code for cloning

```<code>let clone = JSON.parse(JSON.stringify(sunsetColors));
</code>```

Here is a very good article for array cloning in Javascript.

https://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/

Body:
i have function called sunset that copies the existing array sunsetColors by reference and then changes the first element to "blue". sunset should return the copy of the array.

function sunset(){
  let clone =sunsetColors;
clone.splice(0,0,"blue");
  return clone;
}
sunset()

Body:
try the following code for cloning

let clone = JSON.parse(JSON.stringify(sunsetColors));

Here is a very good article for array cloning in Javascript.

https://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/


问:
Using AtomicInteger and CountDownLatch to generate one instance
I have a class which I want to have only one instance. However, I don't want multiple threads to call getInstance(). So I have coded it in the following way

```<code>public class SomeService implements Provider<String, Claims>{

    private SomeService(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // single instance
    private static SomeService instance = null;

    private String a;
    private static AtomicInteger initialized = new AtomicInteger();
    private static CountDownLatch latch = new CountDownLatch(1);
    private String b;
    private String c;

    public static SomeService getInstance(String a, String b, String c) {
       if ( initialized.incrementAndGet() == 1) {
           instance = new SomeService(a, b, c);
           latch.countDown();
       } else {
           try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       }
       return instance;

    }

    // Other implementation code

    }
</code>```

My intention (as well as understanding about this) is that:

When a thread calls getInstance it will atomically increment and check whehther it's desired value.

If not, it will wait for the other thread to open the latch which means initialization is in progress.

It would be helpful if someone helps me correct my mistakes. Seems to me that I can probably just do synchronized(someLockObject) {} block but I was wondering if this makes sense at all.

答:
My intention (as well as understanding about this) is that:

1) When a thread calls getInstance it will atomically increment and
  check whehther it's desired value.

Yes.

2) If not, it will wait for the other thread to open the latch which
  means initialization is in progress.

Yes.

Seems to me that I can probably just do synchronized(someLockObject) {} block

Yes, and that would be more typical.

I was wondering if this makes sense at all.

The code will work as you seem to intend, unless getInstance() is invoked enough times for initialized to wrap back around to 0.  I'd be inclined to use an AtomicBoolean and its compareAndSet() method instead, however, as that seems to model the situation better (and it poses no risk whatever of wraparound).

I would be more inclined to use synchonization, however, until and unless that proved to present an unresolvable performance issue.  It is clearer and more accessible.

But the approach seems poorly conceived overall, inasmuch as a thread that invokes getInstance() with one set of arguments may receive an instance that was initialized with a different set of parameters.  That may be a sign that instead of this variation on the Singleton pattern, you would be better off with the "just use one" pattern.  Note in particular that some people consider Singleton an antipattern.

Body:
I have a class which I want to have only one instance. However, I don't want multiple threads to call getInstance(). So I have coded it in the following way

public class SomeService implements Provider<String, Claims>{

    private SomeService(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // single instance
    private static SomeService instance = null;

    private String a;
    private static AtomicInteger initialized = new AtomicInteger();
    private static CountDownLatch latch = new CountDownLatch(1);
    private String b;
    private String c;

    public static SomeService getInstance(String a, String b, String c) {
       if ( initialized.incrementAndGet() == 1) {
           instance = new SomeService(a, b, c);
           latch.countDown();
       } else {
           try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       }
       return instance;

    }

    // Other implementation code

    }

My intention (as well as understanding about this) is that:

When a thread calls getInstance it will atomically increment and check whehther it's desired value.

If not, it will wait for the other thread to open the latch which means initialization is in progress.

It would be helpful if someone helps me correct my mistakes. Seems to me that I can probably just do synchronized(someLockObject) {} block but I was wondering if this makes sense at all.


问:
Run-time Error 5: Invalid Procedure - Changing Pivot Table Source
I'm getting the "Run-time error '5': Invalid Procedure call or argument at the line below in blue: PT1.ChangePivotCache ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTSourceRngFcst, Version:=6)

These are the values of the cells listed in the code:

```<code>    G24 = \\hguwarps03\WarrenData\Finance\MANAGEMENT_REPORTS\Reforecast 2019\P06_19-Jun Reforecast\
    G25 = fncl-analysis-data_May-29.xlsx
    G26 = L:\Finance\MANAGEMENT_REPORTS\Reforecast 2019\P06_19-Jun Reforecast\[fncl-analysis-data_May-29.xlsx]fncl-analysis-data
</code>```

```<code>Sub Update_Sources()
'
Dim wb As Workbook, wbFromFcst As Workbook, wbFromReFcst As Workbook
Dim wkshtSourceFcst As Worksheet, wkshtSourceReFcst As Worksheet
Dim fromPathFcst As String
Dim SourceNameFcst As String
Dim PTSourcePathFcst As String
Dim rng As Range
Dim StartPointFcst As Range
Dim PTSourceRngFcst As String
Dim PT1 As PivotTable

Set wb = ThisWorkbook

fromPathFcst = Sheets("CONTROLS").Range("G24")
SourceNameFcst = Sheets("CONTROLS").Range("G25")
PTSourcePathFcst = Sheets("CONTROLS").Range("G26")

Set wbFromFcst = Workbooks.Open(fromPathFcst & SourceNameFcst)
Set wkshtSourceFcst = wbFromFcst.Sheets("fncl-analysis-data")
Set StartPointFcst = wkshtSourceFcst.Range("A1")
Set rng = wkshtSourceFcst.Range(StartPointFcst,
StartPointFcst.SpecialCells(xlLastCell))
PTSourceRngFcst = PTSourcePathFcst & "!" &
rng.Address(ReferenceStyle:=xlR1C1)

Set PT1 =
ThisWorkbook.Sheets("Pivots").PivotTables("Customer_Cat_LocnType")

PT1.ChangePivotCache
ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase,
SourceData:=PTSourceRngFcst, Version:=6)
'This is where I get the error

End Sub
</code>```

答:
Try the code below to set the PivotCache and then update the Pivot-Table with the updated PivotCache

```<code>Dim PT1 As PivotTable
Dim PTCache As PivotCache '<-- define new Pivot-Cahce Object

' set the Range Address as String
PTSourceRngFcst = Rng.Address(False, False, xlA1, xlExternal)

' set the Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTSourceRngFcst)

' set The Pivot Table object
Set PT1 = ThisWorkbook.Sheets("Pivots").PivotTables("Customer_Cat_LocnType")

' refresh the Pivot Cache
PT1.ChangePivotCache PTCache
PT1.RefreshTable
</code>```

Body:
I'm getting the "Run-time error '5': Invalid Procedure call or argument at the line below in blue: PT1.ChangePivotCache ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTSourceRngFcst, Version:=6)

These are the values of the cells listed in the code:

    G24 = \\hguwarps03\WarrenData\Finance\MANAGEMENT_REPORTS\Reforecast 2019\P06_19-Jun Reforecast\
    G25 = fncl-analysis-data_May-29.xlsx
    G26 = L:\Finance\MANAGEMENT_REPORTS\Reforecast 2019\P06_19-Jun Reforecast\[fncl-analysis-data_May-29.xlsx]fncl-analysis-data

Sub Update_Sources()
'
Dim wb As Workbook, wbFromFcst As Workbook, wbFromReFcst As Workbook
Dim wkshtSourceFcst As Worksheet, wkshtSourceReFcst As Worksheet
Dim fromPathFcst As String
Dim SourceNameFcst As String
Dim PTSourcePathFcst As String
Dim rng As Range
Dim StartPointFcst As Range
Dim PTSourceRngFcst As String
Dim PT1 As PivotTable

Set wb = ThisWorkbook

fromPathFcst = Sheets("CONTROLS").Range("G24")
SourceNameFcst = Sheets("CONTROLS").Range("G25")
PTSourcePathFcst = Sheets("CONTROLS").Range("G26")

Set wbFromFcst = Workbooks.Open(fromPathFcst & SourceNameFcst)
Set wkshtSourceFcst = wbFromFcst.Sheets("fncl-analysis-data")
Set StartPointFcst = wkshtSourceFcst.Range("A1")
Set rng = wkshtSourceFcst.Range(StartPointFcst,
StartPointFcst.SpecialCells(xlLastCell))
PTSourceRngFcst = PTSourcePathFcst & "!" &
rng.Address(ReferenceStyle:=xlR1C1)

Set PT1 =
ThisWorkbook.Sheets("Pivots").PivotTables("Customer_Cat_LocnType")

PT1.ChangePivotCache
ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase,
SourceData:=PTSourceRngFcst, Version:=6)
'This is where I get the error

End Sub

Body:
Try the code below to set the PivotCache and then update the Pivot-Table with the updated PivotCache

Dim PT1 As PivotTable
Dim PTCache As PivotCache '<-- define new Pivot-Cahce Object

' set the Range Address as String
PTSourceRngFcst = Rng.Address(False, False, xlA1, xlExternal)

' set the Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTSourceRngFcst)

' set The Pivot Table object
Set PT1 = ThisWorkbook.Sheets("Pivots").PivotTables("Customer_Cat_LocnType")

' refresh the Pivot Cache
PT1.ChangePivotCache PTCache
PT1.RefreshTable


问:
Can Hash be sorted by keys or values?
Is it possible to sort Hash by key or by value in following code: </p>

```<code>myhash.each_key do |key|
   print myhash[key], "\t:\t", key, "\n"
end
</code>```

答:
Sorting by keys:

```<code>myhash = {5 => "five", 3 => "three", 2 => "two", 4 => "four", 1 => "one"}

myhash.keys.sort.each do |key|
  print myhash[key], "\t:\t", key, "\n"
end
</code>```

produces

```<code>one     :   1
two     :   2
three   :   3
four    :   4
five    :   5
</code>```

Sorting by value is a bit more effort:

```<code>myhash.to_a.sort { |item1, item2| item1[1] <=> item2[1] }.each do |item|
  puts item.join("\t:\t")
end
</code>```

produces

```<code>5   :   five
4   :   four
1   :   one
3   :   three
2   :   two
</code>```

If you want the outcomes in value:key order, change

```<code>puts item.join("\t:\t")
</code>```

to

```<code>puts item.reverse.join("\t:\t")
</code>```

Title: Can Hash be sorted by keys or values?

Body:
Is it possible to sort Hash by key or by value in following code:

myhash.each_key do |key|
   print myhash[key], "\t:\t", key, "\n"
end

Body:
Sorting by keys:

myhash = {5 => "five", 3 => "three", 2 => "two", 4 => "four", 1 => "one"}

myhash.keys.sort.each do |key|
  print myhash[key], "\t:\t", key, "\n"
end

produces

one     :   1
two     :   2
three   :   3
four    :   4
five    :   5

Sorting by value is a bit more effort:

myhash.to_a.sort { |item1, item2| item1[1] <=> item2[1] }.each do |item|
  puts item.join("\t:\t")
end

produces

5   :   five
4   :   four
1   :   one
3   :   three
2   :   two

If you want the outcomes in value:key order, change

puts item.join("\t:\t")

to

puts item.reverse.join("\t:\t")


问:
How can I display buttons side-by-side in Flutter?
I would like to display both of my buttons next to each other horizontally. So far I can only display them from top to bottom.

With the following code, what would I have to change ?

```<code>new Container(
    child: new Column(

      children: <Widget>[

      new RaisedButton(
        child: new Text("LogIn"),
        color:  Colors.blueAccent[600],
        onPressed: null,
        ),

      new RaisedButton(
        child: new Text("SignUp"),
        color:  Colors.blueAccent[600],
        onPressed: null,
        ),

      ],
    ),
  ),
</code>```

答:
```<code>Wrap(
            children: <Widget>[
              RaisedButton(
                ...
              ),
              RaisedButton(
                ...
              ),
              RaisedButton(
                ...
              ),
            ],
          ),
</code>```

Body:
I would like to display both of my buttons next to each other horizontally. So far I can only display them from top to bottom.

With the following code, what would I have to change ?

new Container(
    child: new Column(

      children: <Widget>[

      new RaisedButton(
        child: new Text("LogIn"),
        color:  Colors.blueAccent[600],
        onPressed: null,
        ),

      new RaisedButton(
        child: new Text("SignUp"),
        color:  Colors.blueAccent[600],
        onPressed: null,
        ),

      ],
    ),
  ),


问:
A-Frame AR.js app isn't recognizing my marker pattern, and also a black overlay upon loading the page
Here is the link: https://sixteendollars.github.io/

As you can see, upon clicking the link, there's a weird black overlay on the page.

In addition, upon pointing the camera at my marker image (https://i.imgur.com/pwGnKIu.png), it's not recognizing the marker and popping up the A-Frame entity like expected. I'm not sure if this is a problem with the marker, the model, the way I'm accessing the assets pipeline, or what.

The HTML:

```<code><!DOCTYPE html>
<html>

<script src="https://aframe.io/releases/0.9.0/aframe.min.js"></script>
<script src="https://cdn.rawgit.com/jeromeetienne/AR.js/1.6.2/aframe/build/aframe-ar.js"></script>

<body style="margin : 0px; overflow: hidden;">

<a-scene embedded arjs="sourceType: webcam; debugUIEnabled: false;">

    <a-marker type="pattern" url="assets/pattern-marker.patt">
        <a-entity
        obj-model= "obj: url(assets/Batman.obj);
        mtl: url(assets/Batman.mtl)">></a-entity>
     </a-marker>
     <a-camera-static/>

</a-scene>

</body>

</html>
</code>```

The directory structure:

```<code>assets
    pattern-marker.patt
    Batman.obj
    Batman.mtl
index.html
</code>```

答:
I threw your code into this codepen, and it's working properly. A couple of issues though.

1) Always make sure how the scene behaves without ar.js

The model is huge (you need to scale it down like a hundred times), and the 'mtl's are not working properly. You can see it in this fiddle.

You can either scale it down with blender / maya, or with the scale component:

```<code><a-entity scale='0.1 0.1 0.1'></a-entity>
</code>```

2) The 'overlay' is actually your model.  should be used as a point of view for the scene. If you want to place AR stuff on the marker, use :

```<code> <a-marker type="pattern" url="assets/pattern-marker.patt">
    <a-entity all-my-models></a-entity>
 </a-marker>
 <a-camera-static/>
</code>```

With the  being the equivalent of a camera (source)

When the marker dissapears, the  makes sure, that the rendered models stay on the screen. So you see an initial position of the loaded model.

Pics or didn't happen

When you scale the model down, and put it inside a , you should see the models (the right one is without the mtls)

UPDATE

This is quite question specific, so i'm placing it separately.

1) MTL's. These console errors show, that you didn't upload some necessary files

2) Github pages. It takes a while to load on my laptop but its clearly there. Tried on firefox / chrome on windows.

Body:
Here is the link: https://sixteendollars.github.io/

As you can see, upon clicking the link, there's a weird black overlay on the page.

In addition, upon pointing the camera at my marker image (https://i.imgur.com/pwGnKIu.png), it's not recognizing the marker and popping up the A-Frame entity like expected. I'm not sure if this is a problem with the marker, the model, the way I'm accessing the assets pipeline, or what.

The HTML:

<!DOCTYPE html>

        >

The directory structure:

assets
    pattern-marker.patt
    Batman.obj
    Batman.mtl
index.html

Body:
I threw your code into this codepen, and it's working properly. A couple of issues though.

1) Always make sure how the scene behaves without ar.js

The model is huge (you need to scale it down like a hundred times), and the 'mtl's are not working properly. You can see it in this fiddle.

You can either scale it down with blender / maya, or with the scale component:

<a-entity scale='0.1 0.1 0.1'></a-entity>

2) The 'overlay' is actually your model. <a-marker-camera> should be used as a point of view for the scene. If you want to place AR stuff on the marker, use <a-marker>:

 <a-marker type="pattern" url="assets/pattern-marker.patt">
    <a-entity all-my-models></a-entity>
 </a-marker>
 <a-camera-static/>

With the <a-camera-static> being the equivalent of a camera (source)

When the marker dissapears, the <a-marker-camera> makes sure, that the rendered models stay on the screen. So you see an initial position of the loaded model.

Pics or didn't happen

When you scale the model down, and put it inside a <a-marker>, you should see the models (the right one is without the mtls)

UPDATE

This is quite question specific, so i'm placing it separately.

1) MTL's. These console errors show, that you didn't upload some necessary files

2) Github pages. It takes a while to load on my laptop but its clearly there. Tried on firefox / chrome on windows.


问:
Cannot grab text in the above div
In the snippet below, I'd like to get Text to grab whenever Edit button is clicked:

```<code><div class="row">
    <div class="col-xs-12">
      <div class="pbody">
        <p>Text to grab</p>
      </div>
    </div>
  </div>
  <br>
  <div class="row treply">
    <div class="col-xs-1">
      <p>Hi there</p>
    </div>
    <div class="col-xs-1">
      <a class="quote btn" href="#">reply</a>
    </div>

    <div class="col-xs-1">
      <a class="edit btn" href="#">Edit</a>
    </div>
  </div>
</code>```

There are several divs with pbody class, but I'd like to get the immediate one above the clicked Edit Button.

I have tried many jQuery tricks like:

```<code>$(document).ready(function () {
  $(".edit").click(function () {
    let postText = $(this).closest(".pbody").children("p").text();
     console.log("postText is:", postText);
  });
});
</code>```

but none work. So appreciate your help.

答:
You aren't traversing the DOM according to your HTML. Try this instead:

$(document).ready(function() {
  $(".edit").click(function() {
    let postText = $(this).closest(".row.treply").prev('br').prev('.row').find('div.pbody > p').text();
    console.log("postText is:", postText);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="col-xs-12">
    <div class="pbody">
      <p>Text to grab</p>
    </div>
  </div>
</div>
<br>
<div class="row treply">
  <div class="col-xs-1">
    <p>Hi there</p>
  </div>
  <div class="col-xs-1">
    reply
  </div>

  <div class="col-xs-1">
    Edit
  </div>
</div></code>```

Refs:

.closest()

.prev()

.find()

Title: Cannot grab text in the above div

Body:
In the snippet below, I'd like to get Text to grab whenever Edit button is clicked:

Text to grab

Hi there

      reply

      Edit

There are several divs with pbody class, but I'd like to get the immediate one above the clicked Edit Button.

I have tried many jQuery tricks like:

$(document).ready(function () {
  $(".edit").click(function () {
    let postText = $(this).closest(".pbody").children("p").text();
     console.log("postText is:", postText);
  });
});

but none work. So appreciate your help.

Body:
You aren't traversing the DOM according to your HTML. Try this instead:

$(document).ready(function() {
  $(".edit").click(function() {
    let postText = $(this).closest(".row.treply").prev('br').prev('.row').find('div.pbody > p').text();
    console.log("postText is:", postText);
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="col-xs-12">
    <div class="pbody">
      <p>Text to grab</p>
    </div>
  </div>
</div>
<br>
<div class="row treply">
  <div class="col-xs-1">
    <p>Hi there</p>
  </div>
  <div class="col-xs-1">
    <a class="quote btn" href="#">reply</a>
  </div>

  <div class="col-xs-1">
    <a class="edit btn" href="#">Edit</a>
  </div>
</div>

Refs:

.closest()

.prev()

.find()


问:
Hazelcast User Code Deployment with dynamically generated classes
I have an application that consists of a grid of hazelcast nodes which uses extensive runtime bytecode generation (asm). Specifically I am dynamically building predicate<> Java functions from user entered filter expressions. I would like to store the predicates in a map so that they are available across the cluster without  having to be recompiled. Predicates are not the only instance of this. I also have ORM style mapping classes that are generated at runtime which need to be shared across the cluster.  These classes are loaded by a custom classloader called DynamiClassLoader.

At first I was unable to store my custom generated classes in Hazelcast IMaps, getting a ClassNotFoundexception. However, I found if tell Hazelcast to use my custom DynamicClassLoader using Config.setClassLoader() then it is able to find my dynamic classes and use them in the local member so I have no issues serializing and deserializing instances of my custom classes in IMaps in the same member.

However, I am still unable to deserialize instances of my predicates which were inserted into the map by a different member. I have enabled UserCodeDeployment and stepped through the code in my debugger to confirm that if it cannot find the class locally then it is hitting UserCodeDeploymentClassLoader.java and on the classNotFoundException it is proceeding to check other members for the classes but it is unable to find them. I haven't been able to discover how exactly this works. it seems to look in an internal map for which member any given class can be found on and it does not find my classes in there. I believe it dispatches an operation to other members then to look for the class, but in this case it looks like my custom classloader isn't used so it's not able to find my custom classes.

How can I make dynamically generated classes work with UserCodeDeployment on Hazelcast? Is there a way I can 'register' my dynamic classes with the member's code service or something like that?

Thankyou,
Troy.

答:
I've finally figured this out after extensive debugging.  It turns out that the operation in Hazelcast on the target member to find a class calls loadBytecodeFromParent() in ClassDataProvider.java. This looks for a .class file using getResourceAsStream on the classloader:

```<code>String resource = className.replace('.', '/').concat(".class");

...

is = parent.getResourceAsStream(resource);
</code>```

Which basically looks for the class file on the filesystem. Since my dynamic classes are entirely in memory there is no .class file resource for it to find.

I resolved this, by putting a hashmap in my DynamicClassLoader to keep the generated bytecode in and overriding getResourceAsStream to return that bytecode when it's available before looking further. Now it works!

Body:
I've finally figured this out after extensive debugging.  It turns out that the operation in Hazelcast on the target member to find a class calls loadBytecodeFromParent() in ClassDataProvider.java. This looks for a .class file using getResourceAsStream on the classloader:

String resource = className.replace('.', '/').concat(".class");

...

is = parent.getResourceAsStream(resource);

Which basically looks for the class file on the filesystem. Since my dynamic classes are entirely in memory there is no .class file resource for it to find.

I resolved this, by putting a hashmap in my DynamicClassLoader to keep the generated bytecode in and overriding getResourceAsStream to return that bytecode when it's available before looking further. Now it works!


问:
ImproperlyConfiguredError about app_name when using namespace in include()
I am currently trying out Django. I use the namespace argument in one of my include()s in urls.py. When I run the server and try to browse,
I get this error.

```<code>File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include
    'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
</code>```

These are my urls.py files:

```<code>#project/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^reviews/', include('reviews.urls', namespace='reviews')),
    url(r'^admin/', include(admin.site.urls)),
]
</code>```

and

```<code>#app/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /
    url(r'^$', views.review_list, name='review_list'),
    # ex: /review/5/
    url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
    # ex: /wine/
    url(r'^wine$', views.wine_list, name='wine_list'),
    # ex: /wine/5/
    url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'),
]
</code>```

What do I pass the app_name as stated in the error message?

答:
I am also face the same error in Django 2.2 and i solve it this way

urls.py file

```<code>urlpatterns = [
   path('publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]
</code>```

polls/urls.py file

```<code>app_name = 'polls'
urlpatterns = [
  path('', views.IndexView.as_view(), name='index')
]
</code>```

example use of namespace in calss based view method

```<code>def get_absolute_url(self):
    from django.urls import reverse
    return reverse('polls.index', args=[str(self.id)])
</code>```

example use of namespace in templates

```<code>{% url 'polls:index' %}
</code>```

Here polls:index mean app_name[define in polls/urls.py file]:name[define in polls/urls.py file inside path function]

their official which is pretty good you can check for more info namespace_django_official_doc

Body:
I am currently trying out Django. I use the namespace argument in one of my include()s in urls.py. When I run the server and try to browse,
I get this error.

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include
    'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

These are my urls.py files:

#project/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^reviews/', include('reviews.urls', namespace='reviews')),
    url(r'^admin/', include(admin.site.urls)),
]

and

#app/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /
    url(r'^$', views.review_list, name='review_list'),
    # ex: /review/5/
    url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
    # ex: /wine/
    url(r'^wine$', views.wine_list, name='wine_list'),
    # ex: /wine/5/
    url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'),
]

What do I pass the app_name as stated in the error message?

Body:
I am also face the same error in Django 2.2 and i solve it this way

urls.py file

urlpatterns = [
   path('publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]

polls/urls.py file

app_name = 'polls'
urlpatterns = [
  path('', views.IndexView.as_view(), name='index')
]

example use of namespace in calss based view method

def get_absolute_url(self):
    from django.urls import reverse
    return reverse('polls.index', args=[str(self.id)])

example use of namespace in templates

{% url 'polls:index' %}

Here polls:index mean app_name[define in polls/urls.py file]:name[define in polls/urls.py file inside path function]

their official which is pretty good you can check for more info namespace_django_official_doc


问:
C++ how to check a condition before using initialiser list?
I am writing a piece of code that is structured this way:

```<code>//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }
</code>```

Then I am using this Field in another class like:

```<code>//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/
</code>```

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.

答:
Another way using delegating constructor:</p>

```<code>class Approx
{
private:
    Field SWAP;

private:
    explicit Approx(std::pair<const int&, const int&> p) : SWAP(p.second, p.first) {}

public:
    Approx(int size, int dim) : Approx(std::minmax(size, dim) {}

    // ...
};
</code>```

Body:
I am writing a piece of code that is structured this way:

//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }

Then I am using this Field in another class like:

//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.

Body:
Another way using delegating constructor:

class Approx
{
private:
    Field SWAP;

private:
    explicit Approx(std::pair<const int&, const int&> p) : SWAP(p.second, p.first) {}

public:
    Approx(int size, int dim) : Approx(std::minmax(size, dim) {}

    // ...
};


问:
Delphi doesn't recognize that multiple printers are present
I've run into a strange problem.

My program is developped using Delphi7. On a client's computer, who is running Windows 7 64-bit, Printer.Printers.Count returns 0 even though there are multiple printers installed.

MS Word prints without problems and returns the correct list of printers.

Apparently, it used to work before on the same computer then stopped working at one point in the past.

There have been problems with the Spooler and network printers have been installed recently.

Of course it could cause the problem but it still doens't explain why Word sees the printers and Delphi doesn't.

Any ideas?

Thanks!

Edit: Running the program with elevated privileges solved the issue. The point goes to Martijn. Thanks!

答: TPrinter.Printers use the external windows function EnumPrinters. if there is a problem should be with your host machine !! <br>You can test your application on a machine running the same OS "Windows 7 64bit" and if it run without problems then you can be sure the problem is not your Delphi code. </p>

Body:
TPrinter.Printers use the external windows function EnumPrinters. if there is a problem should be with your host machine !!
You can test your application on a machine running the same OS "Windows 7 64bit" and if it run without problems then you can be sure the problem is not your Delphi code.


问:
How can I know a certain file is a video file?
I am trying to figure out if a certain user-uploaded file is a video file.

I first tried ffprobe,

```<code># a png file

Input #0, png_pipe, from '<file>':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, rgba(pc), 920x2094 [SAR 4724:4724 DAR 460:1047], 25 tbr, 25 tbn, 25 tbc

# a text file

Input #0, tty, from '<file>':
  Duration: 00:00:00.24, bitrate: 40 kb/s
    Stream #0:0: Video: ansi, pal8, 640x400, 25 fps, 25 tbr, 25 tbn, 25 tbc

# a video file

Input #0, matroska,webm, from '<file>':
  Metadata:
    encoder         : libebml v1.3.5 + libmatroska v1.4.8
    creation_time   : 2017-12-12T20:18:42.000000Z
  <redacted>
</code>```

but it's too hard to figure out what's what. Even image files and text files count as a video.

Should I compare the output matroska,webm, with every codec ffmpeg supports or is there a better way to do this?

答:
Assuming your system supports the file command, you can pass  -i, --mime option to get the mime type of the file and isolate it before processing with ffmpeg:

```<code># a video file

$ file -i movie.mp4 | cut -d ' ' -f2 | cut -d '/' -f1
--> video
</code>```

(Credit for cut command).

Body:
I am trying to figure out if a certain user-uploaded file is a video file.

I first tried ffprobe,

# a png file

Input #0, png_pipe, from '<file>':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, rgba(pc), 920x2094 [SAR 4724:4724 DAR 460:1047], 25 tbr, 25 tbn, 25 tbc

# a text file

Input #0, tty, from '<file>':
  Duration: 00:00:00.24, bitrate: 40 kb/s
    Stream #0:0: Video: ansi, pal8, 640x400, 25 fps, 25 tbr, 25 tbn, 25 tbc

# a video file

Input #0, matroska,webm, from '<file>':
  Metadata:
    encoder         : libebml v1.3.5 + libmatroska v1.4.8
    creation_time   : 2017-12-12T20:18:42.000000Z
  <redacted>

but it's too hard to figure out what's what. Even image files and text files count as a video.

Should I compare the output matroska,webm, with every codec ffmpeg supports or is there a better way to do this?

Body:
Assuming your system supports the file command, you can pass  -i, --mime option to get the mime type of the file and isolate it before processing with ffmpeg:

# a video file

$ file -i movie.mp4 | cut -d ' ' -f2 | cut -d '/' -f1
--> video

(Credit for cut command).


问:
How do I select the minimum and maximum values for a horizontal lollipop plot/dumbbell chart?
I have created a dumbbell chart but I am getting too many minimum and maximum values for each category type. I want to display only one skyblue dot (the minimum price) and one green dot (the maximum price) per area.

This is what the chart looks like so far:

My dumbbell chart

Here is my DataFrame:

The DataFrame

Here is a link to the full dataset:

https://drive.google.com/open?id=1PpI6PlO8ox2vKfM4aGmEUexCPPWa59S_

And here is my code so far:

```<code>   import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns

    db = df[['minPrice','maxPrice', 'neighbourhood_hosts']]
    ordered_db = db.sort_values(by='minPrice')
    my_range=db['neighbourhood_hosts']

    plt.figure(figsize=(8,6))
    plt.hlines(y=my_range, xmin=ordered_db['minPrice'], xmax=ordered_db['maxPrice'], color='grey', alpha=0.4)
    plt.scatter(ordered_db['minPrice'], my_range, color='skyblue', alpha=1, label='minimum price')
    plt.scatter(ordered_db['maxPrice'], my_range, color='green', alpha=0.4 , label='maximum price')
    plt.legend()

    plt.title("Comparison of the minimum and maximum prices")
    plt.xlabel('Value range')
    plt.ylabel('Area')
</code>```

How can I format my code so that I only have one minimum and one maximum value for each area?

答:
As per conversation, here is the script:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('dumbbell data.csv')
db = df[['minPrice','maxPrice', 'neighbourhood_hosts']]
#create max and min price based on area name
max_price = db.groupby(['neighbourhood_hosts'])['maxPrice'].max().reset_index()
min_price = db.groupby(['neighbourhood_hosts'])['minPrice'].min().reset_index()
var_price = pd.DataFrame()
var_price['range'] = max_price.maxPrice-min_price.minPrice
var_price['neighbourhood_hosts'] = min_price['neighbourhood_hosts']
var_price = var_price.sort_values(by='range')

#sort max and min price according to variance
max_price = max_price.reindex(var_price.index)
min_price = min_price.reindex(var_price.index)

plt.figure(figsize=(8,6))
plt.hlines(y=min_price['neighbourhood_hosts'], xmin=min_price['minPrice'], xmax=max_price['maxPrice'], color='grey', alpha=0.4)
plt.scatter(min_price['minPrice'], min_price['neighbourhood_hosts'], color='skyblue', alpha=1, label='minimum price')
plt.scatter(max_price['maxPrice'], max_price['neighbourhood_hosts'], color='green', alpha=0.4 , label='maximum price')
plt.legend()

plt.title("Comparison of the minimum and maximum prices")
plt.xlabel('Value range')
plt.ylabel('Area')
</code>```

Body:
I have created a dumbbell chart but I am getting too many minimum and maximum values for each category type. I want to display only one skyblue dot (the minimum price) and one green dot (the maximum price) per area.

This is what the chart looks like so far:

My dumbbell chart

Here is my DataFrame:

The DataFrame

Here is a link to the full dataset:

https://drive.google.com/open?id=1PpI6PlO8ox2vKfM4aGmEUexCPPWa59S_

And here is my code so far:

   import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns

    db = df[['minPrice','maxPrice', 'neighbourhood_hosts']]
    ordered_db = db.sort_values(by='minPrice')
    my_range=db['neighbourhood_hosts']

    plt.figure(figsize=(8,6))
    plt.hlines(y=my_range, xmin=ordered_db['minPrice'], xmax=ordered_db['maxPrice'], color='grey', alpha=0.4)
    plt.scatter(ordered_db['minPrice'], my_range, color='skyblue', alpha=1, label='minimum price')
    plt.scatter(ordered_db['maxPrice'], my_range, color='green', alpha=0.4 , label='maximum price')
    plt.legend()

    plt.title("Comparison of the minimum and maximum prices")
    plt.xlabel('Value range')
    plt.ylabel('Area')

How can I format my code so that I only have one minimum and one maximum value for each area?

Body:
As per conversation, here is the script:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('dumbbell data.csv')
db = df[['minPrice','maxPrice', 'neighbourhood_hosts']]
#create max and min price based on area name
max_price = db.groupby(['neighbourhood_hosts'])['maxPrice'].max().reset_index()
min_price = db.groupby(['neighbourhood_hosts'])['minPrice'].min().reset_index()
var_price = pd.DataFrame()
var_price['range'] = max_price.maxPrice-min_price.minPrice
var_price['neighbourhood_hosts'] = min_price['neighbourhood_hosts']
var_price = var_price.sort_values(by='range')

#sort max and min price according to variance
max_price = max_price.reindex(var_price.index)
min_price = min_price.reindex(var_price.index)

plt.figure(figsize=(8,6))
plt.hlines(y=min_price['neighbourhood_hosts'], xmin=min_price['minPrice'], xmax=max_price['maxPrice'], color='grey', alpha=0.4)
plt.scatter(min_price['minPrice'], min_price['neighbourhood_hosts'], color='skyblue', alpha=1, label='minimum price')
plt.scatter(max_price['maxPrice'], max_price['neighbourhood_hosts'], color='green', alpha=0.4 , label='maximum price')
plt.legend()

plt.title("Comparison of the minimum and maximum prices")
plt.xlabel('Value range')
plt.ylabel('Area')