答:
Variables in template are defined incorrectly

${$code} should be ${code}

You can use the following method instead of a for loop as explained in the plugin

$(document).ready(function() {
  var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
  ];

  var markup = '<option value="${code}">${title}</option>';

  // Compile the markup as a named template
  $.template( "optionsTemplate", markup );

  // Render the template with the options data and insert
  // the rendered HTML under the "sel" element
  $.tmpl("optionsTemplate", options ).appendTo("#sel");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<div class="col-lg-5">
    <select id="sel"></select>
</div></code>```

Title: How to use jQuery Template to select option?

Body:
I'm working with form that contain select element. I need to fill select with the data coming via json format. How to use jquery template to fill the select element?

I read about jquery template, it's documentation. But still can't get right result.

2 question: Is it good way to use jQuery Template for big data, for example: 4000 columns?

    <select id="sel"></select>

    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');

Body:
Variables in template are defined incorrectly

${$code} should be ${code}

You can use the following method instead of a for loop as explained in the plugin

$(document).ready(function() {
  var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
  ];

  var markup = '<option value="${code}">${title}</option>';

  // Compile the markup as a named template
  $.template( "optionsTemplate", markup );

  // Render the template with the options data and insert
  // the rendered HTML under the "sel" element
  $.tmpl("optionsTemplate", options ).appendTo("#sel");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<div class="col-lg-5">
    <select id="sel"></select>
</div>


来源: stackexchange

问:
What is the difference between persistent volume (PV) and persistent volume claim (PVC) in simple terms?
What is the difference between persistent volume (PV) and persistent volume claim (PVC) in Kubernetes/ Openshift by referring to documentation?

What is the difference between both in simple terms?

答:
A Persistent Volume Claim is telling you what options you have access to in a particular cluster and they got this circular at this store called Smart Tech with some ads about your configuration options, those ads are the Persistent Volume Claim.

Inside your config file you write out the different Persistent Volume Claims that you are going to have inside your cluster, kind of like your wish list to Santa, but of course you are going to go take that to the sales guy at Smart Tech when you are done.

So you write a config file that says there should a 600gb hard drive option available to all your clusters and a 1TB hard drive option as well.

When you choose one of these options of the Persistent Volume Claim you go and request that Kubernetes (the sales guy) goes and gets that option for you, the option you have chosen, Kubernetes has to look through these instances of storage options in the stock room that are readily available. These instances of hard drives can be used right away and they are considered statically provisioned because they are created ahead of time.

On the other hand, there is dynamically provisioned options that were created on the fly, when you asked Kubernetes the sales guy, so kind of like just-in-time production, it got created when you immediately asked for it.

So the Persistent Volume Claim is the stores advertisement of options and whichever one you choose Kubernetes will go get it, either one in storage or create one on the fly.

The Persistent Volume is the actual product or options that you get back from Kubernetes that you asked for. If Kubernetes does not have what you asked for it will try to create it on the fly for you.

So the PVC is what Smart Tech is advertising they have to offer to your cluster which Kubernetes the sales guy will get for you and the PV is the actual finished product delivered to you.

ContentLicense: CC BY-SA 4.0


问:
c++ file descriptor (sockets) isopen()?
In C++, is there a way to check if a file descriptor is still open, long after it was initially opened?</p>

答: You can use fcntl with the F_GETFL to get if the fd is valid or not.</p>

ContentLicense: CC BY-SA 3.0

Title: c++ file descriptor (sockets) isopen()?


问:
Mass assignment won't handle Null input even when default is set on migration.Any solution to this?
I have been using mass assignment a lot. I recently came across this issue, where I create fillable, and also defaults for null values, but on using mass assignment, if my inputs are empty, it returns a "Cannot Be Null" Error.

My Model

```<code>protected $fillable = ['name','status'];
</code>```

My Controller

```<code>$this->model->create($request->all());
</code>```

My Migration

```<code>$table->boolean('status')->default(0);
</code>```

Shouldn't the above mean that when I provide nothing on the input field status, it should default to 0? But column can't be null is thrown.

Is there any solution to this?

答:
I've run into this myself.  Take a look in your app\Http\Kernel.php file.  There is a Laravel middleware that is converting your empty inputs into null values.  So, even though you've correctly got the mass assignment set up, and the migration defaulting to 0, this middleware is changing the value before it gets to those points.  The code you are looking for is similar to:

```<code>protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, // <<-- This one
];
</code>```

You can remove it, or leave it in and write a method to compensate for all inputs.  I simply removed this and then set a mutator to do what the middleware did for those inputs I wanted to be null.

HTH

Body:
I have been using mass assignment a lot. I recently came across this issue, where I create fillable, and also defaults for null values, but on using mass assignment, if my inputs are empty, it returns a "Cannot Be Null" Error.

My Model

protected $fillable = ['name','status'];

My Controller

$this->model->create($request->all());

My Migration

$table->boolean('status')->default(0);

Shouldn't the above mean that when I provide nothing on the input field status, it should default to 0? But column can't be null is thrown.

Is there any solution to this?

Body:
I've run into this myself.  Take a look in your app\Http\Kernel.php file.  There is a Laravel middleware that is converting your empty inputs into null values.  So, even though you've correctly got the mass assignment set up, and the migration defaulting to 0, this middleware is changing the value before it gets to those points.  The code you are looking for is similar to:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, // <<-- This one
];

You can remove it, or leave it in and write a method to compensate for all inputs.  I simply removed this and then set a mutator to do what the middleware did for those inputs I wanted to be null.

HTH


问:
Keep getting "identifier expected" and "; expected" error messages
I am trying to make a high score system for my game in unity and am not really sure on how to do that, but I tried this code nonetheless and I keep receiving error messages.

I have tried to search up these errors but since I am quite new to unity and coding in general none of the solutions there make sense to me.

```<code>public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    scoreText = scoreText.int.Parse;

    if (scoreText > PlayerPrefs.GetInt("High Score", 0)) ;
    {
        PlayerPrefs.SetInt("High Score", scoreText);
        highScore.text = scoreText.ToString;
    }
