问:
Error using useEffect in react functional component
I am learning to use react hooks to manage state but I get the error saying
  Line 5:3:  React Hook "useEffect" is called in function "cockpit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is my code

```<code>import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (
    <div className={classes.Cockpit}>
      <h1>Hi I'm a React App</h1>
      <p className={assiginedClasses.join(" ")}>This is really Working!</p>
      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>
    </div>
  );
};

export default cockpit;
</code>```

答: Functional components usually start with capital letters. So change the name 'cockpit' to 'Cockpit'</p>

Body:
I am learning to use react hooks to manage state but I get the error saying
  Line 5:3:  React Hook "useEffect" is called in function "cockpit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is my code

import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (

Hi I'm a React App

This is really Working!

      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>

  );
};

export default cockpit;


来源: stackexchange

问:
,what is the use and benefit of Serialize() function in php
I know its Generates a storable representation of a value and  used to access the objects across the php files but what if i dont use this function while storing the objects.</p>

答: You can store a PHP structure in a file, session or even database. I use it for caching query results in a file or in memcache.</p>

ContentLicense: CC BY-SA 3.0


问:
PHP foreach statement split names MySQL database
I have a PHP script which interacts with my MySQL database. In my database I've got multiple columns, like:

'temp_0_state',
'temp_0_color',
'temp_1_state',
'temp_1_color',
'temp_2_state',
'temp_2_color'
etc etc. till
'temp_50_state',
'temp_50_color'

All 50 records contain under the 'temp_xxx_state' a name or will be empty ("") and
under 'temp_xxx_color' a color.

I can show all the colors of the 50 records manually, like

```<code>  if ($user['temp_0_state'] == "") {
  } else {
     echo . $user['temp_0_color'] . ;
     }
  if ($user['temp_1_state'] == "") {
  } else {
     echo . $user['temp_1_color'] . ;
     }
  if ($user['temp_2_state'] == "") {
  } else {
     echo . $user['temp_2_color'] . ;
     }
</code>```

etc etc till

```<code>  if ($user['temp_50_state'] == "") {
  } else {
     echo . $user['temp_50_color'] . ;
     }
</code>```

But it'll be easier, and to reduce the amount of php code, to use a foreach statement on the number in the middle of the column name for all records between 0 and 50 (0 < n < 50).
How can I split the names and use a foreach statement on the number 0 till 50 between the underscores?

答:
A for statement would be more convenient in this situation, as you already know the maximum of records, according to your description:

```<code>for ($i = 0; $i <= 50; $i++) {
    if (!empty($user['temp_'.$i.'_state'])) {
        echo $user['temp_'.$i.'_color'];
    }
}
</code>```

Please check the official for loop documentation to learn more about it: https://www.php.net/manual/en/control-structures.for.php

ContentLicense: CC BY-SA 4.0

Body:
I have a PHP script which interacts with my MySQL database. In my database I've got multiple columns, like:

'temp_0_state',
'temp_0_color',
'temp_1_state',
'temp_1_color',
'temp_2_state',
'temp_2_color'
etc etc. till
'temp_50_state',
'temp_50_color'

All 50 records contain under the 'temp_xxx_state' a name or will be empty ("") and
under 'temp_xxx_color' a color.

I can show all the colors of the 50 records manually, like

  if ($user['temp_0_state'] == "") {
  } else {
     echo . $user['temp_0_color'] . ;
     }
  if ($user['temp_1_state'] == "") {
  } else {
     echo . $user['temp_1_color'] . ;
     }
  if ($user['temp_2_state'] == "") {
  } else {
     echo . $user['temp_2_color'] . ;
     }

etc etc till

  if ($user['temp_50_state'] == "") {
  } else {
     echo . $user['temp_50_color'] . ;
     }

But it'll be easier, and to reduce the amount of php code, to use a foreach statement on the number in the middle of the column name for all records between 0 and 50 (0 < n < 50).
How can I split the names and use a foreach statement on the number 0 till 50 between the underscores?

Body:
A for statement would be more convenient in this situation, as you already know the maximum of records, according to your description:

for ($i = 0; $i <= 50; $i++) {
    if (!empty($user['temp_'.$i.'_state'])) {
        echo $user['temp_'.$i.'_color'];
    }
}

Please check the official for loop documentation to learn more about it: https://www.php.net/manual/en/control-structures.for.php


问:
Return an array where the new elements are the sum of sum of distances between indices with same value in a given array
For each index in a given array I want to find the sum of sum of the distances between that index and other indices which have the same value in a given array.

So for [1,2,1,1,2,3], we would have [5,3,3,4,3,0] because

for index 0) |2-0|+|3-0| = 5, for index 1) |4-1| = 3 ,... , for index 3) |3-0|+|3-2| = 4,... etc..

Here is my attempt which gets TLE for arrays of length near 10000.

How can I make my solution more efficient?

```<code>def getDistanceMetrics(arr):
    if len(arr) > 10**5 or len(arr) < 1:
        return -1
    for z in range(len(arr)):
        if arr[z] > 10**9 or arr[z] < 1:
            return -1

    # Write your code here
    hm = collections.defaultdict(set)

    for i,value in enumerate(arr):
        hm[value].add(i)

    ans = []

    for j,val in enumerate(arr):
        tmp = 0
        for element in hm[val]:
            tmp += (j-element) if (j-element) >= 0 else element - j
        ans.append(tmp)

    return ans
</code>```

I would also appreciate knowing as to why and where my answer is slow, because to me it looks like O(n), which seems as good as you could do here.

Body:
For each index in a given array I want to find the sum of sum of the distances between that index and other indices which have the same value in a given array.

So for [1,2,1,1,2,3], we would have [5,3,3,4,3,0] because

for index 0) |2-0|+|3-0| = 5, for index 1) |4-1| = 3 ,... , for index 3) |3-0|+|3-2| = 4,... etc..

Here is my attempt which gets TLE for arrays of length near 10000.

How can I make my solution more efficient?

def getDistanceMetrics(arr):
    if len(arr) > 10**5 or len(arr) < 1:
        return -1
    for z in range(len(arr)):
        if arr[z] > 10**9 or arr[z] < 1:
            return -1

    # Write your code here
    hm = collections.defaultdict(set)

    for i,value in enumerate(arr):
        hm[value].add(i)

    ans = []

    for j,val in enumerate(arr):
        tmp = 0
        for element in hm[val]:
            tmp += (j-element) if (j-element) >= 0 else element - j
        ans.append(tmp)

    return ans

I would also appreciate knowing as to why and where my answer is slow, because to me it looks like O(n), which seems as good as you could do here.

Body:
In [1]: a = [1,2,1,1,2,3]

In [2]: b = [sum(abs(n-m) for m, j in enumerate(a) if i==j) for n, i in enumerat
   ...: e(a)]

In [3]: b
Out[3]: [5, 3, 3, 4, 3, 0]


问:
Easier management of DOM creation of elements in PHP
I'm trying to find an easier way to create  elements and inserting text values into them.

There has to be an easier way than creating a new variable for each  element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 s will require me to  create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 s. This seems excessive to me. Not to mention there's more than one
in the table. Is there any way to shorten the amount of lines I can type to create something like:

```<code><table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</code>```

Short example code of what I'm doing:

```<code>$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>
</code>```

答:
Do you know about SimpleXML? Especially: simplexml_load_string() which you can just pass a fragment of XML, and it'll convert it into an object:

```<code>$xml=simplexml_load_string("<an><element>This is text</element></an>");
echo $xml->element; // => This is text
</code>```

Doesn't get easier than that. Unless you just concatenate strings and create a DOM Document from the resulting pseudo-XML to test if it's well-formed by checking the return value.

Body:
I'm trying to find an easier way to create  elements and inserting text values into them.

There has to be an easier way than creating a new variable for each  element, right? Perhaps making a class with some abstraction? Or maybe I'm doing it the wrong way?

At this rate creating 7 s will require me to  create 7 variables, 7 different createTextNodes for each of them and 14 more lines of appendChild().

That will be 28 lines for only 7 s. This seems excessive to me. Not to mention there's more than one
in the table. Is there any way to shorten the amount of lines I can type to create something like:

Short example code of what I'm doing:

$doc = new DOMDocument;

$table = $doc->createElement('table');

        $doc->appendChild($table);

        $tr1 = $doc->createElement('tr');
        $table->appendChild($tr1);

        $td1 = $doc->createElement('td');
        $tr1->appendChild($td1);

        $td1_1 = $doc->createElement('td');
        $tr1->appendChild($td1_1);

        $td1_2 = $doc->createElement('td');
        $tr1->appendChild($td1_2);

        $title1 = $doc->createTextNode('This is title #1');
        $title2 = $doc->createTextNode('This is title #2');
        $title3 = $doc->createTextNode('This is title #3');

        $td1->appendChild($title1);
        $td1_1->appendChild($title2);
        $td1_2->appendChild($title3);

        echo $doc->saveXML();

?>

Body:
Do you know about SimpleXML? Especially: simplexml_load_string() which you can just pass a fragment of XML, and it'll convert it into an object:

$xml=simplexml_load_string("<an><element>This is text</element></an>");
echo $xml->element; // => This is text

Doesn't get easier than that. Unless you just concatenate strings and create a DOM Document from the resulting pseudo-XML to test if it's well-formed by checking the return value.


问:
Convert AVI video to MP4 video (for playback on iOS)
I have a video file, which is generated by a third party library, which is recording video from a remote camera.  This API generates a video file in AVI format @ 4fps and, the examples I have, at 352x288px

I've been trying to convert the video for playback in iOS.  I understand that iOS only supports a limited range of video formats and I've been trying to make anything work.

I tried to use the following, which is based on iOS Convert AVI to MP4 Format programatically ...

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
  }

  @IBAction func convert(_ sender: Any) {
    makeItSo()
  }

  func makeItSo() {

    guard let inputUrl = Bundle.main.url(forResource: "DVR8-4580V, Channel 7", withExtension: "avi") else {
      print("Could not find video source")
      return
    }

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("MyVideo.mp4").absoluteString
    let outputURL = URL(fileURLWithPath: filePath)
    print("OutputURL = \(outputURL)")
    convertVideoToLowQuailty(withInputURL: inputUrl, outputURL: outputURL, handler: { exportSession in
      guard let exportSession = exportSession else {
        print("No export session")
        return
      }
      print("exportSession.status = \(exportSession.status)")
      if exportSession.status == .completed {
        // Video conversation completed
        print("Video converstion completed")
      } else {
        print("Error = \(exportSession.error)")
      }
    })
  }

  func convertVideoToLowQuailty(withInputURL inputURL: URL?, outputURL: URL?, handler: @escaping (AVAssetExportSession?) -> Void) {
    if let anURL = outputURL {
      try? FileManager.default.removeItem(at: anURL)
    }
    var asset: AVURLAsset? = nil
    if let anURL = inputURL {
      asset = AVURLAsset(url: anURL, options: nil)
    }
    var exportSession: AVAssetExportSession? = nil
    if let anAsset = asset {
      exportSession = AVAssetExportSession(asset: anAsset, presetName: AVAssetExportPresetPassthrough)
    }
    exportSession?.outputURL = outputURL
    exportSession?.outputFileType = .mp4
    exportSession?.exportAsynchronously(completionHandler: {
      handler(exportSession)
    })
  }

}
</code>```

And several other variants, but they fail.  The above code fails with:

```<code>Error = Optional(Error Domain=AVFoundationErrorDomain Code=-11822 "Cannot Open" UserInfo={NSLocalizedFailureReason=This media format is not supported., NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x283244bd0 {Error Domain=NSOSStatusErrorDomain Code=-16976 "(null)"}})
</code>```

So I assume that either I'm not providing the correct options/suggestions to the converter or simply AVFoundation doesn't support this type of operation.

Below is the information generated by MediaInfo

```<code>General
Complete name                            : /Users/swhitehead/Downloads/DVR8-4580V, Channel 8.avi
Format                                   : AVI
Format/Info                              : Audio Video Interleave
File size                                : 361 KiB
Duration                                 : 28s 500ms
Overall bit rate                         : 104 Kbps

Video
ID                                       : 0
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : Baseline@L2
Format settings                          : 1 Ref Frames
Format settings, CABAC                   : No
Format settings, ReFrames                : 1 frame
Format settings, GOP                     : M=1, N=4
Codec ID                                 : H264
Duration                                 : 28s 500ms
Bit rate                                 : 101 Kbps
Width                                    : 352 pixels
Height                                   : 288 pixels
Display aspect ratio                     : 1.222
Frame rate                               : 4.000 fps
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Bits/(Pixel*Frame)                       : 0.249
Stream size                              : 351 KiB (97%)
</code>```

The Question

Is there some way that I can convert this type of video file to a support mp4 format which can played back by iOS?

nb: I appreciate that this potentially a broad question, as a simple solution may not exist, but even some suggestions or hints would be appreciated as it's driving me nuts

答:
Use video without “Format settings, GOP : M=1, N=4”.

When I use the video without GOP Format settings, it can be exported successfully.

Body:
I have a video file, which is generated by a third party library, which is recording video from a remote camera.  This API generates a video file in AVI format @ 4fps and, the examples I have, at 352x288px

I've been trying to convert the video for playback in iOS.  I understand that iOS only supports a limited range of video formats and I've been trying to make anything work.

I tried to use the following, which is based on iOS Convert AVI to MP4 Format programatically ...

import UIKit
import AVFoundation

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
  }

  @IBAction func convert(_ sender: Any) {
    makeItSo()
  }

  func makeItSo() {

    guard let inputUrl = Bundle.main.url(forResource: "DVR8-4580V, Channel 7", withExtension: "avi") else {
      print("Could not find video source")
      return
    }

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("MyVideo.mp4").absoluteString
    let outputURL = URL(fileURLWithPath: filePath)
    print("OutputURL = \(outputURL)")
    convertVideoToLowQuailty(withInputURL: inputUrl, outputURL: outputURL, handler: { exportSession in
      guard let exportSession = exportSession else {
        print("No export session")
        return
      }
      print("exportSession.status = \(exportSession.status)")
      if exportSession.status == .completed {
        // Video conversation completed
        print("Video converstion completed")
      } else {
        print("Error = \(exportSession.error)")
      }
    })
  }

  func convertVideoToLowQuailty(withInputURL inputURL: URL?, outputURL: URL?, handler: @escaping (AVAssetExportSession?) -> Void) {
    if let anURL = outputURL {
      try? FileManager.default.removeItem(at: anURL)
    }
    var asset: AVURLAsset? = nil
    if let anURL = inputURL {
      asset = AVURLAsset(url: anURL, options: nil)
    }
    var exportSession: AVAssetExportSession? = nil
    if let anAsset = asset {
      exportSession = AVAssetExportSession(asset: anAsset, presetName: AVAssetExportPresetPassthrough)
    }
    exportSession?.outputURL = outputURL
    exportSession?.outputFileType = .mp4
    exportSession?.exportAsynchronously(completionHandler: {
      handler(exportSession)
    })
  }

}

And several other variants, but they fail.  The above code fails with:

Error = Optional(Error Domain=AVFoundationErrorDomain Code=-11822 "Cannot Open" UserInfo={NSLocalizedFailureReason=This media format is not supported., NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x283244bd0 {Error Domain=NSOSStatusErrorDomain Code=-16976 "(null)"}})

So I assume that either I'm not providing the correct options/suggestions to the converter or simply AVFoundation doesn't support this type of operation.

Below is the information generated by MediaInfo

General
Complete name                            : /Users/swhitehead/Downloads/DVR8-4580V, Channel 8.avi
Format                                   : AVI
Format/Info                              : Audio Video Interleave
File size                                : 361 KiB
Duration                                 : 28s 500ms
Overall bit rate                         : 104 Kbps

Video
ID                                       : 0
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : Baseline@L2
Format settings                          : 1 Ref Frames
Format settings, CABAC                   : No
Format settings, ReFrames                : 1 frame
Format settings, GOP                     : M=1, N=4
Codec ID                                 : H264
Duration                                 : 28s 500ms
Bit rate                                 : 101 Kbps
Width                                    : 352 pixels
Height                                   : 288 pixels
Display aspect ratio                     : 1.222
Frame rate                               : 4.000 fps
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Bits/(Pixel*Frame)                       : 0.249
Stream size                              : 351 KiB (97%)

The Question

Is there some way that I can convert this type of video file to a support mp4 format which can played back by iOS?

nb: I appreciate that this potentially a broad question, as a simple solution may not exist, but even some suggestions or hints would be appreciated as it's driving me nuts


问:
Error when trying to connect to remote node in Corda OS4.4 [Connection closed due to error on remote side: CREATE_ADDRESS]
FYI, I am not using docker. Connecting directly to remote by updating the additional-node-infos directory with the remote node's nodeinfo. I am able to connect to the remote node from the local node. However the remote node is giving the following error:

Connection closed due to error on remote side: AMQ119032: User: SystemUsers/Peer does not have permission='CREATE_ADDRESS' on address p2p.inbound.DLCm69d1XjYRnqA64iizRneXMu8mv5CrnDugTF2rz42U55 {conn=[id: 0x43b26f57, L:/192.168.1.181:52874 - R:/192.168.1.171:10004],

答:
Wrapping up the answer:

You have to check the nodeinfo files and the network parameters of the nodes to make sure they are in the same network

The error message comes from artemis, the embedded message queue broker in Corda.

The artemis picks up the same CA from the node and so the nodes must share the same root CA

ie. The nodes have to be in the same Corda network.

Detail explanation: https://docs.corda.net/docs/corda-os/4.4/messaging.html#security


问:
Change image alpha from listview position and save
I'm making a music listview. I have a base adapter and music class music class have 3 property; name:String
point:String
image:Int
how can i change image alpha which item selected?

```<code>        listMusics.setOnItemClickListener { parent, view, position, id ->
        val preference = getSharedPreferences("PREFS",0)
        val editor = preference.edit()
        best1 = preference.getInt("best1", 0)
        if(best1>=position*100) {
            music = position
            view.imgMusic.alpha=1F
            editor.putInt("music", music)
            editor.apply()
        }

    }
</code>```

i'm changing image alpha with   view.imgMusic.alpha=1F it's change alpha to image but i can't save item alpha. i want to change alpha to 1F which item selected and save also change the other items to 0.5F how can i do this ?

答:
in adapter onBindViewHolder you can use this code</p>

```<code> holder.container.setOnClickListener(v -> {

        lastSelectedSong = position;

        //reset the color of all items and change color of new selected item
        notifyDataSetChanged();
    });

    //change icon and color of last Selected Song
    if (position == lastSelectedSong) {
        holder.container.setBackgroundColor(your_color);

           } else { //default color and icon of items
        holder.imageView.setBackgroundColor(Color.TRANSPARENT);
    }