</code>```

These are the error messages that show up

Assets\Score.cs(15,31): error CS1001: Identifier expected

Assets\Score.cs(15,31): error CS1002: ; expected

答:
Remove the semicolon after the If condition.

Code:

```<code>void Update()
{
scoreText.text = player.position.z.ToString("0");
// scoreText = scoreText.int.Parse;

if (scoreText > PlayerPrefs.GetInt("High Score", 0))
{
    PlayerPrefs.SetInt("High Score", scoreText);
    highScore.text = scoreText.ToString();
}
</code>```

let me know if it helps

Body:
I am trying to make a high score system for my game in unity and am not really sure on how to do that, but I tried this code nonetheless and I keep receiving error messages.

I have tried to search up these errors but since I am quite new to unity and coding in general none of the solutions there make sense to me.

public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    scoreText = scoreText.int.Parse;

    if (scoreText > PlayerPrefs.GetInt("High Score", 0)) ;
    {
        PlayerPrefs.SetInt("High Score", scoreText);
        highScore.text = scoreText.ToString;
    }

These are the error messages that show up

Assets\Score.cs(15,31): error CS1001: Identifier expected

Assets\Score.cs(15,31): error CS1002: ; expected

Body:
Remove the semicolon after the If condition.

Code:

void Update()
{
scoreText.text = player.position.z.ToString("0");
// scoreText = scoreText.int.Parse;

if (scoreText > PlayerPrefs.GetInt("High Score", 0))
{
    PlayerPrefs.SetInt("High Score", scoreText);
    highScore.text = scoreText.ToString();
}

let me know if it helps


问:
Magento - Import pending orders through excel or csv files
Is it possible to import pending  orders through an Excel or CSV file in Magento? If yes, how can I do that?

Thanks.

答:
you can do it,but it is to hard.
that use cart & checkou object to finish.
1.analyze data from xls
2.add product to cart
3.setting billing address & shipping address
4.checkout</p>


问:
This is a question about lists in python. Can we concatenate two lists
```<code> n=int(input("Enter number of rows: "))
 a=[]
 for i in range(n):
     a.append([])
     a[i].append(1)
     for j in range(1,i):
         a[i].append(a[i-1][j-1]+a[i-1][j])
     if(n!=0):
         a[i].append(1)
 for i in range(n):
     print("   "*(n-i),end=" ",sep=" ")
     for j in range(0,i+1):
         print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
     print()
</code>```

I’m trying to learn to print a pascal triangle, got struck at one line

```<code>a[i].append(a[i-1][j-1]+a[i-1][j])
</code>```

is the above line what does the line do. can anyone explain a[i-1][j-1] does?

答:
Note that a is a list of list where a[i] is the i-th row of the Pascal's triangle.

a[i][j] stores the j-th element of the i-th row of the Pascal's triangle, it is an int.

They are just using the formula of Pascal's triangle.

```<code>a[i][j] = a[i-1][j-1] + a[i-1][j]
</code>```

Body:
 n=int(input("Enter number of rows: "))
 a=[]
 for i in range(n):
     a.append([])
     a[i].append(1)
     for j in range(1,i):
         a[i].append(a[i-1][j-1]+a[i-1][j])
     if(n!=0):
         a[i].append(1)
 for i in range(n):
     print("   "*(n-i),end=" ",sep=" ")
     for j in range(0,i+1):
         print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
     print()

I’m trying to learn to print a pascal triangle, got struck at one line

a[i].append(a[i-1][j-1]+a[i-1][j])

is the above line what does the line do. can anyone explain a[i-1][j-1] does?

Body:
Note that a is a list of list where a[i] is the i-th row of the Pascal's triangle.

a[i][j] stores the j-th element of the i-th row of the Pascal's triangle, it is an int.

They are just using the formula of Pascal's triangle.

a[i][j] = a[i-1][j-1] + a[i-1][j]


问:
Flex box rendering like a column when it should be a row
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

```

I've used flex box plenty of times before, but never seen it behave like this.

答:
There is a small mistake in your code, here is the corrected one, You have given all the properties to Nav, while you need to assign these to UL,

There is no need to give flex-direction: row as this is the default property.

Padding is also working now, please check.

nav ul {
 display: flex;
        text-decoration: none;
 flex-direction: row; /* not working */
 background-color: #d2d6d6;
 padding: 0; /* not working */
}
nav li {
 display: flex;
 text-decoration: none;
 list-style: none;
 border: 2px solid #727171;
 color: #727171;
 background-color: #c4c4c4;
 padding: 4px;
 margin: 2px;
 justify-content: center;
 flex-grow: 1;
}
nav a:hover,
nav a:active {
 background-color: #aaa;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
 <ul>
  <li>Once</li>
  <li>Upon</li>
  <li>A Time</li>
  <li>There</li>
  <li>Was</li>
  <li>A Problematic</li>
  <li>Nav Bar</li>
 </ul>
</nav></code>```

Body:
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

I've used flex box plenty of times before, but never seen it behave like this.

Body:
There is a small mistake in your code, here is the corrected one, You have given all the properties to Nav, while you need to assign these to UL,

There is no need to give flex-direction: row as this is the default property.

Padding is also working now, please check.

nav ul {
 display: flex;
        text-decoration: none;
 flex-direction: row; /* not working */
 background-color: #d2d6d6;
 padding: 0; /* not working */
}
nav li {
 display: flex;
 text-decoration: none;
 list-style: none;
 border: 2px solid #727171;
 color: #727171;
 background-color: #c4c4c4;
 padding: 4px;
 margin: 2px;
 justify-content: center;
 flex-grow: 1;
}
nav a:hover,
nav a:active {
 background-color: #aaa;
}

<nav>
 <ul>
  <li><a href="#">Once</a></li>
  <li><a href="#">Upon</a></li>
  <li><a href="#">A Time</a></li>
  <li><a href="#">There</a></li>
  <li><a href="#">Was</a></li>
  <li><a href="#">A Problematic</a></li>
  <li><a href="#">Nav Bar</a></li>
 </ul>
</nav>


问:
ref doesn't have a value inside event handlers
Aimed functionality:

When a user clicks a button, a list shows. When he clicks outside the list, it closes and the button should receive focus. (following accessibility guidelines)

What I tried:

```<code>  const hideList = () => {
    // This closes the list
    setListHidden(true);
    // This takes a ref, which is forwarded to <Button/>, and focuses it
    button.current.focus();
  }

  <Button
    ref={button}
  />
</code>```

Problem:

When I examined the scope of hideList function, found that ref gets the proper reference to button every where but inside the click event handler, it's {current: null}.

The console outputs: Cannot read property 'focus' of null

Example:

https://codepen.io/moaaz_bs/pen/zQjoLK

- click on the button and then click outside and review the console.

答:
Since you are already using hooks in your App, the only change you need to make is to use useRef instead of createRef to generate a ref to the list.

```<code>const Button = React.forwardRef((props, ref) => {
  return (
    <button
      onClick={props.toggleList}
      ref={ref}
    >
      button
    </button>
  );
})

const List = (props) => {
  const list = React.useRef();

  handleClick = (e) => {
    const clickIsOutsideList = !list.current.contains(e.target);
    console.log(list, clickIsOutsideList);
    if (clickIsOutsideList) {
      props.hideList();
    }
  }

  React.useEffect(function addClickHandler() {
    document.addEventListener('click', handleClick);
  }, []);

  return (
    <ul ref={list}>
      <li>item</li>
      <li>item</li>
      <li>item</li>
    </ul>
  );
}

const App = () => {
  const [ListHidden, setListHidden] = React.useState(true);

  const button = React.useRef();

  const toggleList = () => {
    setListHidden(!ListHidden);
  }

  const hideList = () => {
    setListHidden(true);
    button.current.focus();
  }

  return (
    <div className="App">
      <Button
        toggleList={toggleList}
        ref={button}
      />
      {
        !ListHidden &&
        <List hideList={hideList} />
      }
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

Working demo

The reason that you need it is because on every render of your Functional component, a new ref will be generated if you make use of React.createRef whereas useRef is implemented such that it generates a ref when its called the first time and returns the same reference anytime in future re-renders.

P.S. A a thumb rule, you can say that useRef should be used when you
  want to have refs within functional components whereas createRef
  should be used within class components.

Body:
Aimed functionality:

When a user clicks a button, a list shows. When he clicks outside the list, it closes and the button should receive focus. (following accessibility guidelines)

What I tried:

  const hideList = () => {
    // This closes the list
    setListHidden(true);
    // This takes a ref, which is forwarded to <Button/>, and focuses it
    button.current.focus();
  }

  <Button
    ref={button}
  />

Problem:

When I examined the scope of hideList function, found that ref gets the proper reference to button every where but inside the click event handler, it's {current: null}.

The console outputs: Cannot read property 'focus' of null

Example:

https://codepen.io/moaaz_bs/pen/zQjoLK

- click on the button and then click outside and review the console.

Body:
Since you are already using hooks in your App, the only change you need to make is to use useRef instead of createRef to generate a ref to the list.

const Button = React.forwardRef((props, ref) => {
  return (
    <button
      onClick={props.toggleList}
      ref={ref}
    >
      button
    </button>
  );
})

const List = (props) => {
  const list = React.useRef();

  handleClick = (e) => {
    const clickIsOutsideList = !list.current.contains(e.target);
    console.log(list, clickIsOutsideList);
    if (clickIsOutsideList) {
      props.hideList();
    }
  }

  React.useEffect(function addClickHandler() {
    document.addEventListener('click', handleClick);
  }, []);

  return (
    <ul ref={list}>
      <li>item</li>
      <li>item</li>
      <li>item</li>
    </ul>
  );
}

const App = () => {
  const [ListHidden, setListHidden] = React.useState(true);

  const button = React.useRef();

  const toggleList = () => {
    setListHidden(!ListHidden);
  }

  const hideList = () => {
    setListHidden(true);
    button.current.focus();
  }

  return (
    <div className="App">
      <Button
        toggleList={toggleList}
        ref={button}
      />
      {
        !ListHidden &&
        <List hideList={hideList} />
      }
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));

Working demo

The reason that you need it is because on every render of your Functional component, a new ref will be generated if you make use of React.createRef whereas useRef is implemented such that it generates a ref when its called the first time and returns the same reference anytime in future re-renders.

P.S. A a thumb rule, you can say that useRef should be used when you
  want to have refs within functional components whereas createRef
  should be used within class components.


答:
I guess you have the problem because of ConvertEmptyStringsToNull middleware which was added to laravel >= 5.4. This middleware convert all empty strings to null. So if You don't set any value to status field it will be null. Your migration isn't ->nullable() so there is thrown error Cannot Be Null.

You can resolve it like this:

```<code>$all = $request->all();

if(is_null($request->get('status')))
{
     unset($all['status']);
}

$this->model->create($all);
</code>```

Title: Mass assignment won't handle Null input even when default is set on migration.Any solution to this?

Body:
I guess you have the problem because of ConvertEmptyStringsToNull middleware which was added to laravel >= 5.4. This middleware convert all empty strings to null. So if You don't set any value to status field it will be null. Your migration isn't ->nullable() so there is thrown error Cannot Be Null.

You can resolve it like this:

$all = $request->all();

if(is_null($request->get('status')))
{
     unset($all['status']);
}

$this->model->create($all);


问:
How to make an activity background completely transparent (not translucent)?
In my android activity, I need to make the background of the activity transparent. For that, I found solutions online saying to do this in theme.

```<code><item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</code>```

However this makes the activity background translucent i.e it isn't perfectly transparent, it is slightly grey. Is there a way to get a perfectly transparent background such that the screen below it is perfectly viisible. Thanks!

答:
Try this</p>

```<code>    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@color/transparent</item>
</code>```

Body:
In my android activity, I need to make the background of the activity transparent. For that, I found solutions online saying to do this in theme.

<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>

However this makes the activity background translucent i.e it isn't perfectly transparent, it is slightly grey. Is there a way to get a perfectly transparent background such that the screen below it is perfectly viisible. Thanks!

Body:
Try this

    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@color/transparent</item>


问:
Objective-C and then what? Android, Windows 7, Blackberry
Question: what should one focus on when there is a strong need to develop Apps for multiple platforms? I spend all this time focusing on Obj-C, but that get's me no where with Android, Windows 7 or Blackberry.

At it stands, Objective-C isn't even the language that the iPhone ends up using. Obj-C is compiled for the iPhone. So there must be a way to write the Apps in a more global language and then have it compiled for the iPhone, Android and Blackberry...

Recommendations?

答: Focus on flexibility. There is no "holy grail" language that is perfect for everything, so having the ability to adapt and learn as needed is important.</p>


问:
Understanding .tsconfig file
Being a beginner, I am unable to comprehend the significance of some terms, despite going through documentation.

In my .tsconfig file I have

emitDecoratorMetadata

sourceMap

esModuleInterop ->    Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
Can someone please make the above definition as humanly comprehensible as possible? Does this mean we can just import and not export?

For example, the definition for emitDecoratorMetadata in one of the answers says

emit or not design-type metadata for decorated declarations in source

What does decorated declarations in source mean? Also, if someone could explain sourceMap in slightly more human terms, that would be so helpful.

Update: @Antonis Wrote an amazing answer still the last part looks vague. I created a separate post here:

Understanding esModuleInterop in tsconfig file
Resources I went through:

https://www.typescriptlang.org/docs/handbook/compiler-options.html

https://basarat.gitbooks.io/typescript/docs/project/tsconfig.html

what is the purpose of tsconfig.json?

答:
The offical docs might help understand the .tsconfig file in its entirety.

The presence of a tsconfig.json file in a directory indicates that the
  directory is the root of a TypeScript project. The tsconfig.json file
  specifies the root files and the compiler options required to compile
  the project.

More information here: tsconfig.json

Title: Understanding .tsconfig file


问:
How to find pairs in the below given table
Find all pairs of frequent words that occur in the same document id and report the number of documents the pair occurs in. Report the pairs in decreasing order of frequency.

Note there should not be any replicated entries like
o (truck, boat) (truck, boat)

Note you should not have the same pair occurring twice in opposite order. Only one
of the following should occur:
o (truck, boat) (boat, truck)

```<code>+-------+-----+-----+---------+
|vocabId|docId|count|     word|
+-------+-----+-----+---------+
|      1|    1| 1000|    plane|
|      1|    3|  100|    plane|
|      3|    1| 1200|motorbike|
|      3|    2|  702|motorbike|
|      3|    3|  600|motorbike|
|      5|    3| 2000|     boat|
|      5|    2|  200|     boat|
+-------+-----+-----+---------+
</code>```

I have used this query but it is giving me the wrong result

```<code>select r1.word,r2.word, count(*)
from result_T r1
JOIN result_T r2 ON r1.docId = r2.docId
and r1.word = r2.word group by r1.word, r2.word
</code>```

Expected Ouput:

```<code>boat, motorbike, 2
motorbike, plane, 2
boat, plane, 1
</code>```

答:
You were on the right track with a self-join, but the join logic needs to change a bit.  The join condition should be that the first word is lexicographically less than the second word.  This ensures that pairs will not be double-counted.  Also, the document IDs have to match (you were already checking for this).

```<code>SELECT
    r1.word,
    r2.word,
    COUNT(*) AS cnt
FROM result_T r1
INNER JOIN result_T r2
    ON r1.word < r2.word AND
       r1.docId = r2.docId
GROUP BY
    r1.word,
    r2.word
ORDER BY
    COUNT(*) DESC;
</code>```

Demo

Body:
Find all pairs of frequent words that occur in the same document id and report the number of documents the pair occurs in. Report the pairs in decreasing order of frequency.

Note there should not be any replicated entries like
o (truck, boat) (truck, boat)

Note you should not have the same pair occurring twice in opposite order. Only one
of the following should occur:
o (truck, boat) (boat, truck)

+-------+-----+-----+---------+
|vocabId|docId|count|     word|
+-------+-----+-----+---------+
|      1|    1| 1000|    plane|
|      1|    3|  100|    plane|
|      3|    1| 1200|motorbike|
|      3|    2|  702|motorbike|
|      3|    3|  600|motorbike|
|      5|    3| 2000|     boat|
|      5|    2|  200|     boat|
+-------+-----+-----+---------+

I have used this query but it is giving me the wrong result

select r1.word,r2.word, count(*)
from result_T r1
JOIN result_T r2 ON r1.docId = r2.docId
and r1.word = r2.word group by r1.word, r2.word

Expected Ouput:

boat, motorbike, 2
motorbike, plane, 2
boat, plane, 1

Body:
You were on the right track with a self-join, but the join logic needs to change a bit.  The join condition should be that the first word is lexicographically less than the second word.  This ensures that pairs will not be double-counted.  Also, the document IDs have to match (you were already checking for this).

SELECT
    r1.word,
    r2.word,
    COUNT(*) AS cnt
FROM result_T r1
INNER JOIN result_T r2
    ON r1.word < r2.word AND
       r1.docId = r2.docId
GROUP BY
    r1.word,
    r2.word
ORDER BY
    COUNT(*) DESC;

Demo


问:
Sliding div inside google maps
I am looking to create an expandable div that slides in from the right on google maps. The functionality should  be similar to what the #app-viewcard-strip does here: https://www.google.com/maps/@41.5278682,-76.2402656,12z

Video for reference: https://streamable.com/afrk3

The main functionality being that the div is apart of the controls and moves the controls upwards to fit the div. I am looking to do the same functionality but move controls to the left.

I have a prototype here: https://codepen.io/ParoXsitiC/pen/EzLMZv

However I cannot get the #mySidenav to be contained within #mapPlaceholder

答:
The absolute position is calculated from the closest parent that has either position relative or position absolute.
So just add position:relative; to #mapPlaceholder.

Title: Sliding div inside google maps


问:
405 Method not Allowed/CORS origin problem when redirecting to Angular application in IdentityServer4 login
I have an Angular App as an Login UI (rendered in Backend (Asp Net Core)). When we try to login it goes to login method and validate the username/password. Our doubt is about what we should do to IndentityServer correctly redirect to redirectUrl (client to be logged) with cookies return Redirect(model.ReturnUrl);.

Login method with Redirect Uri

CORS/405 error in chrome console

It looks like some problem with routes/cors but I can't figure it out.

Edit 1:

Code in github with the problem:

https://github.com/kewinbrand/so-405-idsvr-angular

in README.md are the steps to run

答: You need to allow allowedCrosorigion inside client configuration like below.


问:
How to replace all newlines after reading a file
How can I replace a newline in a string with a ','? I have a string that is read from a file:

```<code>const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);
</code>```

It takes a string from a file:

```<code>a,b,c,d,e,f
,,,,,
g,h,i,j,k,l
</code>```

I'm able to detect the newline with this:

```<code>if (char === '\n')
</code>```

But replacing \n like this doesn't work

```<code>str = csvString.replace('/\n/g');
</code>```

I want to get the string to look like this:

```<code>a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,
</code>```

答:
You can add , at end of each line like this

$ - Matches end of line

let str = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`

let op = str.replace(/$/mg, "$&"+ ',')

console.log(op)```

Body:
How can I replace a newline in a string with a ','? I have a string that is read from a file:

const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);

It takes a string from a file:

a,b,c,d,e,f
,,,,,
g,h,i,j,k,l

I'm able to detect the newline with this:

if (char === '\n')

But replacing \n like this doesn't work

str = csvString.replace('/\n/g');

I want to get the string to look like this:

a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,


问:
What happens when a class/struct is returned WITHOUT RVO?
I understand RVO is desireable in general, but what happens when it cannot be applied? Specifically, how does the produced assembly code return a local class/struct instance to its caller?

MyClass callee() {
    MyClass a;
    /* RVO is disabled */
    return a;
}

void caller() {
    /* RVO is disabled */
    MyClass b = no_rvo();
}
```

What does the stack look like in this case? Does caller() and callee() separately allocate space for a and b on the stack, then a is copied to b? If so, does the RET statement at the end of the callee() fully decrement the stack pointer to what it was before, or is the stack memory for a freed after the copy operation?

答:
It depends on the calling convention.  But all x86 32 and 64-bit calling conventions make the same choice, and pass a pointer to the return value as a "hidden" first arg.

callee can still optimize away a (unless something else stops that from happening) and just store directly into that return-value pointer.

non-trivially-copyable types may need to run the copy-constructor at some point, and a destructor for a.

But re: your actual question, with optimization enabled the caller would pass &b as the return-value pointer.

With optimization disabled, I think I've seen some compilers create space for a separate return-value temporary and then copy from there, which is hilariously redundant for trivially-copyable types.

In theory the return-value pointer could point somewhere other than stack memory, e.g. if assigning to an element of static MyClass arr[10].

But it must not point to anything that callee could access any other way, because in the C++ abstract machine the return value is a separate object that nothing can be pointing to before the function returns.

Body:
I understand RVO is desireable in general, but what happens when it cannot be applied? Specifically, how does the produced assembly code return a local class/struct instance to its caller?

MyClass callee() {
    MyClass a;
    /* RVO is disabled */
    return a;
}

void caller() {
    /* RVO is disabled */
    MyClass b = no_rvo();
}

What does the stack look like in this case? Does caller() and callee() separately allocate space for a and b on the stack, then a is copied to b? If so, does the RET statement at the end of the callee() fully decrement the stack pointer to what it was before, or is the stack memory for a freed after the copy operation?


问:
Ajax form submit twice or once but missing last value no submit button
It may seems to be asked a few time, yet I can't find a solution.

```<code><form id="foo">
    <div class="g1">
     <input type="radio" data-next="2" name="op1[]" value="1">
     <input type="radio" data-next="2" name="op1[]" value="2">
     <input type="radio" data-next="2" name="op1[]" value="3">
    </div>
    <div class="g2">
     <input type="radio" data-next="3" name="op2[]" value="1">
     <input type="radio" data-next="3" name="op2[]" value="5">
     <input type="radio" data-next="3" name="op2[]" value="3">
    </div>
    <div class="g3">
     <input type="radio" data-send="1" name="op3[]" value="6">
     <input type="radio" data-send="1" name="op3[]" value="5">
     <input type="radio" data-send="1" name="op3[]" value="3">
    </div>
 </form>
</code>```

That is a basic of my actual code but same concept, g2 and g3 are hidden, when a user select one option from g1 it shows the next block, user selects from g2 and it shows g3...

When user select one option from the group g3 it submit the form via ajax.

The problem is that it submits the form twice the first time only send options 1 and 2, and the second time it send's the whole form.

if I use event.preventDefault(); it only submit the form once which is what I want the problem is that is not sending the value of op3

```<code>$('[data-send]').on('click', function(e) {
 e.preventDefault();
var formdata = $('form#foo').serialize();
// next is a regular ajax, post, dataType: 'json'... etc
})
</code>```

So, by using event.preventDefault(); it doesn't send my last radio value and if I don't, it submits the form twice, if I use return false;, result is the same as preventDefault();,

答:
Add some class attribute in your code as per below:

```<code><form id="foo">
    <div class="g1">
     <input class="radio_g1" type="radio" data-next="2" name="op1[]" value="1">
     <input class="radio_g1" type="radio" data-next="2" name="op1[]" value="2">
     <input class="radio_g1" type="radio" data-next="2" name="op1[]" value="3">
    </div>
    <div class="g2" style="display: none;">
     <input class="radio_g2" type="radio" data-next="3" name="op2[]" value="1">
     <input class="radio_g2" type="radio" data-next="3" name="op2[]" value="5">
     <input class="radio_g2" type="radio" data-next="3" name="op2[]" value="3">
    </div>
    <div class="g3" style="display: none;">
     <input class="radio_g3" type="radio" data-send="1" name="op3[]" value="6">
     <input class="radio_g3" type="radio" data-send="1" name="op3[]" value="5">
     <input class="radio_g3" type="radio" data-send="1" name="op3[]" value="3">
    </div>
 </form>
</code>```

In js code:

```<code>$(document).on('change', '.radio_g1', function(){
    $(document).find('.g2').show();
});

$(document).on('change', '.radio_g2', function(){
    $(document).find('.g3').show();
});

$(document).on('change', '.radio_g3', function(){
    event.preventDefault();
    var formdata = $(document).find('#foo').serializeArray();
    console.log(formdata);
});
</code>```

result like:

```<code>(3) [{…}, {…}, {…}]
0: {name: "op1[]", value: "2"}
1: {name: "op2[]", value: "3"}
2: {name: "op3[]", value: "5"}
length: 3
</code>```

Body:
It may seems to be asked a few time, yet I can't find a solution.

<form id="foo">

     <input type="radio" data-next="2" name="op1[]" value="1">
     <input type="radio" data-next="2" name="op1[]" value="2">
     <input type="radio" data-next="2" name="op1[]" value="3">

     <input type="radio" data-next="3" name="op2[]" value="1">
     <input type="radio" data-next="3" name="op2[]" value="5">
     <input type="radio" data-next="3" name="op2[]" value="3">

     <input type="radio" data-send="1" name="op3[]" value="6">
     <input type="radio" data-send="1" name="op3[]" value="5">
     <input type="radio" data-send="1" name="op3[]" value="3">

 </form>

That is a basic of my actual code but same concept, g2 and g3 are hidden, when a user select one option from g1 it shows the next block, user selects from g2 and it shows g3...

When user select one option from the group g3 it submit the form via ajax.

The problem is that it submits the form twice the first time only send options 1 and 2, and the second time it send's the whole form.

if I use event.preventDefault(); it only submit the form once which is what I want the problem is that is not sending the value of op3

$('[data-send]').on('click', function(e) {
 e.preventDefault();
var formdata = $('form#foo').serialize();
// next is a regular ajax, post, dataType: 'json'... etc
})

So, by using event.preventDefault(); it doesn't send my last radio value and if I don't, it submits the form twice, if I use return false;, result is the same as preventDefault();,

Body:
Add some class attribute in your code as per below:

<form id="foo">
    <div class="g1">
     <input class="radio_g1" type="radio" data-next="2" name="op1[]" value="1">
     <input class="radio_g1" type="radio" data-next="2" name="op1[]" value="2">
     <input class="radio_g1" type="radio" data-next="2" name="op1[]" value="3">
    </div>
    <div class="g2" style="display: none;">
     <input class="radio_g2" type="radio" data-next="3" name="op2[]" value="1">
     <input class="radio_g2" type="radio" data-next="3" name="op2[]" value="5">
     <input class="radio_g2" type="radio" data-next="3" name="op2[]" value="3">
    </div>
    <div class="g3" style="display: none;">
     <input class="radio_g3" type="radio" data-send="1" name="op3[]" value="6">
     <input class="radio_g3" type="radio" data-send="1" name="op3[]" value="5">
     <input class="radio_g3" type="radio" data-send="1" name="op3[]" value="3">
    </div>
 </form>

In js code:

$(document).on('change', '.radio_g1', function(){
    $(document).find('.g2').show();
});

$(document).on('change', '.radio_g2', function(){
    $(document).find('.g3').show();
});

$(document).on('change', '.radio_g3', function(){
    event.preventDefault();
    var formdata = $(document).find('#foo').serializeArray();
    console.log(formdata);
});

result like:

(3) [{…}, {…}, {…}]
0: {name: "op1[]", value: "2"}
1: {name: "op2[]", value: "3"}
2: {name: "op3[]", value: "5"}
length: 3


问:
cant tab what ever i want in emacs indentation mode
in javascript and html mode emacs cant make good indentation and all i want is make it better by hand but when use tab only use self indentation and not listen what i say :D

what can i do?

now

```<code><html>
    <body>
      HTTP 404 ERROR !!
    </body>
</html>
</code>```

what i want

```<code><html>
    <body>
                                  HTTP 404 ERROR !!
    </body>
</html>
</code>```

only example

答:
Some modes offer "bouncing" indentation, where TAB will toggle the indentation level between a few alternatives. An example for javascript is js2-mode. I'm not aware of a more general solution.

However, note that if TAB is getting intercepted by the major mode's keymap, you can still insert a literal TAB character using C-q TAB. That is probably all you need.

Body:
in javascript and html mode emacs cant make good indentation and all i want is make it better by hand but when use tab only use self indentation and not listen what i say :D

what can i do?

now

      HTTP 404 ERROR !!

what i want

                                  HTTP 404 ERROR !!

only example


问:
Emulator is not detected automatically unable to connect to device
I have a Dell device and suddenly I cannot connect the Android studio to the emulator. I get the following error message:

unable to open connection to: localhost/127.0.0.1:5037, due to:
  java.net.connectexception: connection refused: connect

Any Idea how to fix it ?

答:
I had the same problem after some unknown operations with my Windows 10. I tried many different ways, and finally solved it with the following steps:

open Command Prompt with Adminstrator privilege. (If you don't know how to, please google.)

"netstat -ao" to find which process takes the port of 127.0.0.1:5037. FOr example, something like

```<code> TCP    127.0.0.1:5037         mypcname:0       LISTENING       15752
</code>```

Here the culprit PID is 15752.

"taskkill /PID /F PID" to kill the process. Replace PID with your number, e.g., 15752.

retry adb. If it works, you may sometimes have to proceed with the following steps.

If it is a Windows service that is using the port, it may start automatically, and blocks adb subsequently. You could specify another adb server port for environment variable ANDROID_ADB_SERVER_PORT.

If the Windows service is LogsAndAlerts (which is the common case for many), you can disable or delete it with:

```<code>sc config "LogsAndAlerts" start= disabled

sc delete "LogsAndAlerts"
</code>```

Body:
I had the same problem after some unknown operations with my Windows 10. I tried many different ways, and finally solved it with the following steps:

open Command Prompt with Adminstrator privilege. (If you don't know how to, please google.)

"netstat -ao" to find which process takes the port of 127.0.0.1:5037. FOr example, something like

 TCP    127.0.0.1:5037         mypcname:0       LISTENING       15752

Here the culprit PID is 15752.

"taskkill /PID /F PID" to kill the process. Replace PID with your number, e.g., 15752.

retry adb. If it works, you may sometimes have to proceed with the following steps.

If it is a Windows service that is using the port, it may start automatically, and blocks adb subsequently. You could specify another adb server port for environment variable ANDROID_ADB_SERVER_PORT.

If the Windows service is LogsAndAlerts (which is the common case for many), you can disable or delete it with:

sc config "LogsAndAlerts" start= disabled

sc delete "LogsAndAlerts"


问:
How to validate date time with many format in laravel
I want to check my request datetime with many format look like below format:

```<code>Y-m-d
Y-m-
Y-m
</code>```

In Laravel, I use Validator to validate datetime, but Validator can not make checking with many format. This is my code:

```<code>Validator::make(['date' => $departureDate], [
   'date' => 'required|date_format:Y-m-d, Y-m, Y-m-'
]);
</code>```

How can I do it in laravel
Please help me! Many thanks!

答:
You must write a custom validation format for that. Laravel's date_format expects only one parameter and not capable of handling multi-formats. There are Two ways to add custom validation. first, one is making a rule repository and add your validation logic there. Here Taylor Otwell explained this method.

The other way to doing that is extend validation in app service provider and add new rule there. add this code in app service provider:

```<code>use Illuminate\Support\Facades\Validator;

Validator::extend('multi_date_format', function ($attribute, $value, $parameters,$validator) {

    $ok = true;

    $result = [];

      // iterate through all formats
      foreach ($parameters as $parameter){

         //validate with laravels standard date format validation
         $result[] = $validator->validateDateFormat($attribute,$value,[$parameter]);
      }

    //if none of result array is true. it sets ok to false
    if(!in_array(true,$result)){
        $ok = false;
        $validator->setCustomMessages(['multi_date_format' => 'The format must be one of Y-m-d ,Y-m or Y-m-']);
    }

    return $ok;
});
</code>```

And here you can use it this way:

```<code>$validator = Validator::make(['date' => '2000-02-01'], [
    'date' => 'required|multi_date_format:Y-m-d,Y-m,Y-m-'
]);

if($validator->fails()) {
    $errors = $validator->errors()->all();
}
</code>```

Body:
I want to check my request datetime with many format look like below format:

Y-m-d
Y-m-
Y-m

In Laravel, I use Validator to validate datetime, but Validator can not make checking with many format. This is my code:

Validator::make(['date' => $departureDate], [
   'date' => 'required|date_format:Y-m-d, Y-m, Y-m-'
]);

How can I do it in laravel
Please help me! Many thanks!

Body:
You must write a custom validation format for that. Laravel's date_format expects only one parameter and not capable of handling multi-formats. There are Two ways to add custom validation. first, one is making a rule repository and add your validation logic there. Here Taylor Otwell explained this method.

The other way to doing that is extend validation in app service provider and add new rule there. add this code in app service provider:

use Illuminate\Support\Facades\Validator;

Validator::extend('multi_date_format', function ($attribute, $value, $parameters,$validator) {

    $ok = true;

    $result = [];

      // iterate through all formats
      foreach ($parameters as $parameter){

         //validate with laravels standard date format validation
         $result[] = $validator->validateDateFormat($attribute,$value,[$parameter]);
      }

    //if none of result array is true. it sets ok to false
    if(!in_array(true,$result)){
        $ok = false;
        $validator->setCustomMessages(['multi_date_format' => 'The format must be one of Y-m-d ,Y-m or Y-m-']);
    }

    return $ok;
});

And here you can use it this way:

$validator = Validator::make(['date' => '2000-02-01'], [
    'date' => 'required|multi_date_format:Y-m-d,Y-m,Y-m-'
]);

if($validator->fails()) {
    $errors = $validator->errors()->all();
}


问:
Getting linux to buffer /dev/random
I need a reasonable supply of high-quality random data for an application I'm writing. Linux provides the /dev/random file for this purpose which is ideal; however, because my server is a single-service virtual machine, it has very limited sources of entropy, meaning /dev/random quickly becomes exhausted.

I've noticed that if I read from /dev/random, I will only get 16 or so random bytes before the device blocks while it waits for more entropy:

```<code>[duke@poopz ~]# hexdump /dev/random
0000000 f4d3 8e1e 447a e0e3 d937 a595 1df9 d6c5
<process blocks...>
</code>```

If I terminate this process, go away for an hour and repeat the command, again only 16 or so bytes of random data are produced.

However - if instead I leave the command running for the same amount of time, much, much more random data are collected. I assume from this that over the course of a given timeperiod, the system produces plenty of entropy, but Linux only utilises it if you are actually reading from /dev/random, and discards it if you are not. If this is the case, my question is:

Is it possible to configure Linux to buffer /dev/random so that reading from it yields much larger bursts of high-quality random data?

It wouldn't be difficult for me to buffer /dev/random as part of my program but I feel doing this at a system level would be more elegant. I also wonder if having Linux buffer its random data in memory would have security implications.

答: Sounds like you need an entropy deamon that feeds the entropy pool from other sources. </p>

Title: Getting linux to buffer /dev/random

Body:
I need a reasonable supply of high-quality random data for an application I'm writing. Linux provides the /dev/random file for this purpose which is ideal; however, because my server is a single-service virtual machine, it has very limited sources of entropy, meaning /dev/random quickly becomes exhausted.

I've noticed that if I read from /dev/random, I will only get 16 or so random bytes before the device blocks while it waits for more entropy:

[duke@poopz ~]# hexdump /dev/random
0000000 f4d3 8e1e 447a e0e3 d937 a595 1df9 d6c5
<process blocks...>

If I terminate this process, go away for an hour and repeat the command, again only 16 or so bytes of random data are produced.

However - if instead I leave the command running for the same amount of time, much, much more random data are collected. I assume from this that over the course of a given timeperiod, the system produces plenty of entropy, but Linux only utilises it if you are actually reading from /dev/random, and discards it if you are not. If this is the case, my question is:

Is it possible to configure Linux to buffer /dev/random so that reading from it yields much larger bursts of high-quality random data?

It wouldn't be difficult for me to buffer /dev/random as part of my program but I feel doing this at a system level would be more elegant. I also wonder if having Linux buffer its random data in memory would have security implications.


问:
Adding Jquery Mobile breaks CSS
When I add Jquery mobile to my HTML using CDN;

```<code><link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</code>```

It completely takes over my styles & breaks my design.

Is there anything I can do so that way its not using Jquery's CSS for my whole project?

答:
According to my experience including jquery.mobile.css alone is harmless, the trouble comes when the - mostly unnecessary - jquery.mobile scripts are loaded. The solution was using only those functions that are required, in my case 8k vs 200k and the problem was gone.

More details here (since I can't comment):

jQuery Mobile breaks links. What is the correct use?

Title: Adding Jquery Mobile breaks CSS

Body:
When I add Jquery mobile to my HTML using CDN;

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />

It completely takes over my styles & breaks my design.

Is there anything I can do so that way its not using Jquery's CSS for my whole project?


问:
Add class to div that contain Dog 1 and rows in between
The code is automatically generated so I cannot add classes/id's etc by adding HTML so I am trying to do this using js. I truncated the content, but basically I want to add class "dog1" to the rows that pertain to Dog 1 and class "dog2" to the rows that pertain to Dog 2.

I tried using the script in the attached snippet:

let dogCounter = 1;
let classAttribute = '';
const $trs = $('span:contains("Dog 1")').first().closest('div');

$trs.each((i, div) => {
  const selector = 'span:contains("Dog '+dogCounter+'")';
  if ($(div).find(selector).length) {
   classAttribute = 'dog'+dogCounter;
    dogCounter++;
  }
  $(div).addClass(classAttribute);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dog1 {
  color: red;
}
.dog2 {
  color: blue;
}</code>```

Dog 1 Name

Dog 1 Age

Dog 1 Weight

Date of last appointment

Dog 1 Number

Acceptance

Dog 1 Allergies

Dog 2 Details

Dog 2 Name

Dog 2 Name

Dog 2 Age

Dog 2 Weight

Date of last appointment

Dog 2 Number

Acceptance

Dog 2 Allergies
```

答:
:contains() has terrible syntax it's a mess. A less error prone way is to use .text() to extract the text contents of each div then see if a particular substring exists using .includes(). Also, if you run .each() start one level higher than the target elements and use .find() if you want all descendants or .children() if you want the direct descendants.:

```<code>$(ancestor element(s)).find(target elements).each(...
</code>```

Gets every matching element nested within ancestor element

```<code>$(ancestor element(s)).children(target elements).each(...
</code>```

Gets every matching element nested directly within ancestor element

$(function() {
  $(document).find('div').each(function() {
    let txt = $(this).text();
    if (txt.includes('Dog 1')) {
      $(this).addClass('dog1');
    }
    if (txt.includes('Dog 2')) {
      $(this).addClass('dog2');
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dog1 {
  color: red;
}

.dog2 {
  color: blue;
}</code>```

Dog 1 Name

Dog 1 Age

Dog 1 Weight

  Date of last appointment

Dog 1 Number

Acceptance

Dog 1 Allergies

Dog 2 Details

Dog 2 Name

Dog 2 Name

Dog 2 Age

Dog 2 Weight

Date of last appointment

Dog 2 Number

Acceptance

Dog 2 Allergies

```

Body:
The code is automatically generated so I cannot add classes/id's etc by adding HTML so I am trying to do this using js. I truncated the content, but basically I want to add class "dog1" to the rows that pertain to Dog 1 and class "dog2" to the rows that pertain to Dog 2.

I tried using the script in the attached snippet:

let dogCounter = 1;
let classAttribute = '';
const $trs = $('span:contains("Dog 1")').first().closest('div');

$trs.each((i, div) => {
  const selector = 'span:contains("Dog '+dogCounter+'")';
  if ($(div).find(selector).length) {
   classAttribute = 'dog'+dogCounter;
    dogCounter++;
  }
  $(div).addClass(classAttribute);
})

.dog1 {
  color: red;
}
.dog2 {
  color: blue;
}

Dog 1 Name

Dog 1 Age

Dog 1 Weight

Date of last appointment

Dog 1 Number

Acceptance

Dog 1 Allergies

Dog 2 Details

Dog 2 Name

Dog 2 Name

Dog 2 Age

Dog 2 Weight

Date of last appointment

Dog 2 Number

Acceptance

Dog 2 Allergies

Body:
:contains() has terrible syntax it's a mess. A less error prone way is to use .text() to extract the text contents of each div then see if a particular substring exists using .includes(). Also, if you run .each() start one level higher than the target elements and use .find() if you want all descendants or .children() if you want the direct descendants.:

$(ancestor element(s)).find(target elements).each(...

Gets every matching element nested within ancestor element

$(ancestor element(s)).children(target elements).each(...

Gets every matching element nested directly within ancestor element

$(function() {
  $(document).find('div').each(function() {
    let txt = $(this).text();
    if (txt.includes('Dog 1')) {
      $(this).addClass('dog1');
    }
    if (txt.includes('Dog 2')) {
      $(this).addClass('dog2');
    }
  });
});

.dog1 {
  color: red;
}

.dog2 {
  color: blue;
}

<div><span>Dog 1 Name</span></div>
<div><span>Dog 1 Age</span></div>
<div><span>Dog 1 Weight</span></div>
<div>
  <span>Date of last appointment</span></div>
<div><span>Dog 1 Number</span></div>
<div><span>Acceptance</span></div>
<div>
  <div><span>Dog 1 Allergies</span></div>
</div>
<div><span>Dog 2 Details</span></div>
<div><span>Dog 2 Name</span></div>
<div><span>Dog 2 Name</span></div>
<div><span>Dog 2 Age</span></div>
<div><span>Dog 2 Weight</span></div>
<div><span>Date of last appointment</span></div>
<div><span>Dog 2 Number</span></div>
<div><span>Acceptance</span></div>
<div><span>Dog 2 Allergies</span></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Make the last inline list item extend remaining width of container
I'm looking for a way to make the last inline list item extend the remainder of its container. So I have something like this.

```<code><nav>
  <ul>
     <li></li> //width = 50px
     <li></li> //width = 50px
     <li class="last"></li> //width needs to fill the remaining 300px
  </ul>
</nav>

nav {
  width:400px;
  height:50px;
}
nav > ul > li {
  display:inline-block;
  padding:5px;
}
</code>```

Now the number of list items varies so I can't set the last list item to a set width. I need to make it fill whatever is left over in the width of the nav. How to with using css only?

答:
Update for 2019 :</p>

```<code>ul {
    display: flex;
}
ul li:last-child {
    flex: 1;
}
</code>```

Body:
I'm looking for a way to make the last inline list item extend the remainder of its container. So I have something like this.

 //width = 50px

 //width = 50px

 //width needs to fill the remaining 300px

nav {
  width:400px;
  height:50px;
}
nav > ul > li {
  display:inline-block;
  padding:5px;
}

Now the number of list items varies so I can't set the last list item to a set width. I need to make it fill whatever is left over in the width of the nav. How to with using css only?

Body:
Update for 2019 :

ul {
    display: flex;
}
ul li:last-child {
    flex: 1;
}


问:
Multiple value assignment
```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b
</code>```

and

```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b
</code>```

Both give different output.
What is the difference between   a, b = b, a+b  and a = b; b = a+b?

答:
The below code is like swapping.

```<code>a, b = b, a+b
</code>```

Its like doing this

```<code>temp = a
a = b
b = temp + b
</code>```

Title: Multiple value assignment

Body:
a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b

and

a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b

Both give different output.
What is the difference between   a, b = b, a+b  and a = b; b = a+b?

Body:
The below code is like swapping.

a, b = b, a+b

Its like doing this

temp = a
a = b
b = temp + b


问:
Python Selenium selecting option using Select (element not visible?)
I've tried to use a few approaches mentioned in similar questions with no luck. In the HTML source code there is clearly 'value' and 'text' properties, but I cannot seem to access those when I use selenium.webdriver to access these?

Note selection lead to change in data on the page...

Edit2:

Guy has pointed out below that the actual drop down maybe a  element instead of the  element. However using el.click() simply flickers and does not open the drop-down.

EDIT1:
The  and  elements can now be identified but I am unable to make an selection. I believe the page is also in javascript and hence I'm unsure if this affects methods used.

Original post:

Webpage:
https://www.racv.com.au/on-the-road/driving-maintenance/fuel-prices.html

HTML code of selection, for visibility, some options omitted:

<select name="filter-select-6" id="filter-select-6" class="js-dropdown js-select-map js-filter-select" data-filter="#filter-list-60 .js-tab-item" data-url="/bin/racv/fuelprice" style="display: none;" data-parsley-id="3">
    <option value="11" data-index="0">LRP</option>
    <option value="2" selected="true" data-index="0">Unleaded</option>
    <option value="3" data-index="0">Diesel</option>
    <option value="8" data-index="0">Premium Unleaded 98</option>
</select>
```

<p>I believe I can select the Select element without problem:</p>

<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
from selenium.webdriver.support.ui import Select

url = 'https://www.racv.com.au/on-the-road/driving-maintenance/fuel-prices.html'
driver = webdriver.Chrome()
driver.get(url)
driver.implicitly_wait(20)

fuel_select = Select(driver.find_element_by_id('filter-select-6'))
</code>```

When I print the options, I get:

for fuel_option in fuel_select.options:
    print(fuel_option)

<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-2")>
<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-3")>
<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-8")>
<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-11")>
```

<p>Using select():</p>

<pre class="lang-py prettyprint-override"><code>for fuel_option in fuel_select.find_elements_by_tag_name('option'):
    if fuel_option.text == "Diesel":
        fuel_option.select()
</code>```

Error:

Traceback (most recent call last):
  File "C:/file.py", line 18, in <module>
    fuel_option.Select()
AttributeError: 'WebElement' object has no attribute 'select'
```

<p>Using click() or using any of the select_by_xxx():</p>

<pre class="lang-py prettyprint-override"><code>for fuel_option in fuel_select.find_elements_by_tag_name('option'):
    if fuel_option.text == "Diesel":
        fuel_option.click()

#or using select_by_xxx
fuel_select.select_by_value('8')
</code>```

Error:

selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable: Element is not currently visible and may not be manipulated
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)
```

答:
Select is a wrapper around the WebElement, select() is not a valid method. Please refer to Select doc

Have you tried using select_by_value:

```<code>fuel_select = Select(driver.find_element_by_id('filter-select-6'))
fuel_select.select_by_value("8")
</code>```

Or by visible text:

```<code>fuel_select = Select(driver.find_element_by_id('filter-select-6'))
fuel_select.select_by_visible_text("Premium Unleaded 98")
</code>```

EDIT1

Try to click() first to make the dropdown visible:

```<code>el = driver.find_element_by_id('filter-select-6')
el.click()
fuel_select = Select(el)
</code>```

EDIT2:

I believe your issue is more related to the fact that you use the css property style="display: none;"
You should not be able to see the dropdown manually either.

Please refer to the css syntax doc for more detail

When using None: The element is completely removed

Might not be "ideal" but you can change the value of this property to make it visible again using:

```<code>driver.execute_script('arguments[0].style.display = "block";', el)
</code>```

Code would then look like:

```<code>el = driver.find_element_by_id('filter-select-6')
driver.execute_script('arguments[0].style.display = "block";', el)

fuel_select = Select(el)
fuel_select.select_by_value("8")
</code>```

EDIT3:

Just noticed you provided the website! Very useful.
So the dropdown is hidden being another element and only made available once clicked.

Here's the code and it worked for me

```<code>from selenium import webdriver
from selenium.webdriver.common.touch_actions import TouchActions
from selenium.webdriver.support.ui import Select

# Get the first element and tap on it, note you might have to tap few time.
el = driver.find_element_by_css_selector('.chosen-single > div')
action = TouchActions(driver)
action.tap(el).perform()

# once the dropdown is open it does not seems that the Select el is the one to use
els = driver.find_elements_by_css_selector('.active-result')
for el in els:
    if el.text == 'Diesel':
        el.click()
        break
</code>```

Body:
I've tried to use a few approaches mentioned in similar questions with no luck. In the HTML source code there is clearly 'value' and 'text' properties, but I cannot seem to access those when I use selenium.webdriver to access these?

Note selection lead to change in data on the page...

Edit2:

Guy has pointed out below that the actual drop down maybe a  element instead of the  element. However using el.click() simply flickers and does not open the drop-down.

EDIT1:
The  and  elements can now be identified but I am unable to make an selection. I believe the page is also in javascript and hence I'm unsure if this affects methods used.

Original post:

Webpage:
https://www.racv.com.au/on-the-road/driving-maintenance/fuel-prices.html

HTML code of selection, for visibility, some options omitted:

<select name="filter-select-6" id="filter-select-6" class="js-dropdown js-select-map js-filter-select" data-filter="#filter-list-60 .js-tab-item" data-url="/bin/racv/fuelprice" style="display: none;" data-parsley-id="3">
    <option value="11" data-index="0">LRP</option>
    <option value="2" selected="true" data-index="0">Unleaded</option>
    <option value="3" data-index="0">Diesel</option>
    <option value="8" data-index="0">Premium Unleaded 98</option>
</select>

I believe I can select the Select element without problem:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

url = 'https://www.racv.com.au/on-the-road/driving-maintenance/fuel-prices.html'
driver = webdriver.Chrome()
driver.get(url)
driver.implicitly_wait(20)

fuel_select = Select(driver.find_element_by_id('filter-select-6'))

When I print the options, I get:

for fuel_option in fuel_select.options:
    print(fuel_option)

<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-2")>
<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-3")>
<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-8")>
<selenium.webdriver.remote.webelement.WebElement (session="9a10aa750fa59f4412e0bea4d7aae990", element="0.5927271524692566-11")>

Using select():

for fuel_option in fuel_select.find_elements_by_tag_name('option'):
    if fuel_option.text == "Diesel":
        fuel_option.select()

Error:

Traceback (most recent call last):
  File "C:/file.py", line 18, in <module>
    fuel_option.Select()
AttributeError: 'WebElement' object has no attribute 'select'

Using click() or using any of the select_by_xxx():

for fuel_option in fuel_select.find_elements_by_tag_name('option'):
    if fuel_option.text == "Diesel":
        fuel_option.click()

#or using select_by_xxx
fuel_select.select_by_value('8')

Error:

selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable: Element is not currently visible and may not be manipulated
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)

Body:
Select is a wrapper around the WebElement, select() is not a valid method. Please refer to Select doc

Have you tried using select_by_value:

fuel_select = Select(driver.find_element_by_id('filter-select-6'))
fuel_select.select_by_value("8")

Or by visible text:

fuel_select = Select(driver.find_element_by_id('filter-select-6'))
fuel_select.select_by_visible_text("Premium Unleaded 98")

EDIT1

Try to click() first to make the dropdown visible:

el = driver.find_element_by_id('filter-select-6')
el.click()
fuel_select = Select(el)

EDIT2:

I believe your issue is more related to the fact that you use the css property style="display: none;"
You should not be able to see the dropdown manually either.

Please refer to the css syntax doc for more detail

When using None: The element is completely removed

Might not be "ideal" but you can change the value of this property to make it visible again using:

driver.execute_script('arguments[0].style.display = "block";', el)

Code would then look like:

el = driver.find_element_by_id('filter-select-6')
driver.execute_script('arguments[0].style.display = "block";', el)

fuel_select = Select(el)
fuel_select.select_by_value("8")

EDIT3:

Just noticed you provided the website! Very useful.
So the dropdown is hidden being another element and only made available once clicked.

Here's the code and it worked for me

from selenium import webdriver
from selenium.webdriver.common.touch_actions import TouchActions
from selenium.webdriver.support.ui import Select

# Get the first element and tap on it, note you might have to tap few time.
el = driver.find_element_by_css_selector('.chosen-single > div')
action = TouchActions(driver)
action.tap(el).perform()

# once the dropdown is open it does not seems that the Select el is the one to use
els = driver.find_elements_by_css_selector('.active-result')
for el in els:
    if el.text == 'Diesel':
        el.click()
        break


问:
determine jpeg filesize without actually saving the jpeg
I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

```<code>frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;
</code>```

But because of the slow disk access, the program takes too long.
Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)

答:
Try loading it into memory without saving to disk.  Look up MemoryStream.

Also, this answer might help:  How to get the file size of a "System.Drawing.Image"

Body:
I have an image in PNG or BMP format. I would like to find out the filesize of that image after compressing it to a jpeg without saving the jpeg.

Up to now I did it the following way:

frameNormal.Save("temp.jpg", ImageFormat.Jpeg);
tempFile = new FileInfo("temp.jpg");
filesizeJPG = tempFile.Length;

But because of the slow disk access, the program takes too long.
Is there a way to calculate the filesize of the newly created jpeg? Like converting the PNG in memory and read the size...

Any help is very much appreciated :-)


答:
```<code>a, b = b, a+b
</code>```

is equivalent to

```<code>tmp = a
a = b
b = tmp+b
</code>```

Title: Multiple value assignment

Body:
a, b = b, a+b

is equivalent to

tmp = a
a = b
b = tmp+b


答: I believe in some systems newline is \r\n or just \r, so give /\r?\n|\r/ a shot

Title: How to replace all newlines after reading a file

Body:
How can I replace a newline in a string with a ','? I have a string that is read from a file:

const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);

It takes a string from a file:

a,b,c,d,e,f
,,,,,
g,h,i,j,k,l

I'm able to detect the newline with this:

if (char === '\n')

But replacing \n like this doesn't work

str = csvString.replace('/\n/g');

I want to get the string to look like this:

a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,


问:
HTML anchor within Javascript variable assigned dynamically to a dataTable cell is not rendered by the browser
I have implemented a dataTable on dynamic set of data.  There is a javascript variable that contains the following:

```<code>var path = "/<a href="http://demo.example.com/first.html">First</a>/<a href="http://demo.example.com/second.html">Second</a>/";
</code>```

This variable is supposed to have two anchors.  When I assign this variable dynamically to a cell of a dataTable as follows:

```<code>var tab = document.getElementById("sample_table");
var objCells = tab.rows.item(i).cells;
objCells[0].innerHTML = path;
</code>```

It is shown as plain text within the table cell and is not rendered as HTML by the browser:

```<code>/<a href="http://demo.example.com/first.html">First</a>/<a href="http://demo.example.com/second.html">Second</a>/
</code>```

and I want it like this:

/First/Second/

What should be done to render it correctly in the browser?

答:
var path = `/First/Second/`;
var tab = document.getElementById("table1");
var objCells = tab.rows.item(0).cells;
objCells[0].innerHTML = path;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<body>
<table id='table1' border=1>
  <tr>
    <td></td>
    <td></td>
  </tr>
</table>
</body>
</html></code>```

try using JavaScript template literals,
Instead of using single quote using the ` letter

Body:
I have implemented a dataTable on dynamic set of data.  There is a javascript variable that contains the following:

var path = "/First/Second/";

This variable is supposed to have two anchors.  When I assign this variable dynamically to a cell of a dataTable as follows:

var tab = document.getElementById("sample_table");
var objCells = tab.rows.item(i).cells;
objCells[0].innerHTML = path;

It is shown as plain text within the table cell and is not rendered as HTML by the browser:

/First/Second/

and I want it like this:

/First/Second/

What should be done to render it correctly in the browser?

Body:
var path = `/<a href="http://demo.example.com/first.html">First</a>/<a href="http://demo.example.com/second.html">Second</a>/`;
var tab = document.getElementById("table1");
var objCells = tab.rows.item(0).cells;
objCells[0].innerHTML = path;

<!DOCTYPE html>
<html>

<body>
<table id='table1' border=1>
  <tr>
    <td></td>
    <td></td>
  </tr>
</table>
</body>
</html>

try using JavaScript template literals,
Instead of using single quote using the ` letter


问:
Angular Material 2 md-input-container not working
I'm encountering an issue with angular-material2 where I'm trying to use an input. However, none of what I tried has worked.

I'm getting this issue:

'md-input-container' is not a known element

HTML:

<md-input-container>
<input mdInput placeholder="Favorite food" value="Sushi">
</md-input-container>
```

<p>I imported this in my <strong>component.ts</strong> and in my <strong>app.ts</strong>:</p>

<pre class="lang-ts prettyprint-override"><code>import { MdInputModule } from '@angular/material';
</code>```

and I declared it in my 'imports' in @NgModule in app.ts

My version of material is @angular/material@2.0.0-beta.8

Thanks for your help.

EDIT : I found that I imported it in the app.module.ts which imported another module where I needed to put the declarations. My code is a bit messy, I need to clear it up. Sorry for this my friends. Case closed.

答:
Instead of md-input-container or mat-input-container, use mat-form-field.
As its the current supported input container as per release version 8.0.0. For more info, see
official angular material doc</p>

Body:
I'm encountering an issue with angular-material2 where I'm trying to use an input. However, none of what I tried has worked.

I'm getting this issue:

'md-input-container' is not a known element

HTML:

<md-input-container>
<input mdInput placeholder="Favorite food" value="Sushi">
</md-input-container>

I imported this in my component.ts and in my app.ts:

import { MdInputModule } from '@angular/material';

and I declared it in my 'imports' in @NgModule in app.ts

My version of material is @angular/material@2.0.0-beta.8

Thanks for your help.

EDIT : I found that I imported it in the app.module.ts which imported another module where I needed to put the declarations. My code is a bit messy, I need to clear it up. Sorry for this my friends. Case closed.


答:
let text = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`;

let edited = text.replace(/\s+/g, '');

console.log( edited )```

You can try this solution also. \s means white spaces.

Body:
let text = `a,b,c,d,e,f
,,,,,
g,h,i,j,k,l`;

let edited = text.replace(/\s+/g, '');

console.log( edited )

You can try this solution also. \s means white spaces.


问:
CVXPY and MOSEK: Type object 'solsta' has no attribute 'near_optimal'
I'm trying to solve optimization problems using cvxpy and MOSEK. Despite the fact that both packages seem to work independently, I don't manage to get them function together. Whenever I ask cvxpy to solve any problem with MOSEK, I always get the error:

AttributeError: type object 'solsta' has no attribute 'near_optimal'

What am I doing wrong?

Consider the following (minimal) code:

```<code>import cvxpy as cp

x = cp.Variable(2)
obj = cp.Minimize(x[0] + x[1])
constraints = [x >= 2]+[x<=5]
prob = cp.Problem(obj, constraints)

# Solve with MOSEK.
prob.solve(solver=cp.MOSEK,verbose=True)
print("optimal value with MOSEK:", prob.value)
</code>```

As with any other optimization I've tried with MOSEK and cvxpy, the compiler crashes on this line:

```<code>prob.solve(solver=cp.MOSEK,verbose=True)
</code>```

MOSEK correctly solves the problem, but there seems to be an issue in communicating the solution to cvxpy.

答: It looks like you installed the latest Mosek version 9 but you have a fairly old cvxpy which does not support it. Upgrade cvxpy, the latest version supports Mosek 9. </p>

Body:
I'm trying to solve optimization problems using cvxpy and MOSEK. Despite the fact that both packages seem to work independently, I don't manage to get them function together. Whenever I ask cvxpy to solve any problem with MOSEK, I always get the error:

AttributeError: type object 'solsta' has no attribute 'near_optimal'

What am I doing wrong?

Consider the following (minimal) code:

import cvxpy as cp

x = cp.Variable(2)
obj = cp.Minimize(x[0] + x[1])
constraints = [x >= 2]+[x<=5]
prob = cp.Problem(obj, constraints)

# Solve with MOSEK.
prob.solve(solver=cp.MOSEK,verbose=True)
print("optimal value with MOSEK:", prob.value)

As with any other optimization I've tried with MOSEK and cvxpy, the compiler crashes on this line:

prob.solve(solver=cp.MOSEK,verbose=True)

MOSEK correctly solves the problem, but there seems to be an issue in communicating the solution to cvxpy.


问:
save uiimageview to coredata as binary data swift (5)
I am trying to save a imageview as a image to binary data in core data. My code is not working. It has a compile error. In View controller it is not regisitering cdHandler. All i want to do is save the the imaveview as binary data in a core data model.I have 2 classes a app delegate and a view controller.

CLASS VIEW CONTROLLER

```<code>    import UIKit
import CoreData

class ViewController: UIViewController {
var canVasView = UIImageView()
@objc func hhh() {
    let photo = self.canVasView.image
    let data = photo!.pngData()

    if cdHandler.saveObject(pic:  data!){
    }
}
}
</code>```

APP DELEGATE

```<code>  import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

     lazy var persistentContainer: NSPersistentContainer = {
         /*
          The persistent container for the application. This implementation
          creates and returns a container, having loaded the store for the
          application to it. This property is optional since there are legitimate
          error conditions that could cause the creation of the store to fail.
          */
         let container = NSPersistentContainer(name: "Model")
         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
             if let error = error as NSError? {
                 // Replace this implementation with code to handle the error appropriately.
                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
class cdHandler: NSObject {

    private class func getContext() -> NSManagedObjectContext {
        let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
        return appdeleagetzz.persistentContainer.viewContext
    }
    class func saveObject(pic: Data, userName: String) -> Bool {
        let context = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
        let managedObject = NSManagedObject(entity: entity!, insertInto: context)
        managedObject.setValue(pic, forKey:"pic")
        managedObject.setValue(userName, forKey:"userName")
        do {
            try context.save()
            return true

        } catch {
            return false

        }
    }
    class func deletObject(user: User) -> Bool {
        let context = getContext()
        context.delete(user)

        do {
            try context.save()
            return true
        } catch {
            return false

        }
    }

    class func fetchObject() -> [User]? {

        do {
            let context = getContext()
            return try context.fetch(User.fetchRequest())
        } catch {
            return [User]()
        }
    }

}
}
</code>```

答:
The error message, *Value of type 'AppDelegate' has no member named 'persistentContainer', explains the problem.  Indeed, when I look at the code for your AppDelegate class, I can confirm that it has no member named 'persistentContainer'.  (If I am reading it correctly, the last two lines in the file are closing curly brackets.  The first one closes your cdHandler nested class, and the second one closes your AppDelegate class.)

Do the following exercise.  In Xcode, click in the menu: File > New Project and select iOS, Application and Single View App.  Name your new project Junk.  Switch on the Core Data checkbox.  Click button Create.  After it is done, look at the AppDelegate.swift which Xcode created, and in the AppDelegate class, you see it contains 8 functions (func).  The 7th one is lazy var persistentContainer.  Aha!  The compiler is telling you that you probably should not have deleted those 8 functions, persistentContainer in particular.

You should copy that persistentContainer func from that Junk project into your AppDelegate class in your real project.  Or, to head off future trouble, consider copying most of the other 7 funcs also.  As you can see, most of them don't do anything except provide comments with explanations that are useful for beginners.  After you are done copying, close the Junk project.  (I overwrite my Junk project with a new Junk project several times in a typical week, especially when answering StackOverflow questions.)

That should fix this particular error and answer this question.  Onward to the next issue.  :)

Response to comment that you still get the error with cdHandler

Having nothing else to go on, I presume that the error that you are referring to is the compiler error still in your screenshot.  In other words, you are saying that adding the persistentContainer definition did not make it any better.

Well, it works for me.  Please replace all of the code in your AppDelegate.swift class with the following, build and run it…

```<code>import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AppDelegate.cdHandler.testGetContext()
        return true
    }

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "Junk")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    class cdHandler: NSObject {

        private class func getContext() -> NSManagedObjectContext {
            let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
            return appdeleagetzz.persistentContainer.viewContext
        }

        class func testGetContext() {
            let context = getContext()
            print("getContext() succeeded, got \(context)")
        }

        class func saveObject(pic: Data, userName: String) -> Bool {
            let context = getContext()
            let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
            let managedObject = NSManagedObject(entity: entity!, insertInto: context)
            managedObject.setValue(pic, forKey:"pic")
            managedObject.setValue(userName, forKey:"userName")
            do {
                try context.save()
                return true

            } catch {
                return false

            }
        }
        class func deletObject(user: NSManagedObject) -> Bool {
            let context = getContext()
            context.delete(user)

            do {
                try context.save()
                return true
            } catch {
                return false

            }
        }

    }
}
</code>```

You see that compiles with no errors.  Also, it runs and the AppDelegate.cdhandler.getContext() method works.  As you can see, in AppDelegate.application(application:didFinishLaunchingWithOptions:), I have added a call to a new method which I defined later,AppDelegate.cdHandler.testGetContext()`.  It works perfectly.