</code>```

Body:
I'm making a music listview. I have a base adapter and music class music class have 3 property; name:String
point:String
image:Int
how can i change image alpha which item selected?

        listMusics.setOnItemClickListener { parent, view, position, id ->
        val preference = getSharedPreferences("PREFS",0)
        val editor = preference.edit()
        best1 = preference.getInt("best1", 0)
        if(best1>=position*100) {
            music = position
            view.imgMusic.alpha=1F
            editor.putInt("music", music)
            editor.apply()
        }

    }

i'm changing image alpha with   view.imgMusic.alpha=1F it's change alpha to image but i can't save item alpha. i want to change alpha to 1F which item selected and save also change the other items to 0.5F how can i do this ?

Body:
in adapter onBindViewHolder you can use this code

 holder.container.setOnClickListener(v -> {

        lastSelectedSong = position;

        //reset the color of all items and change color of new selected item
        notifyDataSetChanged();
    });

    //change icon and color of last Selected Song
    if (position == lastSelectedSong) {
        holder.container.setBackgroundColor(your_color);

           } else { //default color and icon of items
        holder.imageView.setBackgroundColor(Color.TRANSPARENT);
    }


问:
Calculating Percentages of Multiple Record Groups
Right now I am using this query to calculate the percentage of users who have given their email address, by dividing the count of emails by the count of user opt-ins:

```<code>SELECT cast(A.NUM as float)/cast(A.DENOM as float) * 100 AS Percentage
FROM (SELECT
(SELECT count(*)
FROM "public"."mv_fundraiser_report"
WHERE [[{{NonProfit}}]]
AND [[{{DateRange}}]]
AND "public"."mv_fundraiser_report"."Email" IS NOT NULL) AS NUM,

(SELECT count(*)
FROM "public"."mv_fundraiser_report"
WHERE "public"."mv_fundraiser_report"."opt-in" = TRUE
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]]) AS DENOM) A
</code>```

This is an example of my data:

```<code>NonProfit|User Name|Opt-In|Email
NP1.     |Hunter   |TRUE  |hunter@hunter.com
NP2.     |Hunter   |TRUE  |hunter@hunter.com
NP3.     |Hunter   |TRUE  |hunter@hunter.com
NP4.     |Hunter   |TRUE  |hunter@hunter.com
NP1.     |Hunter   |TRUE  |hunter@hunter.com
NP2.     |Hunter   |TRUE  |hunter@hunter.com
NP3.     |Hunter   |TRUE  |hunter@hunter.com
NP4.     |Hunter   |TRUE  |hunter@hunter.com
</code>```

What I would like to do is group these records by NonProfit, and then return multiple rows, each individually calculated based on the NonProfit. This is what my end data set should look like:

```<code>NonProfit|Email %
NP1.     |57
NP2.     |52
NP3.     |100
NP4.     |31
</code>```

From what I understand, window functions do not allow you to select multiple rows, so how could this outcome be achieved? Any help is appreciated, thanks!

答:
This should do the trick:

```<code>select
  NonProfit,
  sum(case when email is not null then 1 else 0 end) / count(*) * 100 as percentage
from mv_fundraiser_report
where opt_in and ...
group by NonProfit
</code>```

That's assuming you want to divide the number of opt-in users with email by the number of opt-in users, which is slightly different from your query above. If not, divide by sum(case when opt_in then 1 else 0 end) and drop the opt_in from the where condition.

Body:
Right now I am using this query to calculate the percentage of users who have given their email address, by dividing the count of emails by the count of user opt-ins:

SELECT cast(A.NUM as float)/cast(A.DENOM as float) * 100 AS Percentage
FROM (SELECT
(SELECT count(*)
FROM "public"."mv_fundraiser_report"
WHERE [[{{NonProfit}}]]
AND [[{{DateRange}}]]
AND "public"."mv_fundraiser_report"."Email" IS NOT NULL) AS NUM,

(SELECT count(*)
FROM "public"."mv_fundraiser_report"
WHERE "public"."mv_fundraiser_report"."opt-in" = TRUE
AND [[{{NonProfit}}]]
AND [[{{DateRange}}]]) AS DENOM) A

This is an example of my data:

NonProfit|User Name|Opt-In|Email
NP1.     |Hunter   |TRUE  |hunter@hunter.com
NP2.     |Hunter   |TRUE  |hunter@hunter.com
NP3.     |Hunter   |TRUE  |hunter@hunter.com
NP4.     |Hunter   |TRUE  |hunter@hunter.com
NP1.     |Hunter   |TRUE  |hunter@hunter.com
NP2.     |Hunter   |TRUE  |hunter@hunter.com
NP3.     |Hunter   |TRUE  |hunter@hunter.com
NP4.     |Hunter   |TRUE  |hunter@hunter.com

What I would like to do is group these records by NonProfit, and then return multiple rows, each individually calculated based on the NonProfit. This is what my end data set should look like:

NonProfit|Email %
NP1.     |57
NP2.     |52
NP3.     |100
NP4.     |31

From what I understand, window functions do not allow you to select multiple rows, so how could this outcome be achieved? Any help is appreciated, thanks!

Body:
This should do the trick:

select
  NonProfit,
  sum(case when email is not null then 1 else 0 end) / count(*) * 100 as percentage
from mv_fundraiser_report
where opt_in and ...
group by NonProfit

That's assuming you want to divide the number of opt-in users with email by the number of opt-in users, which is slightly different from your query above. If not, divide by sum(case when opt_in then 1 else 0 end) and drop the opt_in from the where condition.


问:
Angular 8 - Replace image URL with inline base64 on production build
I am trying to change all the images of a certain page from a file path to base64, I read that sens Angular 6 we can no longer add custom code to Webpack configurations, and I am not interested in using a custom builder like @angular-builders/custom-webpack as a solution.

is this possible?

Thanks in advance.

答:
You can create a Node script as the following:

```<code>const fs = require('fs');
const base64Img = require('base64-img');

fs.readFile('my/file/path', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  const matches = data.match(/assets\/.*?(svg|png)/g);
  matches.forEach(match => {
    try {
      if (fs.existsSync(match)) {
        const convertedImage = base64Img.base64Sync(match);
        data = data.replace(match, `${convertedImage}`);
      }
    } catch (err) {
      console.error('Error: File not found', match);
    }
  });

  fs.writeFile('my/destination/file', data, 'utf8', (err) => {
    if (err) {
      return console.error(err);
    }
  });
});
</code>```

In this way, it will get the file that you need to replace the files, search for the assets, then convert the images to base64 and replace them. The last step is to write the result to a new file.

To run this, you need to install base64-img library: npm i base64-img --save-dev. Afterwards, you can build the project and then run node include-images.js.

To make it easier, you can also add a script in your package.json, something like:

```<code>"replace-images": "ng build && node include-images.js"
</code>```

This can be run using: npm run replace-images

Please note that I don't prefer converting the images into base64 and include it in the bundle as it will make the bundle / bundles much bigger and will decrease your website performance.

Body:
You can create a Node script as the following:

const fs = require('fs');
const base64Img = require('base64-img');

fs.readFile('my/file/path', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  const matches = data.match(/assets\/.*?(svg|png)/g);
  matches.forEach(match => {
    try {
      if (fs.existsSync(match)) {
        const convertedImage = base64Img.base64Sync(match);
        data = data.replace(match, `${convertedImage}`);
      }
    } catch (err) {
      console.error('Error: File not found', match);
    }
  });

  fs.writeFile('my/destination/file', data, 'utf8', (err) => {
    if (err) {
      return console.error(err);
    }
  });
});

In this way, it will get the file that you need to replace the files, search for the assets, then convert the images to base64 and replace them. The last step is to write the result to a new file.

To run this, you need to install base64-img library: npm i base64-img --save-dev. Afterwards, you can build the project and then run node include-images.js.

To make it easier, you can also add a script in your package.json, something like:

"replace-images": "ng build && node include-images.js"

This can be run using: npm run replace-images

Please note that I don't prefer converting the images into base64 and include it in the bundle as it will make the bundle / bundles much bigger and will decrease your website performance.


问:
Display Image using Image Path isn't Working
I saved user image to a folder in my wwwroot folder and saved the image path to my database, Razor Pages, now i want to display the same image using the image path, its not working.

Here is my code to save the image

```<code>if (Imagefile != null && Imagefile.Length > 0)
            {
                var imgpath = @"\Upload\pkgimages\";
                var uploadpth = _env.WebRootPath + imgpath;

                //Create Directory
                if (!Directory.Exists(uploadpth))
                {
                    Directory.CreateDirectory(uploadpth);
                }
                //create file
                var uniqueFilename = Guid.NewGuid().ToString();
                var filename = Path.GetFileName(uniqueFilename + "." + Imagefile.FileName.Split(".")[1].ToLower());
                string fullPath = Path.Combine(uploadpth, filename);
                using (var filestream = new FileStream(fullPath, FileMode.Create))
                {
                    Input.ImagePath = fullPath;
                    await Imagefile.CopyToAsync(filestream);
                }
            }

            var today = DateTime.Now;
            var exp = today.AddDays(Input.Duration);
            Input.expDate = exp;
            var pkg= new UserPackages
            {
                Title = Input.Title,
                BeginDate = DateTime.Now,
                ExpDate=Input.expDate,
                Status = "Pending",
                PackageID = pckID,
                UserID = Loginuser,
                ImagePath = Input.ImagePath
            };
            await _userPackageDataService.AddUserPackage(pkg)
</code>```

It saves everything correctly to their respective places now to retrieve the these details back and display the uploaded image

here is my code

```<code> public async Task OnGetAsync(string ID)
    {
        Guid _pkgID = Guid.Parse(ID);
        var package= await _userPackageDataService.ReviewPackage(_pkgID);
        var result= _mapper.Map<packageDTO>(package);
        UserPackage= result;
    }
</code>```

then in my chtml file I have this markup

```<code>  <div class="col-sm-6">
            <img src="@Model.UserPackage.ImagePath" alt="Image" style="width:200px; height:200px;" />
        </div>
</code>```

I have also tried

```<code> <div class="col-sm-6">
            <img src="@Uri.Content(Model.UserPackage.ImagePath)" alt="Image" style="width:200px; height:200px;" />
        </div>
</code>```

It returns the full image path wish was saved to the database but image is not rendered on the browser, please what am i missing out here?
Thanks

答:
The src attribute of an img element expects either a relative or full URL to the image, not a file path.

Assuming that your image folder is in wwwroot, try this instead:

```<code><img src="/upload/pkgimages/@(Path.GetFileName(Model.UserPackage.ImagePath))" alt="Image" style="width:200px; height:200px;" />
</code>```

Body:
I saved user image to a folder in my wwwroot folder and saved the image path to my database, Razor Pages, now i want to display the same image using the image path, its not working.

Here is my code to save the image

if (Imagefile != null && Imagefile.Length > 0)
            {
                var imgpath = @"\Upload\pkgimages\";
                var uploadpth = _env.WebRootPath + imgpath;

                //Create Directory
                if (!Directory.Exists(uploadpth))
                {
                    Directory.CreateDirectory(uploadpth);
                }
                //create file
                var uniqueFilename = Guid.NewGuid().ToString();
                var filename = Path.GetFileName(uniqueFilename + "." + Imagefile.FileName.Split(".")[1].ToLower());
                string fullPath = Path.Combine(uploadpth, filename);
                using (var filestream = new FileStream(fullPath, FileMode.Create))
                {
                    Input.ImagePath = fullPath;
                    await Imagefile.CopyToAsync(filestream);
                }
            }

            var today = DateTime.Now;
            var exp = today.AddDays(Input.Duration);
            Input.expDate = exp;
            var pkg= new UserPackages
            {
                Title = Input.Title,
                BeginDate = DateTime.Now,
                ExpDate=Input.expDate,
                Status = "Pending",
                PackageID = pckID,
                UserID = Loginuser,
                ImagePath = Input.ImagePath
            };
            await _userPackageDataService.AddUserPackage(pkg)

It saves everything correctly to their respective places now to retrieve the these details back and display the uploaded image

here is my code

 public async Task OnGetAsync(string ID)
    {
        Guid _pkgID = Guid.Parse(ID);
        var package= await _userPackageDataService.ReviewPackage(_pkgID);
        var result= _mapper.Map<packageDTO>(package);
        UserPackage= result;
    }

then in my chtml file I have this markup

I have also tried

It returns the full image path wish was saved to the database but image is not rendered on the browser, please what am i missing out here?
Thanks

Body:
The src attribute of an img element expects either a relative or full URL to the image, not a file path.

Assuming that your image folder is in wwwroot, try this instead:

<img src="/upload/pkgimages/@(Path.GetFileName(Model.UserPackage.ImagePath))" alt="Image" style="width:200px; height:200px;" />


问:
Upgrading to Gradle version 4.0.0 broke R8 code shrinking
I have upgraded my gradle version to 4.0.0 from 3.6.3. Android Studio was able to install the app properly when minifyenabled was true and gradle version was 3.6.3 without any issues. On gradle version 4.0.0 and minifyenabled set to true doesn't even install the application. Here is what I see:

```<code>Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK

List of apks:
[0] 'C:\Users\user\Desktop\Projects\Application\app\build\outputs\apk\debug\app-debug.apk'
[1] 'C:\Users\user\Desktop\Projects\Application\module1\build\outputs\apk\debug\module1-debug.apk'
[2] 'C:\Users\user\Desktop\Projects\Application\module2\build\outputs\apk\debug\module2-debug.apk'
[3] 'C:\Users\user\Desktop\Projects\Application\module3\build\outputs\apk\debug\module3-debug.apk'
[4] 'C:\Users\user\Desktop\Projects\Application\module4\build\outputs\apk\debug\module4-debug.apk'
[5] 'C:\Users\user\Desktop\Projects\Application\module5\build\outputs\apk\debug\module5-debug.apk'
The APKs are invalid.
</code>```

build.gradle file:

```<code>android {
    compileSdkVersion androidDependencies.compile_sdk_version
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.pills.mydemoapplication"
        minSdkVersion androidDependencies.min_sdk_version
        targetSdkVersion androidDependencies.target_sdk_version
        versionCode 7
        versionName "5.0.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildTypes {
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures{
        dataBinding = true
    }
    dynamicFeatures = [":module1", ":module2", ":module3", ":module4", ":module5"]
}
</code>```

Project level build.gradle

```<code>buildscript {
    ext.kotlin_version = '1.3.72'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath "com.android.tools:r8:1.6.84"
        classpath "com.android.tools.build:gradle:4.0.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-beta01"
    }
}
</code>```

答:
Make sure all your libraries and classpaths are up to date. I had a classpath for firebase-plugins that was out of date. This problem occurred when using the new gradle. After updating the classpath, everything looks fine.

In my case. I changed this

classpath 'com.google.firebase:firebase-plugins:1.1.0'

to this

classpath 'com.google.firebase:perf-plugin:1.3.1'

Body:
I have upgraded my gradle version to 4.0.0 from 3.6.3. Android Studio was able to install the app properly when minifyenabled was true and gradle version was 3.6.3 without any issues. On gradle version 4.0.0 and minifyenabled set to true doesn't even install the application. Here is what I see:

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK

List of apks:
[0] 'C:\Users\user\Desktop\Projects\Application\app\build\outputs\apk\debug\app-debug.apk'
[1] 'C:\Users\user\Desktop\Projects\Application\module1\build\outputs\apk\debug\module1-debug.apk'
[2] 'C:\Users\user\Desktop\Projects\Application\module2\build\outputs\apk\debug\module2-debug.apk'
[3] 'C:\Users\user\Desktop\Projects\Application\module3\build\outputs\apk\debug\module3-debug.apk'
[4] 'C:\Users\user\Desktop\Projects\Application\module4\build\outputs\apk\debug\module4-debug.apk'
[5] 'C:\Users\user\Desktop\Projects\Application\module5\build\outputs\apk\debug\module5-debug.apk'
The APKs are invalid.

build.gradle file:

android {
    compileSdkVersion androidDependencies.compile_sdk_version
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.pills.mydemoapplication"
        minSdkVersion androidDependencies.min_sdk_version
        targetSdkVersion androidDependencies.target_sdk_version
        versionCode 7
        versionName "5.0.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildTypes {
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures{
        dataBinding = true
    }
    dynamicFeatures = [":module1", ":module2", ":module3", ":module4", ":module5"]
}

Project level build.gradle

buildscript {
    ext.kotlin_version = '1.3.72'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath "com.android.tools:r8:1.6.84"
        classpath "com.android.tools.build:gradle:4.0.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.0-beta01"
    }
}


问:
How to get logged in user in multiple websites OpenIdConnect Azure AD B2C?
I want to use OpenIdConnectAuthentication for multiple projects. I'm using following code to authenticate user in my website1 which is working fine but how can I access and manage that in website2 same access token to authenticate user in another website?

```<code>public void ConfigureAuth(IAppBuilder app) {
// Required for Azure webapps, as by default they force TLS 1.2 and this project attempts 1.0
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
    // Generate the metadata address using the tenant and policy information
    MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

    // These are standard OpenID Connect parameters, with values pulled from web.config
    ClientId = Globals.ClientId,
    RedirectUri = Globals.RedirectUri,
    PostLogoutRedirectUri = Globals.RedirectUri,
    AuthenticationType = Globals.DefaultPolicy,
    // Specify the callbacks for each type of notifications
    Notifications = new OpenIdConnectAuthenticationNotifications {
        RedirectToIdentityProvider = OnRedirectToIdentityProvider,
        AuthorizationCodeReceived = OnAuthorizationCodeReceived,
        AuthenticationFailed = OnAuthenticationFailed,
    },
    Scope = "openid",
    ResponseType = "id_token",
    // Specify the claim type that specifies the Name property.
    TokenValidationParameters = new TokenValidationParameters {
        NameClaimType = "name",
        SaveSigninToken = true,
        ValidateIssuer = false
    }//,

    // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
    //Scope = $"openid profile offline_access {Globals.ReadTasksScope} {Globals.WriteT//asksScope}"
});
</code>```

Note: website 1 is MVC project and Website 2 is API project to authenticate api call. How can we manage that?

答:
I can see a couple of things you need to change in order to get this working. First thing, since this is a server application that you are using, you can use the authorization code flow or the hybrid flow to authenticate the user.

That can be achieved like this:

```<code>// for authorization code flow
ResponseType = "code",