Are you getting a different error now?  If so, you need to specify whether it is a Build or Run error.  In either case, copy and paste the text of the  error into your question, and tell us where it occurs.

Body:
I am trying to save a imageview as a image to binary data in core data. My code is not working. It has a compile error. In View controller it is not regisitering cdHandler. All i want to do is save the the imaveview as binary data in a core data model.I have 2 classes a app delegate and a view controller.

CLASS VIEW CONTROLLER

    import UIKit
import CoreData

class ViewController: UIViewController {
var canVasView = UIImageView()
@objc func hhh() {
    let photo = self.canVasView.image
    let data = photo!.pngData()

    if cdHandler.saveObject(pic:  data!){
    }
}
}

APP DELEGATE

  import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

     lazy var persistentContainer: NSPersistentContainer = {
         /*
          The persistent container for the application. This implementation
          creates and returns a container, having loaded the store for the
          application to it. This property is optional since there are legitimate
          error conditions that could cause the creation of the store to fail.
          */
         let container = NSPersistentContainer(name: "Model")
         container.loadPersistentStores(completionHandler: { (storeDescription, error) in
             if let error = error as NSError? {
                 // Replace this implementation with code to handle the error appropriately.
                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
class cdHandler: NSObject {

    private class func getContext() -> NSManagedObjectContext {
        let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
        return appdeleagetzz.persistentContainer.viewContext
    }
    class func saveObject(pic: Data, userName: String) -> Bool {
        let context = getContext()
        let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
        let managedObject = NSManagedObject(entity: entity!, insertInto: context)
        managedObject.setValue(pic, forKey:"pic")
        managedObject.setValue(userName, forKey:"userName")
        do {
            try context.save()
            return true

        } catch {
            return false

        }
    }
    class func deletObject(user: User) -> Bool {
        let context = getContext()
        context.delete(user)

        do {
            try context.save()
            return true
        } catch {
            return false

        }
    }

    class func fetchObject() -> [User]? {

        do {
            let context = getContext()
            return try context.fetch(User.fetchRequest())
        } catch {
            return [User]()
        }
    }

}
}

Body:
The error message, *Value of type 'AppDelegate' has no member named 'persistentContainer', explains the problem.  Indeed, when I look at the code for your AppDelegate class, I can confirm that it has no member named 'persistentContainer'.  (If I am reading it correctly, the last two lines in the file are closing curly brackets.  The first one closes your cdHandler nested class, and the second one closes your AppDelegate class.)

Do the following exercise.  In Xcode, click in the menu: File > New Project and select iOS, Application and Single View App.  Name your new project Junk.  Switch on the Core Data checkbox.  Click button Create.  After it is done, look at the AppDelegate.swift which Xcode created, and in the AppDelegate class, you see it contains 8 functions (func).  The 7th one is lazy var persistentContainer.  Aha!  The compiler is telling you that you probably should not have deleted those 8 functions, persistentContainer in particular.

You should copy that persistentContainer func from that Junk project into your AppDelegate class in your real project.  Or, to head off future trouble, consider copying most of the other 7 funcs also.  As you can see, most of them don't do anything except provide comments with explanations that are useful for beginners.  After you are done copying, close the Junk project.  (I overwrite my Junk project with a new Junk project several times in a typical week, especially when answering StackOverflow questions.)

That should fix this particular error and answer this question.  Onward to the next issue.  :)

Response to comment that you still get the error with cdHandler

Having nothing else to go on, I presume that the error that you are referring to is the compiler error still in your screenshot.  In other words, you are saying that adding the persistentContainer definition did not make it any better.

Well, it works for me.  Please replace all of the code in your AppDelegate.swift class with the following, build and run it…

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AppDelegate.cdHandler.testGetContext()
        return true
    }

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "Junk")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    class cdHandler: NSObject {

        private class func getContext() -> NSManagedObjectContext {
            let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
            return appdeleagetzz.persistentContainer.viewContext
        }

        class func testGetContext() {
            let context = getContext()
            print("getContext() succeeded, got \(context)")
        }

        class func saveObject(pic: Data, userName: String) -> Bool {
            let context = getContext()
            let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
            let managedObject = NSManagedObject(entity: entity!, insertInto: context)
            managedObject.setValue(pic, forKey:"pic")
            managedObject.setValue(userName, forKey:"userName")
            do {
                try context.save()
                return true

            } catch {
                return false

            }
        }
        class func deletObject(user: NSManagedObject) -> Bool {
            let context = getContext()
            context.delete(user)

            do {
                try context.save()
                return true
            } catch {
                return false

            }
        }

    }
}

You see that compiles with no errors.  Also, it runs and the AppDelegate.cdhandler.getContext() method works.  As you can see, in AppDelegate.application(application:didFinishLaunchingWithOptions:), I have added a call to a new method which I defined later,AppDelegate.cdHandler.testGetContext()`.  It works perfectly.

Are you getting a different error now?  If so, you need to specify whether it is a Build or Run error.  In either case, copy and paste the text of the  error into your question, and tell us where it occurs.