// for hybrid flow
ResponseType = "code id_token"
</code>```

Note, when using this two flows, you will need to provide the client secret as well.

Once the user is authenticated on the identity provider, it will get redirected back to your application with an authorization code that you can use to exchange it for access_token and refresh_token.

So, in the OnRedirectToIdentityProvider method

```<code>OnAuthorizationCodeReceived = async n =>
{
    // swap authorization code for an access token
    // i think for AAD B2C the endpoint for retreiving tokens is (not sure though you'll need to double check)
    // https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy-name>/oauth2/v2.0/token
    var tokenClient = new TokenClient("http://localhost:5000/connect/token", Globals.ClientId, Globals.ClientSecret);
    var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                    n.Code, n.RedirectUri);

    // use access token to call the user info endpoint
    // also check what the userinfo endpoint URL is
    var userInfoClient = new UserInfoClient("http://localhost:5000/connect/userinfo");
    var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

    // create a new identity using the claims from the user info endpoint (including tokens)
    var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
    id.AddClaims(userInfoResponse.Claims);
    id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
    id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

    n.AuthenticationTicket = new AuthenticationTicket(
                    new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType),
                    n.AuthenticationTicket.Properties);
}
</code>```

You can get all of the URLs that you need from the metadata endpoint.

Once you do all of this, the access token will be a part of the user claims, and it will be stored in the auth cookie.

Then, once you do all of that you can use the access_token to call the protected API, provided on your API you have JwtBearerAuthentication set up, by providing the access_token in the header of the request to said API.

The TokenClient class is part of a library called IdentityModel which makes it easier to communicate with openidconnect endpoints

Body:
I want to use OpenIdConnectAuthentication for multiple projects. I'm using following code to authenticate user in my website1 which is working fine but how can I access and manage that in website2 same access token to authenticate user in another website?

public void ConfigureAuth(IAppBuilder app) {
// Required for Azure webapps, as by default they force TLS 1.2 and this project attempts 1.0
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions {
    // Generate the metadata address using the tenant and policy information
    MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

    // These are standard OpenID Connect parameters, with values pulled from web.config
    ClientId = Globals.ClientId,
    RedirectUri = Globals.RedirectUri,
    PostLogoutRedirectUri = Globals.RedirectUri,
    AuthenticationType = Globals.DefaultPolicy,
    // Specify the callbacks for each type of notifications
    Notifications = new OpenIdConnectAuthenticationNotifications {
        RedirectToIdentityProvider = OnRedirectToIdentityProvider,
        AuthorizationCodeReceived = OnAuthorizationCodeReceived,
        AuthenticationFailed = OnAuthenticationFailed,
    },
    Scope = "openid",
    ResponseType = "id_token",
    // Specify the claim type that specifies the Name property.
    TokenValidationParameters = new TokenValidationParameters {
        NameClaimType = "name",
        SaveSigninToken = true,
        ValidateIssuer = false
    }//,

    // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
    //Scope = $"openid profile offline_access {Globals.ReadTasksScope} {Globals.WriteT//asksScope}"
});

Note: website 1 is MVC project and Website 2 is API project to authenticate api call. How can we manage that?

Body:
I can see a couple of things you need to change in order to get this working. First thing, since this is a server application that you are using, you can use the authorization code flow or the hybrid flow to authenticate the user.

That can be achieved like this:

// for authorization code flow
ResponseType = "code",

// for hybrid flow
ResponseType = "code id_token"

Note, when using this two flows, you will need to provide the client secret as well.

Once the user is authenticated on the identity provider, it will get redirected back to your application with an authorization code that you can use to exchange it for access_token and refresh_token.

So, in the OnRedirectToIdentityProvider method

OnAuthorizationCodeReceived = async n =>
{
    // swap authorization code for an access token
    // i think for AAD B2C the endpoint for retreiving tokens is (not sure though you'll need to double check)
    // https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy-name>/oauth2/v2.0/token
    var tokenClient = new TokenClient("http://localhost:5000/connect/token", Globals.ClientId, Globals.ClientSecret);
    var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
                    n.Code, n.RedirectUri);

    // use access token to call the user info endpoint
    // also check what the userinfo endpoint URL is
    var userInfoClient = new UserInfoClient("http://localhost:5000/connect/userinfo");
    var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

    // create a new identity using the claims from the user info endpoint (including tokens)
    var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
    id.AddClaims(userInfoResponse.Claims);
    id.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
    id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

    n.AuthenticationTicket = new AuthenticationTicket(
                    new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType),
                    n.AuthenticationTicket.Properties);
}

You can get all of the URLs that you need from the metadata endpoint.

Once you do all of this, the access token will be a part of the user claims, and it will be stored in the auth cookie.

Then, once you do all of that you can use the access_token to call the protected API, provided on your API you have JwtBearerAuthentication set up, by providing the access_token in the header of the request to said API.

The TokenClient class is part of a library called IdentityModel which makes it easier to communicate with openidconnect endpoints


问:
model not showing up in django admin
I have ceated several django apps and stuffs for my own fun and so far everything has been working fine.

Now I just created new project (django 1.2.1) and have run into trouble from 1st moments.

I created new app - game and new model Game. I created admin.py and put related stuff into it. Ran syncdb and went to check into admin. Model did not show up there.

I proceeded to check and doublecheck and read through previous similar threads:
Registered models do not show up in admin
Django App Not Showing up in Admin Interface

But as far as I can tell, they don't help me either. Perhaps someone else can point this out for me.

models.py in game app:

```<code># -*- coding: utf-8 -*-
from django.db import models

class Game(models.Model):
      type = models.IntegerField(blank=False, null=False, default=1)
      teamone = models.CharField(max_length=100, blank=False, null=False)
      teamtwo = models.CharField(max_length=100, blank=False, null=False)
      gametime = models.DateTimeField(blank=False, null=False)
</code>```

admin.py in game app:

```<code># -*- coding: utf-8 -*-
from jalka.game.models import Game
from django.contrib import admin

class GameAdmin(admin.ModelAdmin):
      list_display    = ['type', 'teamone', 'teamtwo', 'gametime']

admin.site.register(Game, GameAdmin)
</code>```

project settings.py:

```<code>MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'jalka.urls'

TEMPLATE_DIRS = (
      "/home/projects/jalka/templates/"
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'game',
)
</code>```

urls.py:

```<code>from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
      # Example:
      # (r'^jalka/', include('jalka.foo.urls')),
      (r'^admin/', include(admin.site.urls)),
)
</code>```

答:
Another thing to point out is that you should make sure you're signed in with a superuser.

It could be that you are signed in with a user who has limited permission on view capacity so try that.

I in Django 2.0 I still register my app using just the name of the app i.e 'game'. But the issue was in the logged in user permissions.

Title: model not showing up in django admin

Body:
I have ceated several django apps and stuffs for my own fun and so far everything has been working fine.

Now I just created new project (django 1.2.1) and have run into trouble from 1st moments.

I created new app - game and new model Game. I created admin.py and put related stuff into it. Ran syncdb and went to check into admin. Model did not show up there.

I proceeded to check and doublecheck and read through previous similar threads:
Registered models do not show up in admin
Django App Not Showing up in Admin Interface

But as far as I can tell, they don't help me either. Perhaps someone else can point this out for me.

models.py in game app:

# -*- coding: utf-8 -*-
from django.db import models

class Game(models.Model):
      type = models.IntegerField(blank=False, null=False, default=1)
      teamone = models.CharField(max_length=100, blank=False, null=False)
      teamtwo = models.CharField(max_length=100, blank=False, null=False)
      gametime = models.DateTimeField(blank=False, null=False)

admin.py in game app:

# -*- coding: utf-8 -*-
from jalka.game.models import Game
from django.contrib import admin

class GameAdmin(admin.ModelAdmin):
      list_display    = ['type', 'teamone', 'teamtwo', 'gametime']

admin.site.register(Game, GameAdmin)

project settings.py:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'jalka.urls'

TEMPLATE_DIRS = (
      "/home/projects/jalka/templates/"
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'game',
)

urls.py:

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
      # Example:
      # (r'^jalka/', include('jalka.foo.urls')),
      (r'^admin/', include(admin.site.urls)),
)


问:
Detect if player is hit by shadow unity2D
I'm making a 2D game that the player can't touch the light source, so I typed the light code :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shadow2DLight : MonoBehaviour
{
    public float range = 5.0f;
    public float intensity = 1.0f;
    public Color color = Color.white;

    //Internal fields, cache V and P matrix for this frame.
    internal Matrix4x4[] V = new Matrix4x4[4];  //Four matricies for right, down, left ,up
    internal Matrix4x4 P;

    public static List<Shadow2DLight> lights = new List<Shadow2DLight>();
    // Start is called before the first frame update
    private void OnEnable() {
        lights.Add(this);
    }

    private void OnDisable() {
        lights.Remove(this);
    }
}

</code>```

then the block code :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

[RequireComponent(typeof(SpriteRenderer))]
public class Shadow2DCaster : MonoBehaviour
{
    private new SpriteRenderer renderer;
    private Mesh shadowMesh;
    private void Awake() {
        renderer = GetComponent<SpriteRenderer>();
        shadowMesh = new Mesh();
        shadowMesh.vertices = renderer.sprite.vertices.Select(t => new Vector3(t.x, t.y, 0.0f)).ToArray();
        var originalTriangles = renderer.sprite.triangles;
        var newTriangleIndicies = new List<int>();
        for (int i = 0; i < originalTriangles.Length / 3; i++) {
            newTriangleIndicies.Add(originalTriangles[3 * i]);
            newTriangleIndicies.Add(originalTriangles[3 * i + 1]);

            newTriangleIndicies.Add(originalTriangles[3 * i + 1]);
            newTriangleIndicies.Add(originalTriangles[3 * i + 2]);

            newTriangleIndicies.Add(originalTriangles[3 * i + 2]);
            newTriangleIndicies.Add(originalTriangles[3 * i]);
        }
        shadowMesh.SetIndices(newTriangleIndicies.ToArray(), MeshTopology.Lines, 0);
        shadowMesh.UploadMeshData(true);
    }

    public Mesh GetLineMesh() {
        return shadowMesh;
    }

    public static List<Shadow2DCaster> casters = new List<Shadow2DCaster>();
    private static Dictionary<Sprite, Mesh> shadowMeshCache;

    private void OnEnable() {
        casters.Add(this);
    }

    private void OnDisable() {
        casters.Remove(this);
    }
}
</code>```

then the Shadow2DPipeline code :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

[RequireComponent(typeof(Camera))]
public class Shadow2DPipeline : MonoBehaviour {
    private Material shadowMapMaterial;
    private Material lightingMaterial;
    private RenderTexture shadowMap;
    private CommandBuffer shadowMapCmdBuffer;
    private CommandBuffer lightingCmdBuffer;
    private MaterialPropertyBlock propertyBlock;
    private Mesh lightingQuad;

    private const int MAX_LIGHTS_COUNT = 64;
    private const int SHADOW_MAP_WIDTH = 256;
    private int ShadowMapHeight {
        get {
            return MAX_LIGHTS_COUNT * 4;
        }
    }

    private void Start() {
        propertyBlock = new MaterialPropertyBlock();
        shadowMap = new RenderTexture(SHADOW_MAP_WIDTH, ShadowMapHeight, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
        shadowMap.filterMode = FilterMode.Point;
        shadowMap.antiAliasing = 1;
        shadowMap.anisoLevel = 0;
        shadowMapMaterial = new Material(Resources.Load<Shader>("2DShadowMap"));
        lightingMaterial = new Material(Resources.Load<Shader>("2DAdditiveLight"));
        {
            lightingQuad = new Mesh();
            lightingQuad.vertices = new Vector3[] {
                new Vector3(-1.0f, -1.0f),
                new Vector3(-1.0f, 1.0f),
                new Vector3(1.0f, -1.0f),
                new Vector3(1.0f, 1.0f),
            };
            lightingQuad.triangles = new int[] {
                0, 1, 2, 2, 1, 3
            };
            lightingQuad.UploadMeshData(true);
        }
    }

    private void OnPreRender() {

        var cam = GetComponent<Camera>();
        var shadowCasters = Shadow2DCaster.casters;
        var lights = Shadow2DLight.lights;

        {   //Update shadow map rendering command buffer.
            if (shadowMapCmdBuffer == null) {
                shadowMapCmdBuffer = new CommandBuffer();
                cam.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, shadowMapCmdBuffer);
            }
            shadowMapCmdBuffer.Clear();
            /*
             * Shadow caster mesh is line-strip mesh.
             *
             * In shadow map, each 4 rows belong to one light, corresponding to depth in (0, 90), (90, 180)...(270, 360).
             *
             * To render shadow mesh at correct position, a naive MVP matrix is used.
             * Then, after transforming to clip space, manually edit y component to the corresponding row.
             */
            shadowMapCmdBuffer.SetRenderTarget(shadowMap);
            shadowMapCmdBuffer.ClearRenderTarget(true, true, Color.black);
            shadowMapCmdBuffer.SetGlobalVector(ShaderKeys.ShadowMap2DSize, new Vector4(1.0f / shadowMap.width, 1.0f / shadowMap.height, shadowMap.width, shadowMap.height));

            //Calculate V and P for each light.
            foreach (var light in lights) {
                for (int i = 0; i < 4; i++) {   //four directions.

                    //This TRS here calculates light->world matrix.
                    //The Quaternion.Euler(90.0f * i, 90.0f, 270.0f) aligns light to right, down, left, up.
                    //-1.0f in z-component in scale corrects camera forward direction.
                    var V = Matrix4x4.TRS(light.transform.position, Quaternion.Euler(90.0f * i, 90.0f, 270.0f), new Vector3(1.0f, 1.0f, -1.0f));
                    //Inverse it, so it's a world->light matrix.
                    V = V.inverse;

                    var P = Matrix4x4.Perspective(90.0f, 1.0f, 0.01f, 10.0f);
                    P = GL.GetGPUProjectionMatrix(P, true);
                    light.V[i] = V;
                    light.P = P;
                }
            }

            foreach (var shadowCaster in shadowCasters) {
                var M = shadowCaster.transform.localToWorldMatrix;
                for (int iLight = 0; iLight < Mathf.Min(MAX_LIGHTS_COUNT, lights.Count); iLight++) {
                    //Render shadow map of each light, by drawing shadow line mesh onto the shadowmap.
                    for (int iDir = 0; iDir < 4; iDir++) { //Four directions, right, down, left, up.

                        var light = lights[iLight];
                        var MVP = light.P * light.V[iDir] * M;

                        shadowMapCmdBuffer.SetGlobalMatrix(ShaderKeys.ShadowMap2DMVP, MVP);
                        float writeClipSpaceY = (iLight * 4 + iDir + 0.5f) / (float)(ShadowMapHeight);
                        shadowMapCmdBuffer.SetGlobalFloat(ShaderKeys.ShadowMap2DWriteRow, (writeClipSpaceY - 0.5f) * 2.0f);
                        shadowMapCmdBuffer.DrawMesh(shadowCaster.GetLineMesh(), Matrix4x4.identity /*Use our own MVP matrix*/, shadowMapMaterial);
                    }

                }
            }
        }

        {   //Update lighting command buffer.

            //Draw a "light quad" for each light.
            //
            //There's lots of ways to add light to 2d scene.
            //Here we just use an additive "layer"
            //Edit to what you like.
            if (lightingCmdBuffer == null) {
                lightingCmdBuffer = new CommandBuffer();
                lightingCmdBuffer.name = "2D Lighting";
                cam.AddCommandBuffer(CameraEvent.AfterForwardAlpha, lightingCmdBuffer);
            }
            lightingCmdBuffer.Clear();

            lightingCmdBuffer.SetGlobalTexture(ShaderKeys.ShadowMap2D, shadowMap);
            for (int iLight = 0; iLight < Mathf.Min(MAX_LIGHTS_COUNT, lights.Count); iLight++) {
                var light = lights[iLight];
                lightingCmdBuffer.SetGlobalVector(ShaderKeys.LightParams, new Vector4(light.range, light.intensity, light.transform.position.x, light.transform.position.y));
                lightingCmdBuffer.SetGlobalVector(ShaderKeys.LightColor, light.color);

                lightingCmdBuffer.SetGlobalFloat(ShaderKeys.ShadowMap2DLightIndex, (float)iLight);
                for (int iVP = 0; iVP < ShaderKeys._ShadowMap2DVP.Length; iVP++) {
                    lightingCmdBuffer.SetGlobalMatrix(ShaderKeys._ShadowMap2DVP[iVP], light.P * light.V[iVP]);
                }
                var M = Matrix4x4.TRS(light.transform.position, Quaternion.identity, Vector3.one * light.range);
                lightingCmdBuffer.SetGlobalMatrix(ShaderKeys.LightM, M);
                lightingCmdBuffer.DrawMesh(lightingQuad, M, lightingMaterial);
            }
        }
    }

    public static class ShaderKeys {
        public static int ShadowMap2DSize = Shader.PropertyToID("_ShadowMap2DSize");
        public static int ShadowMap2DMVP = Shader.PropertyToID("_ShadowMap2DMVP");
        public static int ShadowMap2DWriteRow = Shader.PropertyToID("_ShadowMap2DWriteRow");
        public static int ShadowMap2D = Shader.PropertyToID("_ShadowMap2D");
        public static int ShadowMap2DLightIndex = Shader.PropertyToID("_ShadowMap2DLightIndex");
        public static int[] _ShadowMap2DVP = new int[] {
            Shader.PropertyToID("_ShadowMap2DVP_Right"),
            Shader.PropertyToID("_ShadowMap2DVP_Down"),
            Shader.PropertyToID("_ShadowMap2DVP_Left"),
            Shader.PropertyToID("_ShadowMap2DVP_Up"),
        };
        public static int LightM = Shader.PropertyToID("_LightM");
        public static int LightParams = Shader.PropertyToID("_LightParams");
        public static int LightColor = Shader.PropertyToID("_LightColor");
    }
}
</code>```

but how i can detect if the player touch the light??
you can get the source code from here : https://github.com/yangrc1234/Unity2DShadowMap

preview from here : https://i.stack.imgur.com/oGgr2.gif

答:
So one solution would be not to directly detect any shadows, but leverage the essential properties of shadows to get the same effect.

An area that is in shadow is in shadow because there is an opaque object between it and the light source.

An area that is in light is in light because there are no objects between it and the light source.

Therefore you can simply detect if there is an object between your player and the light source using a raycast and use that information to determine if you are in shadow/light.

Very roughly:

```<code>Vector3 playerToLight = light.transform.position - player.transform.position;
float distance = playerToLight.magnitude;
vctor3 origin = player.transform.position;
vector3 direction = playerToLight.normalized;

if(Physics.Raycast(origin,direction,distance)){
    // in shadow
} else {
    // in light
}
</code>```

Body:
I'm making a 2D game that the player can't touch the light source, so I typed the light code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shadow2DLight : MonoBehaviour
{
    public float range = 5.0f;
    public float intensity = 1.0f;
    public Color color = Color.white;

    //Internal fields, cache V and P matrix for this frame.
    internal Matrix4x4[] V = new Matrix4x4[4];  //Four matricies for right, down, left ,up
    internal Matrix4x4 P;

    public static List<Shadow2DLight> lights = new List<Shadow2DLight>();
    // Start is called before the first frame update
    private void OnEnable() {
        lights.Add(this);
    }

    private void OnDisable() {
        lights.Remove(this);
    }
}

then the block code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

[RequireComponent(typeof(SpriteRenderer))]
public class Shadow2DCaster : MonoBehaviour
{
    private new SpriteRenderer renderer;
    private Mesh shadowMesh;
    private void Awake() {
        renderer = GetComponent<SpriteRenderer>();
        shadowMesh = new Mesh();
        shadowMesh.vertices = renderer.sprite.vertices.Select(t => new Vector3(t.x, t.y, 0.0f)).ToArray();
        var originalTriangles = renderer.sprite.triangles;
        var newTriangleIndicies = new List<int>();
        for (int i = 0; i < originalTriangles.Length / 3; i++) {
            newTriangleIndicies.Add(originalTriangles[3 * i]);
            newTriangleIndicies.Add(originalTriangles[3 * i + 1]);

            newTriangleIndicies.Add(originalTriangles[3 * i + 1]);
            newTriangleIndicies.Add(originalTriangles[3 * i + 2]);

            newTriangleIndicies.Add(originalTriangles[3 * i + 2]);
            newTriangleIndicies.Add(originalTriangles[3 * i]);
        }
        shadowMesh.SetIndices(newTriangleIndicies.ToArray(), MeshTopology.Lines, 0);
        shadowMesh.UploadMeshData(true);
    }

    public Mesh GetLineMesh() {
        return shadowMesh;
    }

    public static List<Shadow2DCaster> casters = new List<Shadow2DCaster>();
    private static Dictionary<Sprite, Mesh> shadowMeshCache;

    private void OnEnable() {
        casters.Add(this);
    }

    private void OnDisable() {
        casters.Remove(this);
    }
}

then the Shadow2DPipeline code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

[RequireComponent(typeof(Camera))]
public class Shadow2DPipeline : MonoBehaviour {
    private Material shadowMapMaterial;
    private Material lightingMaterial;
    private RenderTexture shadowMap;
    private CommandBuffer shadowMapCmdBuffer;
    private CommandBuffer lightingCmdBuffer;
    private MaterialPropertyBlock propertyBlock;
    private Mesh lightingQuad;

    private const int MAX_LIGHTS_COUNT = 64;
    private const int SHADOW_MAP_WIDTH = 256;
    private int ShadowMapHeight {
        get {
            return MAX_LIGHTS_COUNT * 4;
        }
    }

    private void Start() {
        propertyBlock = new MaterialPropertyBlock();
        shadowMap = new RenderTexture(SHADOW_MAP_WIDTH, ShadowMapHeight, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
        shadowMap.filterMode = FilterMode.Point;
        shadowMap.antiAliasing = 1;
        shadowMap.anisoLevel = 0;
        shadowMapMaterial = new Material(Resources.Load<Shader>("2DShadowMap"));
        lightingMaterial = new Material(Resources.Load<Shader>("2DAdditiveLight"));
        {
            lightingQuad = new Mesh();
            lightingQuad.vertices = new Vector3[] {
                new Vector3(-1.0f, -1.0f),
                new Vector3(-1.0f, 1.0f),
                new Vector3(1.0f, -1.0f),
                new Vector3(1.0f, 1.0f),
            };
            lightingQuad.triangles = new int[] {
                0, 1, 2, 2, 1, 3
            };
            lightingQuad.UploadMeshData(true);
        }
    }

    private void OnPreRender() {

        var cam = GetComponent<Camera>();
        var shadowCasters = Shadow2DCaster.casters;
        var lights = Shadow2DLight.lights;

        {   //Update shadow map rendering command buffer.
            if (shadowMapCmdBuffer == null) {
                shadowMapCmdBuffer = new CommandBuffer();
                cam.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, shadowMapCmdBuffer);
            }
            shadowMapCmdBuffer.Clear();
            /*
             * Shadow caster mesh is line-strip mesh.
             *
             * In shadow map, each 4 rows belong to one light, corresponding to depth in (0, 90), (90, 180)...(270, 360).
             *
             * To render shadow mesh at correct position, a naive MVP matrix is used.
             * Then, after transforming to clip space, manually edit y component to the corresponding row.
             */
            shadowMapCmdBuffer.SetRenderTarget(shadowMap);
            shadowMapCmdBuffer.ClearRenderTarget(true, true, Color.black);
            shadowMapCmdBuffer.SetGlobalVector(ShaderKeys.ShadowMap2DSize, new Vector4(1.0f / shadowMap.width, 1.0f / shadowMap.height, shadowMap.width, shadowMap.height));

            //Calculate V and P for each light.
            foreach (var light in lights) {
                for (int i = 0; i < 4; i++) {   //four directions.

                    //This TRS here calculates light->world matrix.
                    //The Quaternion.Euler(90.0f * i, 90.0f, 270.0f) aligns light to right, down, left, up.
                    //-1.0f in z-component in scale corrects camera forward direction.
                    var V = Matrix4x4.TRS(light.transform.position, Quaternion.Euler(90.0f * i, 90.0f, 270.0f), new Vector3(1.0f, 1.0f, -1.0f));
                    //Inverse it, so it's a world->light matrix.
                    V = V.inverse;

                    var P = Matrix4x4.Perspective(90.0f, 1.0f, 0.01f, 10.0f);
                    P = GL.GetGPUProjectionMatrix(P, true);
                    light.V[i] = V;
                    light.P = P;
                }
            }

            foreach (var shadowCaster in shadowCasters) {
                var M = shadowCaster.transform.localToWorldMatrix;
                for (int iLight = 0; iLight < Mathf.Min(MAX_LIGHTS_COUNT, lights.Count); iLight++) {
                    //Render shadow map of each light, by drawing shadow line mesh onto the shadowmap.
                    for (int iDir = 0; iDir < 4; iDir++) { //Four directions, right, down, left, up.

                        var light = lights[iLight];
                        var MVP = light.P * light.V[iDir] * M;

                        shadowMapCmdBuffer.SetGlobalMatrix(ShaderKeys.ShadowMap2DMVP, MVP);
                        float writeClipSpaceY = (iLight * 4 + iDir + 0.5f) / (float)(ShadowMapHeight);
                        shadowMapCmdBuffer.SetGlobalFloat(ShaderKeys.ShadowMap2DWriteRow, (writeClipSpaceY - 0.5f) * 2.0f);
                        shadowMapCmdBuffer.DrawMesh(shadowCaster.GetLineMesh(), Matrix4x4.identity /*Use our own MVP matrix*/, shadowMapMaterial);
                    }

                }
            }
        }

        {   //Update lighting command buffer.

            //Draw a "light quad" for each light.
            //
            //There's lots of ways to add light to 2d scene.
            //Here we just use an additive "layer"
            //Edit to what you like.
            if (lightingCmdBuffer == null) {
                lightingCmdBuffer = new CommandBuffer();
                lightingCmdBuffer.name = "2D Lighting";
                cam.AddCommandBuffer(CameraEvent.AfterForwardAlpha, lightingCmdBuffer);
            }
            lightingCmdBuffer.Clear();

            lightingCmdBuffer.SetGlobalTexture(ShaderKeys.ShadowMap2D, shadowMap);
            for (int iLight = 0; iLight < Mathf.Min(MAX_LIGHTS_COUNT, lights.Count); iLight++) {
                var light = lights[iLight];
                lightingCmdBuffer.SetGlobalVector(ShaderKeys.LightParams, new Vector4(light.range, light.intensity, light.transform.position.x, light.transform.position.y));
                lightingCmdBuffer.SetGlobalVector(ShaderKeys.LightColor, light.color);

                lightingCmdBuffer.SetGlobalFloat(ShaderKeys.ShadowMap2DLightIndex, (float)iLight);
                for (int iVP = 0; iVP < ShaderKeys._ShadowMap2DVP.Length; iVP++) {
                    lightingCmdBuffer.SetGlobalMatrix(ShaderKeys._ShadowMap2DVP[iVP], light.P * light.V[iVP]);
                }
                var M = Matrix4x4.TRS(light.transform.position, Quaternion.identity, Vector3.one * light.range);
                lightingCmdBuffer.SetGlobalMatrix(ShaderKeys.LightM, M);
                lightingCmdBuffer.DrawMesh(lightingQuad, M, lightingMaterial);
            }
        }
    }

    public static class ShaderKeys {
        public static int ShadowMap2DSize = Shader.PropertyToID("_ShadowMap2DSize");
        public static int ShadowMap2DMVP = Shader.PropertyToID("_ShadowMap2DMVP");
        public static int ShadowMap2DWriteRow = Shader.PropertyToID("_ShadowMap2DWriteRow");
        public static int ShadowMap2D = Shader.PropertyToID("_ShadowMap2D");
        public static int ShadowMap2DLightIndex = Shader.PropertyToID("_ShadowMap2DLightIndex");
        public static int[] _ShadowMap2DVP = new int[] {
            Shader.PropertyToID("_ShadowMap2DVP_Right"),
            Shader.PropertyToID("_ShadowMap2DVP_Down"),
            Shader.PropertyToID("_ShadowMap2DVP_Left"),
            Shader.PropertyToID("_ShadowMap2DVP_Up"),
        };
        public static int LightM = Shader.PropertyToID("_LightM");
        public static int LightParams = Shader.PropertyToID("_LightParams");
        public static int LightColor = Shader.PropertyToID("_LightColor");
    }
}

but how i can detect if the player touch the light??
you can get the source code from here : https://github.com/yangrc1234/Unity2DShadowMap

preview from here : https://i.stack.imgur.com/oGgr2.gif

Body:
So one solution would be not to directly detect any shadows, but leverage the essential properties of shadows to get the same effect.

An area that is in shadow is in shadow because there is an opaque object between it and the light source.

An area that is in light is in light because there are no objects between it and the light source.

Therefore you can simply detect if there is an object between your player and the light source using a raycast and use that information to determine if you are in shadow/light.

Very roughly:

Vector3 playerToLight = light.transform.position - player.transform.position;
float distance = playerToLight.magnitude;
vctor3 origin = player.transform.position;
vector3 direction = playerToLight.normalized;

if(Physics.Raycast(origin,direction,distance)){
    // in shadow
} else {
    // in light
}


问:
How to print Jasper report programmatically
I have to write a code for generating the Jasper report which containing the images.
I want to send the jasper report to printer.
I tried  a Code:

```<code>    String Report = "C:\\Template\\"+file_name+".jrxml";//my Jasper report file
    JasperPrint print = JasperFillManager.fillReport(Report,null,con);
    PrinterJob job = PrinterJob.getPrinterJob();
    /* Create an array of PrintServices */
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
    int selectedService = 0;
    /* Scan found services to see if anyone suits our needs *
    for(int i = 0; i < services.length;i++)
    {
        if(services[i].getName().toUpperCase().contains("Your printer's name"))
        {
            /*If the service is named as what we are querying we select it */
                 selectedService = i;
        }
    }
    job.setPrintService(services[selectedService]);
    PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
    MediaSizeName mediaSizeName = MediaSize.findMedia(4,4,MediaPrintableArea.INCH);
    printRequestAttributeSet.add(mediaSizeName);
    printRequestAttributeSet.add(new Copies(1));
    JRPrintServiceExporter exporter;
    exporter = new JRPrintServiceExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
    /* We set the selected service and pass it as a paramenter */
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
    exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
    exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);
    exporter.exportReport();
</code>```

but It gives me error as:

```<code>   net.sf.jasperreports.engine.JRException: Error loading object from file : C:\Template\Alcon_Ele_Temp1.jrxml
</code>```

答:
The Jasper Report rendering library only renders .jasper file which is generated only .jrxml file is compiled.

The process is:

Design the Jasper Report using JasperSoft IDE. Once a report is
designed, it will create one file with .jrxml extension; also call
jasper report template

Once .jrxml file created (report template),
next step is compile it to make it .jasper file.
There are two ways to compile it,

Compile using JasperSoft report studio

Problematically using Java code (using Jasper library)

JasperCompileManager.compileReport("abc.xml");

Once it will be compiled and .jasper created it is loaded into JasperFillManager to print it.

Body:
I have to write a code for generating the Jasper report which containing the images.
I want to send the jasper report to printer.
I tried  a Code:

    String Report = "C:\\Template\\"+file_name+".jrxml";//my Jasper report file
    JasperPrint print = JasperFillManager.fillReport(Report,null,con);
    PrinterJob job = PrinterJob.getPrinterJob();
    /* Create an array of PrintServices */
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
    int selectedService = 0;
    /* Scan found services to see if anyone suits our needs *
    for(int i = 0; i < services.length;i++)
    {
        if(services[i].getName().toUpperCase().contains("Your printer's name"))
        {
            /*If the service is named as what we are querying we select it */
                 selectedService = i;
        }
    }
    job.setPrintService(services[selectedService]);
    PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
    MediaSizeName mediaSizeName = MediaSize.findMedia(4,4,MediaPrintableArea.INCH);
    printRequestAttributeSet.add(mediaSizeName);
    printRequestAttributeSet.add(new Copies(1));
    JRPrintServiceExporter exporter;
    exporter = new JRPrintServiceExporter();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
    /* We set the selected service and pass it as a paramenter */
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
    exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
    exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
    exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);
    exporter.exportReport();

but It gives me error as:

   net.sf.jasperreports.engine.JRException: Error loading object from file : C:\Template\Alcon_Ele_Temp1.jrxml


问:
Why can we compare character constants?
Came across this statement in a C book, if ((letter >= 'P') && (letter <= 'S'))

It's trying to check if the letter falls between P and S (including both) and I was quite surprised to see it work.

How is it possible to do greater-than/lesser-than type operations on alphabets (character data type)?

It is a feature in only C or in other programming languages as well?

答:
How is it possible

To invert the question, why wouldn’t it be? Our alphabet is naturally ordered, and having an ordering between letters is convenient and just makes sense. In the particular case of C, character literal are simply integer numbers, so ordering them naturally works.

On a more technical levels, characters are mapped to integer numbers by some encoding schema, known as a character encoding. Different encodings exist, and which particular encoding is used isn’t defined by the C standard, and isn’t important for comparing characters, as long as it’s consistent. This also means that C does not guarantee that this ordering corresponds to a particular alphabet, or that letters are consecutive.

It is a feature in only C or in other programming languages as well?

Virtually every modern programming language allows order comparison of character types.

Caveat: Many languages extend this capability to character strings. Such a comparison is called lexicographical comparison. While C also supports this, e.g. via strcmp, it’s important to note that C does not allow you to compare strings using operators (<, >, <=, >=). Unfortunate C will accept your attempt to do so without complaining:

```<code>char a[] = "hello";
char b[] = "world";
if (a < b) { /* not allowed! */ }
if (strcmp(a, b) < 0) { /* correct way. */ }
</code>```

The first if will compile, but it will do the wrong thing: instead of comparing the string contents, it will convert a and b to pointers and compare the values of the two pointers. And that is undefined behaviour (!), which means that it’s not valid C, the result is potentially unpredictable, but the compiler will not necessarily tell you that anything is wrong.

Title: Why can we compare character constants?

Body:
How is it possible

To invert the question, why wouldn’t it be? Our alphabet is naturally ordered, and having an ordering between letters is convenient and just makes sense. In the particular case of C, character literal are simply integer numbers, so ordering them naturally works.

On a more technical levels, characters are mapped to integer numbers by some encoding schema, known as a character encoding. Different encodings exist, and which particular encoding is used isn’t defined by the C standard, and isn’t important for comparing characters, as long as it’s consistent. This also means that C does not guarantee that this ordering corresponds to a particular alphabet, or that letters are consecutive.

It is a feature in only C or in other programming languages as well?

Virtually every modern programming language allows order comparison of character types.

Caveat: Many languages extend this capability to character strings. Such a comparison is called lexicographical comparison. While C also supports this, e.g. via strcmp, it’s important to note that C does not allow you to compare strings using operators (<, >, <=, >=). Unfortunate C will accept your attempt to do so without complaining:

char a[] = "hello";
char b[] = "world";
if (a < b) { /* not allowed! */ }
if (strcmp(a, b) < 0) { /* correct way. */ }

The first if will compile, but it will do the wrong thing: instead of comparing the string contents, it will convert a and b to pointers and compare the values of the two pointers. And that is undefined behaviour (!), which means that it’s not valid C, the result is potentially unpredictable, but the compiler will not necessarily tell you that anything is wrong.


问:
Poor image resolution when using imageList in C#
I am using an imageList which has 5 images stored, 3 of which are .jpg and 2 .bmp.

I am using these images to change a picturebox image using a timer -

```<code>private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Image = imageList1.Images[imgIndex++];
    }
</code>```

where private int imgIndex = 0; is set in the Form class.

I have 2 problems, firstly the resolution of the images when displayed in the picture box is very pixelated and of poor quality, and I have tried to resolve this by changing the ColorDepth in the imageList properties and I have also tried using different image formats i.e. .gif, .png etc and altering the image size but this does not work. How can I get a better resolution?

The second problem is when the timer gets to the last image, the application crashes with the error 'InvalidArgument=Value of '5' is not valid for 'index. Parameter name: index'
There are 5 images in the imageList and when debugging the error arises from private int imgIndex = 0; how can I resolve this?

答:
I get the same problem where every once in a while, the form resource file decides to provide a lower resolution image format for my image list.

I have to delete the images from the image list and re-add them to get the full resolution back.

Body:
I am using an imageList which has 5 images stored, 3 of which are .jpg and 2 .bmp.

I am using these images to change a picturebox image using a timer -

private void timer1_Tick(object sender, EventArgs e)
    {
        pictureBox1.Image = imageList1.Images[imgIndex++];
    }

where private int imgIndex = 0; is set in the Form class.

I have 2 problems, firstly the resolution of the images when displayed in the picture box is very pixelated and of poor quality, and I have tried to resolve this by changing the ColorDepth in the imageList properties and I have also tried using different image formats i.e. .gif, .png etc and altering the image size but this does not work. How can I get a better resolution?

The second problem is when the timer gets to the last image, the application crashes with the error 'InvalidArgument=Value of '5' is not valid for 'index. Parameter name: index'
There are 5 images in the imageList and when debugging the error arises from private int imgIndex = 0; how can I resolve this?


问:
sql golang invalid memory address or nil pointer dereference when do query
i am trying to insert data after the connection, when i command the logic of INSERT... i was able to connect to the database, but when i uncommand them , i got error

```<code>panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x40f8e2a]

</code>```

here is my function :

```<code>func Connect() (*sql.DB, error) {
    db, err := sql.Open("postgres", os.Getenv("PG_URL"))
    if err != nil {
        return nil, err
    }
    defer db.Close()

    stmt, _ := db.Prepare("INSERT INTO users(name, email, password) VALUES(?,?,?)")
    res, err := stmt.Exec("test", "test@mail.com", "12344")

    if err != nil{
        panic(err.Error())
    }
    fmt.Println(res)
    fmt.Println("Successfully connected!")
    return db, nil
}

</code>```

I have tried to do the same thing also like this article go sql
and have the same issue
do I wrong implement this?

答: I bet a dollar/euro/frank that the NPE is on the line executing the prepared statement and that if you check the only error you ignored it won't be nil and it will tell you what's wrong.

Body:
i am trying to insert data after the connection, when i command the logic of INSERT... i was able to connect to the database, but when i uncommand them , i got error

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x40f8e2a]

here is my function :

func Connect() (*sql.DB, error) {
    db, err := sql.Open("postgres", os.Getenv("PG_URL"))
    if err != nil {
        return nil, err
    }
    defer db.Close()

    stmt, _ := db.Prepare("INSERT INTO users(name, email, password) VALUES(?,?,?)")
    res, err := stmt.Exec("test", "test@mail.com", "12344")

    if err != nil{
        panic(err.Error())
    }
    fmt.Println(res)
    fmt.Println("Successfully connected!")
    return db, nil
}

I have tried to do the same thing also like this article go sql
and have the same issue
do I wrong implement this?


答:
chars in C are actually small integers (normally with range -128..127). All operators that work on other integers also work on chars, this includes >= and <=.

A character literal like 'P' is a numeric code of the character (normally an ASCII code, but the standard doesn't specify the encoding). In ASCII, codes for letters are consecutive (separately for A-Z and a-z), so >= and <= do the right thing.

It is a feature in only C or in other programming languages as well?

At least one language does: C++ is based on C, so it also has this feature.

Title: Why can we compare character constants?

Body:
Came across this statement in a C book, if ((letter >= 'P') && (letter <= 'S'))

It's trying to check if the letter falls between P and S (including both) and I was quite surprised to see it work.

How is it possible to do greater-than/lesser-than type operations on alphabets (character data type)?

It is a feature in only C or in other programming languages as well?