问:
How to pass efficiently a huge sized parameter to a function?
thank you reading. Please forgive my English, I'm french. Is it a justification ?

The aim of my function is to scan many IPv4:PORT via multiprocessing/threading (do not, I forsee you, do not !) in Python3, send a SYN and register any result. Multisomething is called here because of the timeout needed to wait to any potential reply.
So.

This function is called a producer. It stores potential TCP connection into a database. Consumers
 then read the database and do some pentesting indepently. So.

I prepared an IPv4 list. It's a random valid IP list of 10's K elements. Remember we have 65K ports to test per IPv4.

My method is then to suffle the list port with a new seed for each producer launched. I have many. Each have a valid IPv4 list, but, if we consider 65K ports with 100K IP's, we have a 6.5G elements to pass.

Why ?

IP[] are random.shuffle()-like, by construction. Ports[] are too.

If I read p in Ports and for each p, join IPv4:Ports and append into params[], I can launch the parallelized job via scan(u) for u in params[]

I launch it via run(rounds) like this :

```<code>def run(rounds):
   for r in rounds:
      scan(r)
</code>```

But, the problem is size(rounds) = size(params) ~ 6.5G elements

I cannot find a efficient (memory talking) way to pass such a huge parameter (big list) to a parallelized job. I'm running out of memory.

I'm not asking how to manage it on a mind-blowing-capable workstation, while having designed this function on a paper, it doesn't fit into the raspi2 (1GB mem).

I do not need Python3 at all for myself, it a teaching product. Thus, i'm stuck.

My question is : could you help me to find a efficient way to attack a huge list by a parallelized function that pop's the list without sending it via a parameter ?

I googled, followed forums and threads I'm aware of, but, as I refactor the programm, the constant problem stays, laughing at me, at the same place in the main().

What I dont want to reproduce :

```<code>MAX_IPV4 = i.IPv4Address._ALL_ONES
MAX_PORT = 65535

def r_ipv4():
    while True:
        a=i.IPv4Address._string_from_ip_int(r.randint(0, MAX_IPV4))
        b=i.IPv4Address(a)
        if b.is_multicast or b.is_private or b.is_loopback or b.is_reserved or b.is_link_local :
            continue
        else :
            return a
            break

def generate_target():
    return r_ipv4()

def generate_r_targets(n):
    ip=[]
    for i in range(0,n):
            ip.append(generate_target())
    ports=[]
    for p in range(1,65535):
            ports.append(p)
    r.shuffle(ports)
    targets=[]
    for p in ports:
        for z in ip:
            targets.append((str(z)+","+str(p)))
</code>```

It's not my optimal method, but the way I can explain and show the problem at best.

I dont want to lost the (shuffled ports) iterable, it is my principal vector and it is at the heart.
I'm testing a dynamic configuration of knockd.

Say. Computer_one register a sequence in knockd.
Computer_one is the only one to know the seed.
The seed is the key of the sequence of keys of knockd, that's done.

答: We passed it via a plain file :)</p>

Body:
thank you reading. Please forgive my English, I'm french. Is it a justification ?

The aim of my function is to scan many IPv4:PORT via multiprocessing/threading (do not, I forsee you, do not !) in Python3, send a SYN and register any result. Multisomething is called here because of the timeout needed to wait to any potential reply.
So.

This function is called a producer. It stores potential TCP connection into a database. Consumers
 then read the database and do some pentesting indepently. So.

I prepared an IPv4 list. It's a random valid IP list of 10's K elements. Remember we have 65K ports to test per IPv4.

My method is then to suffle the list port with a new seed for each producer launched. I have many. Each have a valid IPv4 list, but, if we consider 65K ports with 100K IP's, we have a 6.5G elements to pass.

Why ?

IP[] are random.shuffle()-like, by construction. Ports[] are too.

If I read p in Ports and for each p, join IPv4:Ports and append into params[], I can launch the parallelized job via scan(u) for u in params[]

I launch it via run(rounds) like this :

def run(rounds):
   for r in rounds:
      scan(r)

But, the problem is size(rounds) = size(params) ~ 6.5G elements

I cannot find a efficient (memory talking) way to pass such a huge parameter (big list) to a parallelized job. I'm running out of memory.

I'm not asking how to manage it on a mind-blowing-capable workstation, while having designed this function on a paper, it doesn't fit into the raspi2 (1GB mem).

I do not need Python3 at all for myself, it a teaching product. Thus, i'm stuck.

My question is : could you help me to find a efficient way to attack a huge list by a parallelized function that pop's the list without sending it via a parameter ?

I googled, followed forums and threads I'm aware of, but, as I refactor the programm, the constant problem stays, laughing at me, at the same place in the main().

What I dont want to reproduce :

MAX_IPV4 = i.IPv4Address._ALL_ONES
MAX_PORT = 65535

def r_ipv4():
    while True:
        a=i.IPv4Address._string_from_ip_int(r.randint(0, MAX_IPV4))
        b=i.IPv4Address(a)
        if b.is_multicast or b.is_private or b.is_loopback or b.is_reserved or b.is_link_local :
            continue
        else :
            return a
            break

def generate_target():
    return r_ipv4()

def generate_r_targets(n):
    ip=[]
    for i in range(0,n):
            ip.append(generate_target())
    ports=[]
    for p in range(1,65535):
            ports.append(p)
    r.shuffle(ports)
    targets=[]
    for p in ports:
        for z in ip:
            targets.append((str(z)+","+str(p)))

It's not my optimal method, but the way I can explain and show the problem at best.

I dont want to lost the (shuffled ports) iterable, it is my principal vector and it is at the heart.
I'm testing a dynamic configuration of knockd.

Say. Computer_one register a sequence in knockd.
Computer_one is the only one to know the seed.
The seed is the key of the sequence of keys of knockd, that's done.

Body: We passed it via a plain file :)


来源: stackexchange

问:
how set ClickListener on drawable in Drawable class in android?
I have a class that extends from Drawable.
I draw some Views on it. I have drawable that I should set ClickListener on it!
I  searched a lot, and according to this link, we have not listener for this class!

anybody can help me ?! Thanks

答:
There's no way to set a click listener on a Drawable directly. You should put the Drawable into an ImageView using setImageDrawable(...).

From there, you can set a click listener on the ImageView with setOnClickListener just as you would with any other View.

ContentLicense: CC BY-SA 4.0


问:
LiteDB use same ID for different entries
I have  a database where I'm trying to add messages and I use channelID for LiteDB id. I want to post more than 1 message in the same channel somehow but for that I would have to use the same ID somehow.

```<code>   private LiteDatabase Database { get; } = new LiteDatabase(@"data/msg.db");

    public ILiteCollection<Message> Messages { get { return Database.GetCollection<Message>("Messages"); } }

    public void Add(int channelid, Message message)
    {
        message.ChannelID = channelid;
        Messages.Insert(message);

        //Books.Add(book.Id,book);
    }
</code>```

Message class

```<code>public class Message
{
    [LiteDB.BsonId]
    public int ChannelID { get; set; }

    public int User { get; set; }

    public DateTime Date { get; set; }

    public string Text { get; set; }
}
</code>```

This is the API I want to replicate: http://www.webservies.be/chat/swagger/index.html
In this it's possible to use the same channelID when I want to POST a message.

答:
If you want your class to match the API you posted, you'll need an additional Channel class with a one-to-many relationship with Message. One chat channel can have many messages, right?

Something like

```<code>public class Channel
{
    [BsonId]
    public int ChannelId { get; set; }
    public string Name { get; set; }

    [BsonRef]
    public List<Message> Messages { get; set; }
}

public class Message
{
    [BsonId]
    public int MessageId { get; set; }
    public int ChannelId { get; set; }
    public int UserId { get; set; }
    public DateTime Date { get; set; }
    public string Text { get; set; }
}
</code>```

Inserting a new message would be very similar to what you've already done.

```<code>public void Add(int channelId, string text, int userId)
{
   var message = new Message {
       ChannelId = channelId,
       Text = text,
       UserId = userId,
       Date = DateTime.Now
   };

   Messages.Insert(message);
}
</code>```

Body:
I have  a database where I'm trying to add messages and I use channelID for LiteDB id. I want to post more than 1 message in the same channel somehow but for that I would have to use the same ID somehow.

   private LiteDatabase Database { get; } = new LiteDatabase(@"data/msg.db");

    public ILiteCollection<Message> Messages { get { return Database.GetCollection<Message>("Messages"); } }

    public void Add(int channelid, Message message)
    {
        message.ChannelID = channelid;
        Messages.Insert(message);

        //Books.Add(book.Id,book);
    }

Message class

public class Message
{
    [LiteDB.BsonId]
    public int ChannelID { get; set; }

    public int User { get; set; }

    public DateTime Date { get; set; }

    public string Text { get; set; }
}

This is the API I want to replicate: http://www.webservies.be/chat/swagger/index.html
In this it's possible to use the same channelID when I want to POST a message.

Body:
If you want your class to match the API you posted, you'll need an additional Channel class with a one-to-many relationship with Message. One chat channel can have many messages, right?

Something like

public class Channel
{
    [BsonId]
    public int ChannelId { get; set; }
    public string Name { get; set; }

    [BsonRef]
    public List<Message> Messages { get; set; }
}

public class Message
{
    [BsonId]
    public int MessageId { get; set; }
    public int ChannelId { get; set; }
    public int UserId { get; set; }
    public DateTime Date { get; set; }
    public string Text { get; set; }
}

Inserting a new message would be very similar to what you've already done.

public void Add(int channelId, string text, int userId)
{
   var message = new Message {
       ChannelId = channelId,
       Text = text,
       UserId = userId,
       Date = DateTime.Now
   };

   Messages.Insert(message);
}


问:
HTML: Automatically Display Given Input on the Same Page
I would like to ask how should we write in HTML to display automatically an input given by a Web user on the same page without a button or click.

Here is an example that I copy from elsewhere:

```<code><!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<script type="text/javascript">

function changeThis(){
   var formInput = document.getElementById('theInput').value;
   document.getElementById('newText').innerHTML = formInput;   }
</script>

<p>You wrote: <span id='newText'></span> </p>
<input type='text' id='theInput'>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
</code>```

I want to obtain the same effect without using any button, click or Enter tab.

In other words, the input given is display next to "You wrote" second after the user puts something on the line box.

答:
Please see the code below. It will write the text as soon you type in input box:</p>

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

Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<p id="rewrite"></p>

<script>
function myFunction() {
  var x = document.getElementById("fname");
  document.getElementById("rewrite").innerHTML=x.value;
}
</script>

</body>
</html>
</code>```

Body:
I would like to ask how should we write in HTML to display automatically an input given by a Web user on the same page without a button or click.

Here is an example that I copy from elsewhere:

<!DOCTYPE HTML>

You wrote:

<input type='text' id='theInput'>
<input type='button' onclick='changeThis()' value='See what you wrote'/>

I want to obtain the same effect without using any button, click or Enter tab.

In other words, the input given is display next to "You wrote" second after the user puts something on the line box.

Body:
Please see the code below. It will write the text as soon you type in input box:

<!DOCTYPE html>
<html>
<body>

Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<p id="rewrite"></p>

<script>
function myFunction() {
  var x = document.getElementById("fname");
  document.getElementById("rewrite").innerHTML=x.value;
}
</script>

</body>
</html>


问:
Firebase Update Data Not work using FirebaseData.net nuget
I am using FirebaseDatabase.net plugin in my xamarin mobile app.

I am able to insert and read data,but unable to use update.I am using PutAsync method:

Example:

```<code>FirebaseClient firebase = new FirebaseClient("https://******.firebaseio.com/");
await firebase.Child("Users").Child("nhUHmmu8HJimlo").PutAsync(JsonConvert.SerializeObject(user));
</code>```

in the last line I am not able to use multiple 'Child' keyword for this PutAsync method,so how to solve this?Is there any other way to achieve this?

答:
I'm not sure why the Xamarin client only allows a single call to Child() as all official SDKs allow you to chain those.

Luckily you can put the entire path in a single call, by separating the segments with /. So:

```<code>firebase.Child("Users/nhUHmmu8HJimlo").PutAsync(JsonConvert.SerializeObject(user));
</code>```

Body:
I am using FirebaseDatabase.net plugin in my xamarin mobile app.

I am able to insert and read data,but unable to use update.I am using PutAsync method:

Example:

FirebaseClient firebase = new FirebaseClient("https://******.firebaseio.com/");
await firebase.Child("Users").Child("nhUHmmu8HJimlo").PutAsync(JsonConvert.SerializeObject(user));

in the last line I am not able to use multiple 'Child' keyword for this PutAsync method,so how to solve this?Is there any other way to achieve this?

Body:
I'm not sure why the Xamarin client only allows a single call to Child() as all official SDKs allow you to chain those.

Luckily you can put the entire path in a single call, by separating the segments with /. So:

firebase.Child("Users/nhUHmmu8HJimlo").PutAsync(JsonConvert.SerializeObject(user));


问:
Addition with carryover in arrays in pure Javascript
I want to create simple addition of array with carryover. Also need carryover and result value for display.

Something like this:-

e.g var input = [[0,0,9],[0,9,9]];
 var carryover = [];
var result = [];

Thanks...

答:
```<code>    1.turn both numbers into array of digits, reverse them.
    2.determine the end index of the for-loop with max length of above 2 arrays.
    3.create the 3rd carryover digits array of zeros (don't forget the extra digit).
    4.Add the respective digits from step1 and step3,
       as you iterate through each of digits from right to left,
    4.1 if the sum is greater than 9 then add 1 into next carryover slot.
    5. you should have array of carried over digits when the for-loop is done
         count the number of 1s you have in them.
</code>```

```<code>function numberOfCarryOperations(num1, num2) {
    const dd1 = [...num1.toString()].reverse()
    const dd2 = [...num2.toString()].reverse()
    const end = Math.max(dd1.length, dd2.length)
    const carry = Array(end+1).fill(0)
    for (let i = 0; i < end; i++) {
        //console.log(i,(Number(dd1[i]?dd1[i]:0)),Number(dd2[i]?dd2[i]:0),carry)
        if (((Number(dd1[i]?dd1[i]:0)) + Number(dd2[i]?dd2[i]:0) + carry[i]) > 9) {
            carry[i+1] = 1
        }
        //console.log('-----',carry)
    }
    //console.log(num1, num2,carry)
    return carry.reduce((sum,curr)=>sum+curr)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    1.turn both numbers into array of digits, reverse them.
    2.determine the end index of the for-loop with max length of above 2 arrays.
    3.create the 3rd carryover digits array of zeros (don't forget the extra digit).
    4.Add the respective digits from step1 and step3,
       as you iterate through each of digits from right to left,
    4.1 if the sum is greater than 9 then add 1 into next carryover slot.
    5. you should have array of carried over digits when the for-loop is done
         count the number of 1s you have in them.

function numberOfCarryOperations(num1, num2) {
    const dd1 = [...num1.toString()].reverse()
    const dd2 = [...num2.toString()].reverse()
    const end = Math.max(dd1.length, dd2.length)
    const carry = Array(end+1).fill(0)
    for (let i = 0; i < end; i++) {
        //console.log(i,(Number(dd1[i]?dd1[i]:0)),Number(dd2[i]?dd2[i]:0),carry)
        if (((Number(dd1[i]?dd1[i]:0)) + Number(dd2[i]?dd2[i]:0) + carry[i]) > 9) {
            carry[i+1] = 1
        }
        //console.log('-----',carry)
    }
    //console.log(num1, num2,carry)
    return carry.reduce((sum,curr)=>sum+curr)
}


问:
Android Kotlin app RecyclerView Showing Nothing, Adapter Not Working, No errors
I'm trying an Api with a simple MVP Kotlin app and I do everything for it, I receive the list of coins in the Adapter but when I do a Log in bind() It doesn't show to me any error and app runs well but without any item.
I have a similar app with the same code but it works well so I don't know what to do. I bring you my code, thanks!

MainActivity:

```<code>class MainActivity : AppCompatActivity(),
    CoinsView {

    lateinit var presenter: MainPresenter
    lateinit var numAdapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val remoteRepository = RemoteRepoCalls(RetrofitFactory.getCoinApi())

        presenter = MainPresenter(
            this,
            remoteRepository
        )

        recyclerViewMain.layoutManager = LinearLayoutManager(this)
        recyclerViewMain.setHasFixedSize(true)

        numAdapter = MainAdapter()
        recyclerViewMain.adapter = numAdapter

        presenter.getMonedas("3")
    }

    override fun showData(result: List<Coins>) {
        //numAdapter.getData(result)
        numAdapter.getData(result)
    }
}
</code>```

MainAdapter:

```<code>class MainAdapter: RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    var listNums : List<Coins> = listOf<Coins>()

    fun getData(list: List<Coins>) {
        listNums = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        return ViewHolder.from(parent)
    }

    //Tamaño lista
    override fun getItemCount(): Int = listNums.size

    //Nos pasa cada dato de la lista segun posicion
    override fun onBindViewHolder(holder: MainAdapter.ViewHolder, position: Int) {
        holder.bind(listNums[position])
    }

    //Rellena la vista con cada dato
    class ViewHolder private constructor(view: View): RecyclerView.ViewHolder(view) {
        private val coinNames = view.findViewById<TextView>(R.id.coinName)
        private val coinSymbol = view.findViewById<TextView>(R.id.coinSymbol)
        //private val imageItem1 = view.findViewById<ImageView>(R.id.imageItem)

        fun bind(coinss : Coins) {
            coinNames.text = coinss.name
            coinSymbol.text = coinss.symbol
            //Picasso.get().load(coinss.thumbnail).into(imageItem1)
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
                return ViewHolder(view)
            }
        }
    }

}
</code>```

MainPresenter:

```<code>class MainPresenter(
    private val view: CoinsView,
    private val remoteRepository: RemoteRepository,
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    fun getMonedas(limite: String) {
        CoroutineScope(ioDispatcher).launch {

            var resultado = remoteRepository.getCoins(limite)

            withContext(mainDispatcher) {
                view.showData(resultado)

            }
        }
    }
}
interface CoinsView {
    fun showData(result : List<Coins>)
}
</code>```

CoinRanking.kt:

```<code>interface CoinRanking {
    @GET("coins")
    suspend fun getAll(): Response <EveryData>
}

object RetrofitFactory {

    const val BASE_URL = "https://api.coinranking.com/v1/public/"

    fun getCoinApi(): CoinRanking {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(MoshiConverterFactory.create())
            .build().create(CoinRanking::class.java)
    }
}
</code>```

Coins Model:

```<code>data class Coins (
    var symbol: String,
    var name: String,
    var iconUrl: String,
    var price: String
)
</code>```

AppPhoto: Under tittle should show the recycler with coins items

答:
I suggest to change this line:

```<code>var listNums : List<Coins> = listOf<Coins>()
</code>```

into this:

```<code>val listNums : ArrayList<Coins> = arrayListOf<Coins>()
</code>```

Then also change this method (please rename it to something more reflecting its nature) :

```<code>    fun getData(list: List<Coins>) {
        listNums.clear()
        listNums.addAll(list)
        notifyDataSetChanged()
    }
</code>```

Body:
I'm trying an Api with a simple MVP Kotlin app and I do everything for it, I receive the list of coins in the Adapter but when I do a Log in bind() It doesn't show to me any error and app runs well but without any item.
I have a similar app with the same code but it works well so I don't know what to do. I bring you my code, thanks!

MainActivity:

class MainActivity : AppCompatActivity(),
    CoinsView {

    lateinit var presenter: MainPresenter
    lateinit var numAdapter: MainAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val remoteRepository = RemoteRepoCalls(RetrofitFactory.getCoinApi())

        presenter = MainPresenter(
            this,
            remoteRepository
        )

        recyclerViewMain.layoutManager = LinearLayoutManager(this)
        recyclerViewMain.setHasFixedSize(true)

        numAdapter = MainAdapter()
        recyclerViewMain.adapter = numAdapter

        presenter.getMonedas("3")
    }

    override fun showData(result: List<Coins>) {
        //numAdapter.getData(result)
        numAdapter.getData(result)
    }
}

MainAdapter:

class MainAdapter: RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    var listNums : List<Coins> = listOf<Coins>()

    fun getData(list: List<Coins>) {
        listNums = list
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
        return ViewHolder.from(parent)
    }

    //Tamaño lista
    override fun getItemCount(): Int = listNums.size

    //Nos pasa cada dato de la lista segun posicion
    override fun onBindViewHolder(holder: MainAdapter.ViewHolder, position: Int) {
        holder.bind(listNums[position])
    }

    //Rellena la vista con cada dato
    class ViewHolder private constructor(view: View): RecyclerView.ViewHolder(view) {
        private val coinNames = view.findViewById<TextView>(R.id.coinName)
        private val coinSymbol = view.findViewById<TextView>(R.id.coinSymbol)
        //private val imageItem1 = view.findViewById<ImageView>(R.id.imageItem)

        fun bind(coinss : Coins) {
            coinNames.text = coinss.name
            coinSymbol.text = coinss.symbol
            //Picasso.get().load(coinss.thumbnail).into(imageItem1)
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
                return ViewHolder(view)
            }
        }
    }

}

MainPresenter:

class MainPresenter(
    private val view: CoinsView,
    private val remoteRepository: RemoteRepository,
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    fun getMonedas(limite: String) {
        CoroutineScope(ioDispatcher).launch {

            var resultado = remoteRepository.getCoins(limite)

            withContext(mainDispatcher) {
                view.showData(resultado)

            }
        }
    }
}
interface CoinsView {
    fun showData(result : List<Coins>)
}

CoinRanking.kt:

interface CoinRanking {
    @GET("coins")
    suspend fun getAll(): Response <EveryData>
}

object RetrofitFactory {

    const val BASE_URL = "https://api.coinranking.com/v1/public/"

    fun getCoinApi(): CoinRanking {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(MoshiConverterFactory.create())
            .build().create(CoinRanking::class.java)
    }
}

Coins Model:

data class Coins (
    var symbol: String,
    var name: String,
    var iconUrl: String,
    var price: String
)

AppPhoto: Under tittle should show the recycler with coins items

Body:
I suggest to change this line:

var listNums : List<Coins> = listOf<Coins>()

into this:

val listNums : ArrayList<Coins> = arrayListOf<Coins>()

Then also change this method (please rename it to something more reflecting its nature) :

    fun getData(list: List<Coins>) {
        listNums.clear()
        listNums.addAll(list)
        notifyDataSetChanged()
    }


问:
How to make a tkinter canvas polygon transparent?
Is there a better way to make the fill of a polygon transparent, rather than using stipple?
Heres an example:

import tkinter as tk

class GUI:
    def __init__(self, master, x, y):
        self.master = master
        self.canvas = tk.Canvas(master, width=x, height=y)
        self.canvas.pack()
        self.canvas.create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10,
        outline="green", fill="blue")
        self.canvas.create_polygon(100, 10, 10, 40, 50, 300, 250, 400, 100, 10,
        outline="green", fill="red", stipple="gray50")

x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()
```

I would like to make the transparency of the red polygon realistic, like any software given the alpha parameter.

答:
My solution is inspired by this answer on a similar question but for rectangles, not polygons.

Unfortunately, Tkinter doesn't support RGBA, so it's impossible just to pass fill args fill="#ff000055". Instead, we can create an image which contains the rectangle and has RGBA channel using PIL.

Here is an example:

```<code>from tkinter import *
from PIL import Image, ImageDraw, ImageTk

def create_polygon(*args, **kwargs):
    if "alpha" in kwargs:
        if "fill" in kwargs:
            # Get and process the input data
            fill = root.winfo_rgb(kwargs.pop("fill"))\
                   + (int(kwargs.pop("alpha") * 255),)
            outline = kwargs.pop("outline") if "outline" in kwargs else None

            # We need to find a rectangle the polygon is inscribed in
            # (max(args[::2]), max(args[1::2])) are x and y of the bottom right point of this rectangle
            # and they also are the width and height of it respectively (the image will be inserted into
            # (0, 0) coords for simplicity)
            image = Image.new("RGBA", (max(args[::2]), max(args[1::2])))
            ImageDraw.Draw(image).polygon(args, fill=fill, outline=outline)

            images.append(ImageTk.PhotoImage(image))  # prevent the Image from being garbage-collected
            return canvas.create_image(0, 0, image=images[-1], anchor="nw")  # insert the Image to the 0, 0 coords
        raise ValueError("fill color must be specified!")
    return canvas.create_polygon(*args, **kwargs)

images = []  # to hold the newly created image(s)

root = Tk()

canvas = Canvas(width=260, height=310)
canvas.pack()

create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10, fill="blue", alpha=0.5)
create_polygon(150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200, fill="blue", alpha=0.2)

root.mainloop()
</code>```

Body:
Is there a better way to make the fill of a polygon transparent, rather than using stipple?
Heres an example:

import tkinter as tk

class GUI:
    def __init__(self, master, x, y):
        self.master = master
        self.canvas = tk.Canvas(master, width=x, height=y)
        self.canvas.pack()
        self.canvas.create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10,
        outline="green", fill="blue")
        self.canvas.create_polygon(100, 10, 10, 40, 50, 300, 250, 400, 100, 10,
        outline="green", fill="red", stipple="gray50")

x, y = 500, 500
root = tk.Tk()
gui = GUI(root, x, y)
root.mainloop()

I would like to make the transparency of the red polygon realistic, like any software given the alpha parameter.

Body:
My solution is inspired by this answer on a similar question but for rectangles, not polygons.

Unfortunately, Tkinter doesn't support RGBA, so it's impossible just to pass fill args fill="#ff000055". Instead, we can create an image which contains the rectangle and has RGBA channel using PIL.

Here is an example:

from tkinter import *
from PIL import Image, ImageDraw, ImageTk

def create_polygon(*args, **kwargs):
    if "alpha" in kwargs:
        if "fill" in kwargs:
            # Get and process the input data
            fill = root.winfo_rgb(kwargs.pop("fill"))\
                   + (int(kwargs.pop("alpha") * 255),)
            outline = kwargs.pop("outline") if "outline" in kwargs else None

            # We need to find a rectangle the polygon is inscribed in
            # (max(args[::2]), max(args[1::2])) are x and y of the bottom right point of this rectangle
            # and they also are the width and height of it respectively (the image will be inserted into
            # (0, 0) coords for simplicity)
            image = Image.new("RGBA", (max(args[::2]), max(args[1::2])))
            ImageDraw.Draw(image).polygon(args, fill=fill, outline=outline)

            images.append(ImageTk.PhotoImage(image))  # prevent the Image from being garbage-collected
            return canvas.create_image(0, 0, image=images[-1], anchor="nw")  # insert the Image to the 0, 0 coords
        raise ValueError("fill color must be specified!")
    return canvas.create_polygon(*args, **kwargs)

images = []  # to hold the newly created image(s)

root = Tk()

canvas = Canvas(width=260, height=310)
canvas.pack()

create_polygon(10, 10, 10, 20, 200, 300, 250, 150, 10, 10, fill="blue", alpha=0.5)
create_polygon(150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200, fill="blue", alpha=0.2)

root.mainloop()


答:
Please see my snippet below for the solution:

let input = document.querySelector('#theInput');
input.addEventListener('input', () => {
document.querySelector('#newText').innerHTML = input.value;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <p>You wrote: <span id='newText'></span> </p>
 <input type='text' id='theInput'>
 <input type='button' value='See what you wrote'/>
 </code>```

Title: HTML: Automatically Display Given Input on the Same Page

Body:
Please see my snippet below for the solution:

let input = document.querySelector('#theInput');
input.addEventListener('input', () => {
document.querySelector('#newText').innerHTML = input.value;
})

 <p>You wrote: <span id='newText'></span> </p>
 <input type='text' id='theInput'>
 <input type='button' value='See what you wrote'/>


问:
nHiberbate: Table per hierarchy - SchemaExport problem
I am using nhibernate to map the following classes:

```<code>public class DeviceConfig : EntityBase
{
    public virtual string Name
    {
        get { return m_Name; }
        set { SetValue(ref m_Name, value); }
    }
    public virtual string Description
    {
        get { return m_Description; }
        set { SetValue(ref m_Description, EmptyStringIfValueNull(value)); }
    }
}

 public class DeviceConfigEmail : DeviceConfig
{
    public virtual string SmtpServer
    {
        get { return m_SmtpServer; }
        set { SetValue(ref m_SmtpServer, EmptyStringIfValueNull(value)); }
    }
}

public class DeviceConfigSMS : DeviceConfig
{
    public virtual string SmsServer
    {
        get { return m_SmsServer; }
        set { SetValue(ref m_SmsServer, EmptyStringIfValueNull(value)); }
    }

}
</code>```

With the following Mapping file:

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"  default-access="field.pascalcase-m-underscore">
  <class name="MyNamespace.DeviceConfig, MyNamespace" table="DeviceConfig" lazy="false">
      <id name="ID" access="property" column="DeviceConfigID" unsaved-value="-1">
      <generator class="identity" />
    </id>

    <discriminator column="Discriminator"/>

    <version name="Version" column="Version"/>

    <property name="Name" not-null="true"/>
    <property name="Description" not-null="true"/>

    <subclass name="MyNamespace.DeviceConfigEmail, MyNamespace" discriminator-value="Email" lazy="false">
      <property name="SmtpServer" not-null="true"  />
    </subclass>

    <subclass name="MyNamespace.DeviceConfigSMS, MyNamespace" discriminator-value="SMS" lazy="false">
      <property name="SmsServer" not-null="true"  />
    </subclass>

  </class>
</hibernate-mapping>
</code>```

I am doing table per hierarchy data modelling to a table as follows:

```<code>table: DeviceConfig
- DeviceConfigID (PK, int, not null)
- Discriminator (varchar(20), not null)
- Name (varchar(50), not null)
- Description (varchar(200), not null)
- SmtpServer (varchar(30), null)
- SmsServer (varchar(30), null)
</code>```

This is all well and good, and works against my SQL database.

I now want to do a SchemaExport to do some in memory testing against Sqlite.  When I generate this table with a schema export, both SmtpServer and SmsServer columns get generated as not null.

Is there something I am doing wrong? How can I get these columns to generate as nullable?

Thanks,

Paul

答:
You've set the columns as not null in the mapping:

```<code><property name="SmtpServer" not-null="true" />
....
<property name="SmsServer" not-null="true" />
</code>```

Remove the not-null attributes.

Body:
I am using nhibernate to map the following classes:

public class DeviceConfig : EntityBase
{
    public virtual string Name
    {
        get { return m_Name; }
        set { SetValue(ref m_Name, value); }
    }
    public virtual string Description
    {
        get { return m_Description; }
        set { SetValue(ref m_Description, EmptyStringIfValueNull(value)); }
    }
}

 public class DeviceConfigEmail : DeviceConfig
{
    public virtual string SmtpServer
    {
        get { return m_SmtpServer; }
        set { SetValue(ref m_SmtpServer, EmptyStringIfValueNull(value)); }
    }
}

public class DeviceConfigSMS : DeviceConfig
{
    public virtual string SmsServer
    {
        get { return m_SmsServer; }
        set { SetValue(ref m_SmsServer, EmptyStringIfValueNull(value)); }
    }

}

With the following Mapping file:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"  default-access="field.pascalcase-m-underscore">
  <class name="MyNamespace.DeviceConfig, MyNamespace" table="DeviceConfig" lazy="false">
      <id name="ID" access="property" column="DeviceConfigID" unsaved-value="-1">
      <generator class="identity" />
    </id>

    <discriminator column="Discriminator"/>

    <version name="Version" column="Version"/>

    <property name="Name" not-null="true"/>
    <property name="Description" not-null="true"/>

    <subclass name="MyNamespace.DeviceConfigEmail, MyNamespace" discriminator-value="Email" lazy="false">
      <property name="SmtpServer" not-null="true"  />
    </subclass>

    <subclass name="MyNamespace.DeviceConfigSMS, MyNamespace" discriminator-value="SMS" lazy="false">
      <property name="SmsServer" not-null="true"  />
    </subclass>

  </class>
</hibernate-mapping>

I am doing table per hierarchy data modelling to a table as follows:

table: DeviceConfig
- DeviceConfigID (PK, int, not null)
- Discriminator (varchar(20), not null)
- Name (varchar(50), not null)
- Description (varchar(200), not null)
- SmtpServer (varchar(30), null)
- SmsServer (varchar(30), null)

This is all well and good, and works against my SQL database.

I now want to do a SchemaExport to do some in memory testing against Sqlite.  When I generate this table with a schema export, both SmtpServer and SmsServer columns get generated as not null.

Is there something I am doing wrong? How can I get these columns to generate as nullable?

Thanks,

Paul

Body:
You've set the columns as not null in the mapping:

<property name="SmtpServer" not-null="true" />
....
<property name="SmsServer" not-null="true" />

Remove the not-null attributes.


问:
What is the style of click onclicking?
I'm glad you can help me. I want to use css, html, and javascript to draw the text inside the p tag when the checkbox is checked.</p>

答:
Try this: </p>

```<code><!DOCTYPE html>
<html>
<head>
<style>
input:checked {
  height: 50px;
  width: 50px;
}
</style>
</head>
<body>

<form action="">
  <input type="radio" checked="checked" value="male" name="gender"> Male<br>
  <input type="radio" value="female" name="gender"> Female<br>
  <input type="checkbox" checked="checked" value="Bike"> I have a bike<br>
  <input type="checkbox" value="Car"> I have a car
</form>

</body>
</html>

</code>```

Title: What is the style of click onclicking?

Body:
Try this:

<!DOCTYPE html>
<html>
<head>
<style>
input:checked {
  height: 50px;
  width: 50px;
}
</style>
</head>
<body>

<form action="">
  <input type="radio" checked="checked" value="male" name="gender"> Male<br>
  <input type="radio" value="female" name="gender"> Female<br>
  <input type="checkbox" checked="checked" value="Bike"> I have a bike<br>
  <input type="checkbox" value="Car"> I have a car
</form>

</body>
</html>


问:
Privoxy, proxy some domain, and exclude some sub-domain
I use privoxy action file for proxy some domain, it works well

```<code>{{alias}}
proxy = +forward-override{forward-socks5 localhost:55501 .}

{proxy}
.demo1.com
.demo2.com
</code>```

now I want exclude some sub-domain, for example:

```<code>noproxy.demo1.com
</code>```

What should I write in the action file ?

答:
Got the same issue. The answer above is almost correct.

Documentation on https://www.privoxy.org/user-manual/actions-file.html#FORWARD-OVERRIDE says

```<code>"forward ." to use a direct connection without any additional proxies.
</code>```

So, correcting the previous answer:

```<code>{+forward-override{forward .}}
yourdomain.com
</code>```

Will do bypass the proxies for yourdomain.com

Body:
I use privoxy action file for proxy some domain, it works well

{{alias}}
proxy = +forward-override{forward-socks5 localhost:55501 .}

{proxy}
.demo1.com
.demo2.com

now I want exclude some sub-domain, for example:

noproxy.demo1.com

What should I write in the action file ?

Body:
Got the same issue. The answer above is almost correct.

Documentation on https://www.privoxy.org/user-manual/actions-file.html#FORWARD-OVERRIDE says

"forward ." to use a direct connection without any additional proxies.

So, correcting the previous answer:

{+forward-override{forward .}}
yourdomain.com

Will do bypass the proxies for yourdomain.com


问:
How to set innodb_thread_concurrency in MYSQL
My MYSQL DB is very slow but when I change the innodb_thread_concurrency value from the default 33 to 0 selects per second rise from 30-40 to 600-700. I would like to set this value every time the DB starts. I usually change variables in my.ini. There are 3 my.ini files on my system but the one in use (listed in MYSQL Workbench) is in the programdata directory. I have tried adding the variable to all 3 but it makes no difference. I must be getting the syntax wrong but I've tried several variations:
    innodb_thread_concurrency=0
    set-variable=innodb_thread_concurrency=0
Neither seem to work. Whenever I look at the system variable (in MYSQL Workbench) the innodb_thread_concurrency is 33 until I start a session and enter :
    set global innodb_thread_concurrency=0;
On Unix systems they talk about my.cnf but no such file exists on my W10 system.

What do I need to do to have this variable correctly set at startup?

答:
On Windows, the my.ini file may be in several locations. See https://dev.mysql.com/doc/refman/8.0/en/option-files.html

```<code>%WINDIR%\my.ini, %WINDIR%\my.cnf
C:\my.ini, C:\my.cnf
BASEDIR\my.ini, BASEDIR\my.cnf
</code>```

BASEDIR represents the MySQL base installation directory. When MySQL 8.0 has been installed using MySQL Installer, this is typically C:\PROGRAMDIR\MySQL\MySQL 8.0 Server where PROGRAMDIR represents the programs directory (usually Program Files on English-language versions of Windows)

The doc also says:

On Windows, MySQL programs read startup options from the files shown in the following table, in the specified order (files listed first are read first, files read later take precedence).

This means if you have an option file in multiple locations, MySQL Server will read all of them, in the order I listed them. If a subsequent file contains a setting for innodb_thread_concurrency, the value it sets will replace a value set in an earlier file. Just as a line setting that value lower within one file replaces a value set earlier in the file.

So make sure you check all files thoroughly, to make sure your change in the option file isn't superseded by a later line!

Body:
On Windows, the my.ini file may be in several locations. See https://dev.mysql.com/doc/refman/8.0/en/option-files.html

%WINDIR%\my.ini, %WINDIR%\my.cnf
C:\my.ini, C:\my.cnf
BASEDIR\my.ini, BASEDIR\my.cnf

BASEDIR represents the MySQL base installation directory. When MySQL 8.0 has been installed using MySQL Installer, this is typically C:\PROGRAMDIR\MySQL\MySQL 8.0 Server where PROGRAMDIR represents the programs directory (usually Program Files on English-language versions of Windows)

The doc also says:

On Windows, MySQL programs read startup options from the files shown in the following table, in the specified order (files listed first are read first, files read later take precedence).

This means if you have an option file in multiple locations, MySQL Server will read all of them, in the order I listed them. If a subsequent file contains a setting for innodb_thread_concurrency, the value it sets will replace a value set in an earlier file. Just as a line setting that value lower within one file replaces a value set earlier in the file.

So make sure you check all files thoroughly, to make sure your change in the option file isn't superseded by a later line!


问:
laravel policy not working for CamelCase model
I am trying to create policy for the custom method which is not working. Each time it returns 403 for the custom method with camelcase naming in laravel 7

Eg.

```<code>class UserPostController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(UserPost::class);
    }

    public function resourceMethodsWithoutModels()
    {
        return [
            'getListing'
        ];
    }

    public function getListing(UserPostDataTable $dataTable)
    {
        dd(\Auth::user()->can('viewAny', UserPost::class));

//        $this->authorize('viewAny', UserPost::class);
        return $dataTable->ajax();
    }

//Policy:
use App\User;
use App\UserPost;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;

class UserPostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return Response::allow()
    }

</code>```

I have already added $this->registerPolicies(); in boot method of service provider.
It works with all crud operation of resource but not with custom method.

When I use UserPost::class it returns 403.

If I use User::class it works perfectly.
It seems like some naming issue or I am missing out something.

I tried middleware too but not working for camelcase naming.

Don't know how can I add viewAny policy for getListing method.

Route list:

```<code>        | GET|HEAD  | UserPost                              | UserPost.index          | App\Http\Controllers\UserPostController@index                       | web,auth:web,can:viewAny,user_post |
|        | POST      | UserPost                              | UserPost.store          | App\Http\Controllers\UserPostController@store                       | web,auth:web,can:create,user_post  |
|        | GET|HEAD  | UserPost/create                       | UserPost.create         | App\Http\Controllers\UserPostController@create                      | web,auth:web,can:create,user_post  |
|        | POST      | UserPost/getListing                   | UserPost.getListing     | App\Http\Controllers\UserPostController@getListing                  | web,auth:web                          |
|        | DELETE    | UserPost/{UserPost}                | UserPost.destroy        | App\Http\Controllers\UserPostController@destroy                     | web,auth:web,can:delete,user_post  |
|        | PUT|PATCH | UserPost/{UserPost}                | UserPost.update         | App\Http\Controllers\UserPostController@update                      | web,auth:web,can:update,user_post  |
|        | GET|HEAD  | UserPost/{UserPost}                | UserPost.show           | App\Http\Controllers\UserPostController@show                        | web,auth:web,can:view,user_post    |
|        | GET|HEAD  | UserPost/{UserPost}/edit           | UserPost.edit           | App\Http\Controllers\UserPostController@edit                        | web,auth:web,can:update,user_post

</code>```

答:
```<code>$this->authorizeResource(UserPost::class);
</code>```

this method take a second parameter, this parameter must
match the parameter you use in route

so ... to solve this problem you should use

```<code>php artisan route:list
</code>```

then find out what is the route parameter name
( should be userPost ... or user_post) ...
suppose it is user_post ....
then change authorizeResource resource statement to:

```<code>$this->authorizeResource(UserPost::class,'user_post');
</code>```

and another note:
 in

```<code> public function viewAny(User $user)
    {
        return Response::allow()
    }
</code>```

do not miss setting the parameter name correctly:

```<code> public function viewAny(UserPost $user_post) // make sure you use correct parameter name
    {
        return Response::allow()
    }
</code>```

it should work ....

Body:
I am trying to create policy for the custom method which is not working. Each time it returns 403 for the custom method with camelcase naming in laravel 7

Eg.

class UserPostController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(UserPost::class);
    }

    public function resourceMethodsWithoutModels()
    {
        return [
            'getListing'
        ];
    }

    public function getListing(UserPostDataTable $dataTable)
    {
        dd(\Auth::user()->can('viewAny', UserPost::class));

//        $this->authorize('viewAny', UserPost::class);
        return $dataTable->ajax();
    }

//Policy:
use App\User;
use App\UserPost;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;

class UserPostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any models.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return Response::allow()
    }

I have already added $this->registerPolicies(); in boot method of service provider.
It works with all crud operation of resource but not with custom method.

When I use UserPost::class it returns 403.

If I use User::class it works perfectly.
It seems like some naming issue or I am missing out something.

I tried middleware too but not working for camelcase naming.

Don't know how can I add viewAny policy for getListing method.

Route list:

        | GET|HEAD  | UserPost                              | UserPost.index          | App\Http\Controllers\UserPostController@index                       | web,auth:web,can:viewAny,user_post |
|        | POST      | UserPost                              | UserPost.store          | App\Http\Controllers\UserPostController@store                       | web,auth:web,can:create,user_post  |
|        | GET|HEAD  | UserPost/create                       | UserPost.create         | App\Http\Controllers\UserPostController@create                      | web,auth:web,can:create,user_post  |
|        | POST      | UserPost/getListing                   | UserPost.getListing     | App\Http\Controllers\UserPostController@getListing                  | web,auth:web                          |
|        | DELETE    | UserPost/{UserPost}                | UserPost.destroy        | App\Http\Controllers\UserPostController@destroy                     | web,auth:web,can:delete,user_post  |
|        | PUT|PATCH | UserPost/{UserPost}                | UserPost.update         | App\Http\Controllers\UserPostController@update                      | web,auth:web,can:update,user_post  |
|        | GET|HEAD  | UserPost/{UserPost}                | UserPost.show           | App\Http\Controllers\UserPostController@show                        | web,auth:web,can:view,user_post    |
|        | GET|HEAD  | UserPost/{UserPost}/edit           | UserPost.edit           | App\Http\Controllers\UserPostController@edit                        | web,auth:web,can:update,user_post

Body:
$this->authorizeResource(UserPost::class);

this method take a second parameter, this parameter must
match the parameter you use in route

so ... to solve this problem you should use

php artisan route:list

then find out what is the route parameter name
( should be userPost ... or user_post) ...
suppose it is user_post ....
then change authorizeResource resource statement to:

$this->authorizeResource(UserPost::class,'user_post');

and another note:
 in

 public function viewAny(User $user)
    {
        return Response::allow()
    }

do not miss setting the parameter name correctly:

 public function viewAny(UserPost $user_post) // make sure you use correct parameter name
    {
        return Response::allow()
    }

it should work ....


问:
How to append to a list from a csv reading a column with operators appearing in line ; getting "invalid literal for float()" error
I am appending to a list from a csv which looks like this

SampleA,Type,3.782*0.0627

then vals = line.split(',')

So, I ve tried something like
value = float(str(vals[2]))
or
value = float(vals[2])

but I get errors like ValueError: invalid literal for float(): 3.782*0.0627

So what I want, is to basically store to value = 0.237 ie the result of the mutlipication

TIA

答:
You could calculate the float first.</p>

```<code>floats = vals[2].split('*')
value = float(floats[0]) * float(floats[1])
</code>```

Body:
You could calculate the float first.

floats = vals[2].split('*')
value = float(floats[0]) * float(floats[1])


问:
Upgrading VS2005 to VS2008
I have a small program <350ish lines of code on 5 forms>. It works fine compiled on VS2005 but doesn't run correctly on Vista. After importing through VS2008, it initially runs correctly. However, there is one main form with four subordinate ones that set the settings and attributes of the starter form. they work correctly until they are instantiated a second time then they are displayed but act like they are completely modal. The only way to remove the form is to close the start up form. Does anyone have any solutions to this?</p>

答: Are you sure you are cleaning up after you close the forms and not leaving one open, but not visible. I am not sure whether this is any different in VS2005, but I have seen applications that did not completely dispose of items on a form, leaving bits in memory. While they do not create a modal form, per se, that is the feeling one has when the form is opened. Without seeing your code, I can only guess.</p>

ContentLicense: CC BY-SA 2.5

Title: Upgrading VS2005 to VS2008

LastEditorDisplayName: moocha

OwnerDisplayName: Gregory A Beamer


问:
Automating Amazon EBS snapshots anyone have a good script or solution for this on linux
I'd expect this to be fairly routine, but cannot find a simple approach for creating an managing EBS snapshots automatically.

Was hoping there'd be a shceduler in the AWS console.. alas not yet.

Would appreciate any suggestions as to how best to do this on from Ubuntu.

Thanks

答:
A wonderful script to create an automatic snapshots.

https://github.com/rakesh-sankar/Tools/blob/master/AmazonAWS/EBS/EBS-Snapshot.sh

Just copy the code and create a file, then add a cronjob whenever you want it to run.


问:
Parsing nested JSON into a list of Tuples with Aeson
Say I have the following structure:

```<code>data AddressDto = AddressDto
  { addressDtoId                   :: UUID
  , addressDtoCode                 :: Text
  , addressDtoCity                 :: Maybe Text
  , addressDtoStreet               :: Text
  , addressDtoPostCode             :: Text
  } deriving (Eq, Show, Generic)

instance FromJSON AddressDto where
  parseJSON = genericParseJSON $ apiOptions "addressDto"

instance ToJSON AddressDto where
  toJSON = genericToJSON $ apiOptions "addressDto"
  toEncoding = genericToEncoding $ apiOptions "addressDto"
</code>```

This works as you would expect.

Now say I want to parse a JSON structure of the format:

```<code>{ UUID: AddressDto, UUID: AddressDto, UUID: AddressDto }
</code>```

A reasonable Haskell representation would seem to be:

```<code>data AddressListDto = AddressListDto [(UUID, AddressDto)]
</code>```

Creating a helper function like so:

```<code>keyAndValueToList :: Either ServiceError AddressListDto -> Text -> DiscountDto -> Either ServiceError AddressListDto
keyAndValueToList (Left err) _ _ = Left err
keyAndValueToList (Right (AddressListDto ald)) k v = do
  let maybeUUID = fromString $ toS k
  case maybeUUID of
    Nothing        -> Left $ ParseError $ InvalidDiscountId k
    Just validUUID -> Right $ AddressListDto $ (validUUID, v) : ald
</code>```

and finally an instance of FromJSON:

```<code>instance FromJSON AddressListDto where
  parseJSON = withObject "tuple" $ \o -> do
    let result = foldlWithKey' keyAndValueToList (Right $ AddressListDto []) o
    case result of
      Right res -> pure res
      Left err -> throwError err
</code>```

This fails to compile with:

```<code>Couldn't match type ‘aeson-1.4.5.0:Data.Aeson.Types.Internal.Value’
                     with ‘AddressDto’
      Expected type: unordered-containers-0.2.10.0:Data.HashMap.Base.HashMap
                       Text AddressDto
</code>```

Two questions:

1) How do I make sure the nested values in the hashmap get parsed correctly to an AddressDto.
2) How do I avoid forcing the initial value into an either? Is there a function I could use instead of foldlWithKey' that didn't make me wrap the initial value like this?

答:
Funny answer. To implement parseJSON, you can use

```<code>parseJSON :: Value -> Parser (HashMap Text AddressDto)
</code>```

...but even better, why not just use a type alias instead of a fresh data type, so:

```<code>type AddressListDto = HashMap UUID AddressDto
</code>```

This already has a suitable FromJSON instance, so then you don't even need to write any code yourself.

Body:
Say I have the following structure:

data AddressDto = AddressDto
  { addressDtoId                   :: UUID
  , addressDtoCode                 :: Text
  , addressDtoCity                 :: Maybe Text
  , addressDtoStreet               :: Text
  , addressDtoPostCode             :: Text
  } deriving (Eq, Show, Generic)

instance FromJSON AddressDto where
  parseJSON = genericParseJSON $ apiOptions "addressDto"

instance ToJSON AddressDto where
  toJSON = genericToJSON $ apiOptions "addressDto"
  toEncoding = genericToEncoding $ apiOptions "addressDto"

This works as you would expect.

Now say I want to parse a JSON structure of the format:

{ UUID: AddressDto, UUID: AddressDto, UUID: AddressDto }

A reasonable Haskell representation would seem to be:

data AddressListDto = AddressListDto [(UUID, AddressDto)]

Creating a helper function like so:

keyAndValueToList :: Either ServiceError AddressListDto -> Text -> DiscountDto -> Either ServiceError AddressListDto
keyAndValueToList (Left err) _ _ = Left err
keyAndValueToList (Right (AddressListDto ald)) k v = do
  let maybeUUID = fromString $ toS k
  case maybeUUID of
    Nothing        -> Left $ ParseError $ InvalidDiscountId k
    Just validUUID -> Right $ AddressListDto $ (validUUID, v) : ald

and finally an instance of FromJSON:

instance FromJSON AddressListDto where
  parseJSON = withObject "tuple" $ \o -> do
    let result = foldlWithKey' keyAndValueToList (Right $ AddressListDto []) o
    case result of
      Right res -> pure res
      Left err -> throwError err

This fails to compile with:

Couldn't match type ‘aeson-1.4.5.0:Data.Aeson.Types.Internal.Value’
                     with ‘AddressDto’
      Expected type: unordered-containers-0.2.10.0:Data.HashMap.Base.HashMap
                       Text AddressDto

Two questions:

1) How do I make sure the nested values in the hashmap get parsed correctly to an AddressDto.
2) How do I avoid forcing the initial value into an either? Is there a function I could use instead of foldlWithKey' that didn't make me wrap the initial value like this?

Body:
Funny answer. To implement parseJSON, you can use

parseJSON :: Value -> Parser (HashMap Text AddressDto)

...but even better, why not just use a type alias instead of a fresh data type, so:

type AddressListDto = HashMap UUID AddressDto

This already has a suitable FromJSON instance, so then you don't even need to write any code yourself.


问:
How to configure NGINX for Vue and Django?
I was following this tutorial to create a backend and it worked.

I made simple a Django REST admin panel to upload images, it worked.

Then I created Vue frontend app, run npm run serve while in 'VScode remote' and it worked (images are fetched from Django and styled by Vue in my localhost).

The PROBLEM is it's not obvious how to make all this work in the production VPS server (i mean from Vue 'dist' folder after vue run build).
Everything I tried just gives me a 404 error or ruins the Django admin panel.

Here are my NGINX settings :

```<code>server {
server_name kruglovks.xyz www.kruglovks.xyz;
client_max_body_size 100m;

location = /favicon.ico { access_log off; log_not_found off; }

location /static {
    root /home/kirill/myprojectdir/myproject;
}

location /media {
    root /home/kirill/myprojectdir/myproject;
}

location /dist {
    try_files $uri $uri/ /index.html;
    alias /home/kirill/myprojectdir/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}
</code>```

Vue router is set to history mode.

Please, I need some info on how to make Vue work in this configuration.

P.S. Maybe there is an alternative way of using Vue alongside Django?

Thank you so much and have a nice day!

答:
That was a huge step forward, not a 404 but blank page called 'frontend' and browser refused to find css and js.

Later with a friends help and thisguide i could reconfigure nginx settings to this :

```<code>server {
listen      80;
server_name kruglovks.xyz www.kruglovks.xyz;
root /home/sasha/myprojectdir/myproject/dist/;
client_max_body_size 100m;

location = /favicon.ico { access_log off; log_not_found off; }

location /static {
    alias /home/sasha/myprojectdir/myproject/static;
}

location /media {
    alias /home/sasha/myprojectdir/myproject/media;
}

location / {
    try_files $uri $uri/ /index.html;
}

location ^~ /api/ {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}

location ^~ /admin {
     include proxy_params;
     proxy_pass http://unix:/run/gunicorn.sock;
}
</code>```

and it works now !

Thank you so muck @Danizavtz, you saved me like weeks of life ...

Body:
I was following this tutorial to create a backend and it worked.

I made simple a Django REST admin panel to upload images, it worked.

Then I created Vue frontend app, run npm run serve while in 'VScode remote' and it worked (images are fetched from Django and styled by Vue in my localhost).

The PROBLEM is it's not obvious how to make all this work in the production VPS server (i mean from Vue 'dist' folder after vue run build).
Everything I tried just gives me a 404 error or ruins the Django admin panel.

Here are my NGINX settings :

server {
server_name kruglovks.xyz www.kruglovks.xyz;
client_max_body_size 100m;

location = /favicon.ico { access_log off; log_not_found off; }

location /static {
    root /home/kirill/myprojectdir/myproject;
}

location /media {
    root /home/kirill/myprojectdir/myproject;
}

location /dist {
    try_files $uri $uri/ /index.html;
    alias /home/kirill/myprojectdir/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}

Vue router is set to history mode.

Please, I need some info on how to make Vue work in this configuration.

P.S. Maybe there is an alternative way of using Vue alongside Django?

Thank you so much and have a nice day!

Body:
That was a huge step forward, not a 404 but blank page called 'frontend' and browser refused to find css and js.

Later with a friends help and thisguide i could reconfigure nginx settings to this :

server {
listen      80;
server_name kruglovks.xyz www.kruglovks.xyz;
root /home/sasha/myprojectdir/myproject/dist/;
client_max_body_size 100m;

location = /favicon.ico { access_log off; log_not_found off; }

location /static {
    alias /home/sasha/myprojectdir/myproject/static;
}

location /media {
    alias /home/sasha/myprojectdir/myproject/media;
}

location / {
    try_files $uri $uri/ /index.html;
}

location ^~ /api/ {
    include proxy_params;
    proxy_pass http://unix:/run/gunicorn.sock;
}

location ^~ /admin {
     include proxy_params;
     proxy_pass http://unix:/run/gunicorn.sock;
}

and it works now !

Thank you so muck @Danizavtz, you saved me like weeks of life ...


问:
How can I set background color per tick by MQL4?
How can I set background color per tick like following by MQL4?

I couldn't find in documentation.

https://mt4trader.net/wp-content/uploads/2015-08-17_hikinashibg.jpg

答: I use array of colors and a static variable in the OnTick function to pick new color upon every call for the function. the same logic can be used for any function you'll define outside the OnTick function. A static variable will enable you to keep a value of the index of the used color from the array in the function after execution.


问:
React Native Picker moves back to first item
This works as expected, where the picker stays on the selected item...

```<code><Picker
    selectedValue={this.state.person}
    onValueChange={(itemValue) => this.setState({person: itemValue})}
    style={styles.picker}>
    {Object.keys(coWorkers)
        .map((result, index) =>
            <Picker.Item
                label={`${coWorkers[result].name}(${coWorkers[result].likes})`}
                value={coWorkers[result].name}
                key={index}
            />
        )
    }
</Picker>
</code>```

I want to get multiple key/values from the coWorkers object in this.setState, so I am trying this...

```<code><Picker
    selectedValue={this.state.person}
    onValueChange={(itemValue) => this.setState({person: itemValue.name, likes: itemValue.likes})}
    style={styles.picker}>
    {Object.keys(coWorkers)
        .map((result, index) =>
            <Picker.Item
                label={`${coWorkers[result].name} (${coWorkers[result].likes})`}
                value={coWorkers[result]}
                key={index}
            />
        )
    }
</Picker>
</code>```

However, now the picker jumps back to the top (this.state is being correctly updated though).

答:
If someone else has this problem and the solutions above are not working, it might be because you don't have the selectedValue flag set to something:

```<code>// You can replace the null with an actual value in your array(check to see it's exact)
const [toLanguage, setToLanguage] = useState(null);

selectedValue={toLanguage}
</code>```

Body:
This works as expected, where the picker stays on the selected item...

<Picker
    selectedValue={this.state.person}
    onValueChange={(itemValue) => this.setState({person: itemValue})}
    style={styles.picker}>
    {Object.keys(coWorkers)
        .map((result, index) =>
            <Picker.Item
                label={`${coWorkers[result].name}(${coWorkers[result].likes})`}
                value={coWorkers[result].name}
                key={index}
            />
        )
    }
</Picker>

I want to get multiple key/values from the coWorkers object in this.setState, so I am trying this...

<Picker
    selectedValue={this.state.person}
    onValueChange={(itemValue) => this.setState({person: itemValue.name, likes: itemValue.likes})}
    style={styles.picker}>
    {Object.keys(coWorkers)
        .map((result, index) =>
            <Picker.Item
                label={`${coWorkers[result].name} (${coWorkers[result].likes})`}
                value={coWorkers[result]}
                key={index}
            />
        )
    }
</Picker>

However, now the picker jumps back to the top (this.state is being correctly updated though).

Body:
If someone else has this problem and the solutions above are not working, it might be because you don't have the selectedValue flag set to something:

// You can replace the null with an actual value in your array(check to see it's exact)
const [toLanguage, setToLanguage] = useState(null);

selectedValue={toLanguage}


问:
'import matplotlib' gives 'module not found error'
pip install matplotlib
says requirement already satisfied.
I'm on a Mac and have looked through tons of answers online but can't get matplotlib to work. I'd appreciate any suggestions.

答: Maybe you install it in one venv and try to import in other one.</p>


问:
ArrayList value show the column and related values in angular table

var ArrayList = [{ Width: "3" }, { Width: "3.9" }, { Width: "4.4" },
{ Width: "2" }, { Width: "2.5" }, { Width: "1.625" }, { Width: null },
{ VoltageToleranceMax: null }, { ThresholdVoltage: null },
{ ThresholdVoltage: "2.55/2.88" }, { ThresholdVoltage: "1.2" },
{ ThresholdVoltage: "1.665" }, { ThresholdVoltage: "3.3" }]
```

<p>Above array, list convert separate column</p>

<p>My Result:</p>

```Width | Threshold Voltage-Nom

3     |  2.55/2.88
3.9   |  1.2
4.4   |  1.665
2     |  3.3
2.5
1.625
```

convert the Array List to HTML table show in column and values

答:
In ts :- </p>

```<code>public arrayList = [{Width: "3"} {Width: "3.9"} {Width: "4.4"} {Width: "2"} {Width: "2.5"} {Width: "1.625"} {Width: null} {Voltage Tolerance-Max: null} {Threshold Voltage: null} {Threshold Voltage: "2.55/2.88"} {Threshold Voltage: "1.2"} {Threshold Voltage: "1.665"} {Threshold Voltage: "3.3"} ];

public modifiedData = {};

ngOnInit() {
   this.filterArray();
}

public filterArray() {
   this.arrayList.forEach((item) => {
      var itemArr = Object.entries(item)[0];
      if(!modifiedData[itemArr[0]]) {
         modifiedData[itemArry[0]] = [];
      }
      modifiedData[itemArry[0]].push(itemArry[1]);
   });
}
</code>```

<p>In HTML :- </p>

```<code><table>
   <thead>
     <tr>
        <th *ngFor="let data of modifiedData|keyvalue">{{data.key}}</th>
     </tr>
   </thead>
   <tbody>
     <tr>
      <ng-container *ngFor="let data of modifiedData|keyvalue">
           <td>
                <table>
                    <tr *ngFor="let item of data.value">
                       <td>{{item}}</td>
                    <tr>
                </table>
           </td>
      </ng-container>
     </tr>
   </tbody>
</table>
</code>```

Body:
var ArrayList = [{ Width: "3" }, { Width: "3.9" }, { Width: "4.4" },
{ Width: "2" }, { Width: "2.5" }, { Width: "1.625" }, { Width: null },
{ VoltageToleranceMax: null }, { ThresholdVoltage: null },
{ ThresholdVoltage: "2.55/2.88" }, { ThresholdVoltage: "1.2" },
{ ThresholdVoltage: "1.665" }, { ThresholdVoltage: "3.3" }]

Above array, list convert separate column

My Result:

Width | Threshold Voltage-Nom

3     |  2.55/2.88
3.9   |  1.2
4.4   |  1.665
2     |  3.3
2.5
1.625

convert the Array List to HTML table show in column and values

Body:
In ts :-

public arrayList = [{Width: "3"} {Width: "3.9"} {Width: "4.4"} {Width: "2"} {Width: "2.5"} {Width: "1.625"} {Width: null} {Voltage Tolerance-Max: null} {Threshold Voltage: null} {Threshold Voltage: "2.55/2.88"} {Threshold Voltage: "1.2"} {Threshold Voltage: "1.665"} {Threshold Voltage: "3.3"} ];

public modifiedData = {};

ngOnInit() {
   this.filterArray();
}

public filterArray() {
   this.arrayList.forEach((item) => {
      var itemArr = Object.entries(item)[0];
      if(!modifiedData[itemArr[0]]) {
         modifiedData[itemArry[0]] = [];
      }
      modifiedData[itemArry[0]].push(itemArry[1]);
   });
}

In HTML :-

<table>
   <thead>
     <tr>
        <th *ngFor="let data of modifiedData|keyvalue">{{data.key}}</th>
     </tr>
   </thead>
   <tbody>
     <tr>
      <ng-container *ngFor="let data of modifiedData|keyvalue">
           <td>
                <table>
                    <tr *ngFor="let item of data.value">
                       <td>{{item}}</td>
                    <tr>
                </table>
           </td>
      </ng-container>
     </tr>
   </tbody>
</table>


问:
How can I have flutter's navigator push a route in the navigation bar instead if fullscreen
In Flutter, How do I push a screen so that it appears inside the tab, rather than full screen.

Here is my code:

```<code>Card(
  color: Colors.white,
  child: ListTile(
    title: Text("PRIVACY POLICY", style: Styles.textDark),
    trailing: Icon(Icons.arrow_forward_ios),
    onTap: () => Navigator.of(context).push(CupertinoPageRoute(builder: (context) => SinglePageTextView("PRIVACY POLICY", "/assets/privacy.txt"))),
  ),
)
</code>```

PS: I have tried the fullscreenDialog setting on CupertinoPageRoute, and it does nothing!

Source screen:

When tapped Privacy Policy, this shows up:

This is what I am trying to achieve (tab bar is still showing!):

Thanks in advance for the help.

答: Instead of using Navigator, use setState() to change the current page content to one you need.</p>

Body:
In Flutter, How do I push a screen so that it appears inside the tab, rather than full screen.

Here is my code:

Card(
  color: Colors.white,
  child: ListTile(
    title: Text("PRIVACY POLICY", style: Styles.textDark),
    trailing: Icon(Icons.arrow_forward_ios),
    onTap: () => Navigator.of(context).push(CupertinoPageRoute(builder: (context) => SinglePageTextView("PRIVACY POLICY", "/assets/privacy.txt"))),
  ),
)

PS: I have tried the fullscreenDialog setting on CupertinoPageRoute, and it does nothing!

Source screen:

When tapped Privacy Policy, this shows up:

This is what I am trying to achieve (tab bar is still showing!):

Thanks in advance for the help.


问:
Program exception when I run a program with TextIO
I wrote the following test program using Eclipse IDE

```<code>01 package Prog01Cal
02
03 import textio.TextIO;
04
05 public class Prog01CalcClas
06
07  public static void main(String[] args) {
08      // TODO Auto-generated method stub
09
10      // Variables Declaracion;
11      int var1;
12
13      // Read line
14      var1 = TextIO.getlnInt();
15
16      // Print line
17      System.out.print("This is a Test Program");
18      }
19
20 }
</code>```

Case 1:

When I comment out line 14 and I run the program, a window popup with this message:

Errors in workspace

  Errors exist in required project(s):

  Prog01Calc

  Proceed with launch?

I responsed "Proceed"

And the program apparently run fine and print the line:

This is a Test Program

Case 2:

But when line 14 is not comment, the program got the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

  at textio.TextIO.getlnInt(TextIO.java:547)

  at Prog01Calc.Prog01CalcClass.main(Prog01CalcClass.java:14)

And the test program do not print anything

Just to clarify the project window in eclipse contains the following:

Prog01Calc

  JRE System Library [jdk 14.0.1]

  __src

  ____Prog01Calc

  ______Prog01CalcClass.java

  ________Prog01CalcClass

  __________mainString[] ) : void

  __textio

  ____TextIO.java

Can somebody help me with this exception error?

I don't know whats wrong.

答: I didn't pay attention to the file structure at first, I had assumed textio was added as a jar, but it seems like the source code is in a single class in your project. My guess is that you did not set textio as a source root, so Eclipse is not compiling it.  Move textio under src and it should work.

Body:
I wrote the following test program using Eclipse IDE

01 package Prog01Cal
02
03 import textio.TextIO;
04
05 public class Prog01CalcClas
06
07  public static void main(String[] args) {
08      // TODO Auto-generated method stub
09
10      // Variables Declaracion;
11      int var1;
12
13      // Read line
14      var1 = TextIO.getlnInt();
15
16      // Print line
17      System.out.print("This is a Test Program");
18      }
19
20 }

Case 1:

When I comment out line 14 and I run the program, a window popup with this message:

Errors in workspace

  Errors exist in required project(s):

  Prog01Calc

  Proceed with launch?

I responsed "Proceed"

And the program apparently run fine and print the line:

This is a Test Program

Case 2:

But when line 14 is not comment, the program got the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

  at textio.TextIO.getlnInt(TextIO.java:547)

  at Prog01Calc.Prog01CalcClass.main(Prog01CalcClass.java:14)

And the test program do not print anything

Just to clarify the project window in eclipse contains the following:

Prog01Calc

  JRE System Library [jdk 14.0.1]

  __src

  ____Prog01Calc

  ______Prog01CalcClass.java

  ________Prog01CalcClass

  __________mainString[] ) : void

  __textio

  ____TextIO.java

Can somebody help me with this exception error?

I don't know whats wrong.


问:
Evaluating boolean expression with recursive
I've wrote a program to recursively evaluate boolean expression. But when I run with input "(1|1)", in the second recursion of function S, specifically in line result = result || P() instead of step into P(), it passes the line and returns result. However it works fine with input "(~1|1)". How can I fix this?

```<code>#include <stdbool.h>
#include <stdlib.h>

char *s;
char *f;
bool P(), A();

// The grammar is:
// S -> P||S | P&&S | P
// P -> A | ~A
// A -> (S) | 0 | 1

bool S() {
    bool result = P();
    if (*s == '|') {
        s++;
        result = result || P();
    }
    else
        if (*s == '&') {
            s++;
            result = result && P();
        }
    return result;
}

bool P() {
    if (*s == '~') {
        s++;
        return !A();
    }
    else
    {
        return A();
    }
}

bool A() {
    bool result;
    if (*s == '(') {
        s++;
        result = S();
        if (*s == ')') s++;
        else {
            printf("Syntaktisch falsch! Stelle %ld, Art: Anzahl von '(' und ')' sind nicht gleich\n", s-f);
            exit(1);
        }
    }
    else
        if (*s == '1') {
            s++;
            result = true;
        }
        else
            if (*s == '0') {
                s++;
                result = false;
            }
            else {
                printf("Syntaktisch falsch! Stelle: %ld, Art: Boolscher Ausdruck fehlt\n", s-f); // Hier gibt Fehlermeldung aus, wenn Input String ist nur '~'.
                exit(1);
            }

    return result;
}

int main(int argc, char *argv[])
{
    bool result;
    if (argc != 2) exit(1);
    s = argv[1];
    f = s;
    result = S();
    printf("%d\n", result);
    return 0;
}
</code>```

答:
result || P() only requires that ONE of the values - result OR P() - be TRUE in order to satisfy the expression. If result is TRUE when result || P() is evaluated the function is not required to be called - this is known as "short-circuit evaluation". Change your code to:

```<code>bool p_val;

p_val = P();
result = result || p_val;
</code>```

in order to ensure that the function is actually invoked.

Body:
I've wrote a program to recursively evaluate boolean expression. But when I run with input "(1|1)", in the second recursion of function S, specifically in line result = result || P() instead of step into P(), it passes the line and returns result. However it works fine with input "(~1|1)". How can I fix this?

#include <stdbool.h>
#include <stdlib.h>

char *s;
char *f;
bool P(), A();

// The grammar is:
// S -> P||S | P&&S | P
// P -> A | ~A
// A -> (S) | 0 | 1

bool S() {
    bool result = P();
    if (*s == '|') {
        s++;
        result = result || P();
    }
    else
        if (*s == '&') {
            s++;
            result = result && P();
        }
    return result;
}

bool P() {
    if (*s == '~') {
        s++;
        return !A();
    }
    else
    {
        return A();
    }
}

bool A() {
    bool result;
    if (*s == '(') {
        s++;
        result = S();
        if (*s == ')') s++;
        else {
            printf("Syntaktisch falsch! Stelle %ld, Art: Anzahl von '(' und ')' sind nicht gleich\n", s-f);
            exit(1);
        }
    }
    else
        if (*s == '1') {
            s++;
            result = true;
        }
        else
            if (*s == '0') {
                s++;
                result = false;
            }
            else {
                printf("Syntaktisch falsch! Stelle: %ld, Art: Boolscher Ausdruck fehlt\n", s-f); // Hier gibt Fehlermeldung aus, wenn Input String ist nur '~'.
                exit(1);
            }

    return result;
}

int main(int argc, char *argv[])
{
    bool result;
    if (argc != 2) exit(1);
    s = argv[1];
    f = s;
    result = S();
    printf("%d\n", result);
    return 0;
}

Body:
result || P() only requires that ONE of the values - result OR P() - be TRUE in order to satisfy the expression. If result is TRUE when result || P() is evaluated the function is not required to be called - this is known as "short-circuit evaluation". Change your code to:

bool p_val;

p_val = P();
result = result || p_val;

in order to ensure that the function is actually invoked.


问:
How can I test LDAP using ASPNETBOILERPLATE?
ASPNET Boilerplate or ASPNETZero have the ability to integrate with LDAP. Apparently the configuration is easy, but it only lets me configure a Domain, a User and Password. I was wondering if anyone has a working example with a test server of LDAP? Currently I have enabled the LDAP Authentication:

```<code>//Enable LDAP authentication (It can be enabled only if MultiTenancy is disabled!)
Configuration.Modules.ZeroLdap().Enable(typeof(Authorization.Ldap.AppLdapAuthenticationSource));
</code>```

And using a test LDAP server for it. Once I enable the LDAP authentication I configure the domain, user and password, but I am getting an error on the method GetLoginResultAsync in TokenAuthController.cs. The error is as follows:

```<code>System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=System.DirectoryServices.AccountManagement
  StackTrace:
   at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
   at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password)
   at Abp.Zero.Ldap.Authentication.LdapAuthenticationSource`2.<CreatePrincipalContext>d__13.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Zero.Ldap.Authentication.LdapAuthenticationSource`2.<TryAuthenticateAsync>d__6.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Abp.Authorization.AbpLogInManager`3.<TryLoginFromExternalAuthenticationSources>d__41.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Authorization.AbpLogInManager`3.<LoginAsyncInternal>d__37.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Authorization.AbpLogInManager`3.<LoginAsync>d__36.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Threading.InternalAsyncHelper.<AwaitTaskWithPostActionAndFinallyAndGetResult>d__5`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Paradigm.Web.Controllers.TokenAuthController.<GetLoginResultAsync>d__43.MoveNext() in C:\Users\victo\Documents\Work\NS\JNJ\QueDevBase2\src\Paradigm.Web.Core\Controllers\TokenAuthController.cs:line 618

  This exception was originally thrown at this call stack:
    System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(string, ref System.DirectoryServices.AccountManagement.ServerProperties)
    System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
    System.DirectoryServices.AccountManagement.PrincipalContext.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType, string, string, System.DirectoryServices.AccountManagement.ContextOptions, string, string)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    Abp.Authorization.AbpLogInManager<TTenant, TRole, TUser>.LoginAsyncInternal(string, string, string, bool)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    ...
    [Call Stack Truncated]
</code>```

Any help is appreciated.

答:
The current Abp.Zero.Ldap used PrincipalContext:
PrincipalContext - I Can't connect to a local openldap server

For AD add the settings in the DefaultSettingsCreator.cs:

```<code>AddSettingIfNotExists(LdapSettingNames.UserName, "AD_Administrator", tenantId);
AddSettingIfNotExists(LdapSettingNames.Password, "password", tenantId);
AddSettingIfNotExists(LdapSettingNames.ContextType, "Domain.Context", tenantId);
AddSettingIfNotExists(LdapSettingNames.Domain, "test.local");
</code>```

Note: If you don't define a domain, username and password, LDAP authentication works for the current domain if your application runs in a domain with appropriate privileges. https://aspnetboilerplate.com/Pages/Documents/Zero/User-Management#settings

For LDAP online Test Server

Check out: https://github.com/do-it-ger/DoAspnetboilerplateLdap for the Novell.Ldap implementation.
Test runs against the online Ldap test Server: ldap.forumsys.com

Body:
ASPNET Boilerplate or ASPNETZero have the ability to integrate with LDAP. Apparently the configuration is easy, but it only lets me configure a Domain, a User and Password. I was wondering if anyone has a working example with a test server of LDAP? Currently I have enabled the LDAP Authentication:

//Enable LDAP authentication (It can be enabled only if MultiTenancy is disabled!)
Configuration.Modules.ZeroLdap().Enable(typeof(Authorization.Ldap.AppLdapAuthenticationSource));

And using a test LDAP server for it. Once I enable the LDAP authentication I configure the domain, user and password, but I am getting an error on the method GetLoginResultAsync in TokenAuthController.cs. The error is as follows:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=System.DirectoryServices.AccountManagement
  StackTrace:
   at System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(String serverName, ServerProperties& properties)
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
   at System.DirectoryServices.AccountManagement.PrincipalContext..ctor(ContextType contextType, String name, String container, ContextOptions options, String userName, String password)
   at Abp.Zero.Ldap.Authentication.LdapAuthenticationSource`2.<CreatePrincipalContext>d__13.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Zero.Ldap.Authentication.LdapAuthenticationSource`2.<TryAuthenticateAsync>d__6.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Abp.Authorization.AbpLogInManager`3.<TryLoginFromExternalAuthenticationSources>d__41.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Authorization.AbpLogInManager`3.<LoginAsyncInternal>d__37.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Authorization.AbpLogInManager`3.<LoginAsync>d__36.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Abp.Threading.InternalAsyncHelper.<AwaitTaskWithPostActionAndFinallyAndGetResult>d__5`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Paradigm.Web.Controllers.TokenAuthController.<GetLoginResultAsync>d__43.MoveNext() in C:\Users\victo\Documents\Work\NS\JNJ\QueDevBase2\src\Paradigm.Web.Core\Controllers\TokenAuthController.cs:line 618

  This exception was originally thrown at this call stack:
    System.DirectoryServices.AccountManagement.PrincipalContext.ReadServerConfig(string, ref System.DirectoryServices.AccountManagement.ServerProperties)
    System.DirectoryServices.AccountManagement.PrincipalContext.DoServerVerifyAndPropRetrieval()
    System.DirectoryServices.AccountManagement.PrincipalContext.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType, string, string, System.DirectoryServices.AccountManagement.ContextOptions, string, string)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    Abp.Authorization.AbpLogInManager<TTenant, TRole, TUser>.LoginAsyncInternal(string, string, string, bool)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    ...
    [Call Stack Truncated]

Any help is appreciated.

Body:
The current Abp.Zero.Ldap used PrincipalContext:
PrincipalContext - I Can't connect to a local openldap server

For AD add the settings in the DefaultSettingsCreator.cs:

AddSettingIfNotExists(LdapSettingNames.UserName, "AD_Administrator", tenantId);
AddSettingIfNotExists(LdapSettingNames.Password, "password", tenantId);
AddSettingIfNotExists(LdapSettingNames.ContextType, "Domain.Context", tenantId);
AddSettingIfNotExists(LdapSettingNames.Domain, "test.local");

Note: If you don't define a domain, username and password, LDAP authentication works for the current domain if your application runs in a domain with appropriate privileges. https://aspnetboilerplate.com/Pages/Documents/Zero/User-Management#settings

For LDAP online Test Server

Check out: https://github.com/do-it-ger/DoAspnetboilerplateLdap for the Novell.Ldap implementation.
Test runs against the online Ldap test Server: ldap.forumsys.com


问:
how do i check if all rows have similiar data in one column
so I am working on restaurant and I have tables(I am referring to actual table not sql table) and clients in each table, I am having trouble making a query that returns the table_ID of the tables that contains only customers from the one family
for the following table named a :

```<code>costumer_name|| table_ID
-----        ||----
Levi         ||   1
Levi         ||   1
Levi         ||   1
Levi         ||   1
Cohen        ||   2
Cohen        ||   2
shalev       ||   3
shalev       ||   3
shalev       ||   3
shalev       ||   3
jacob        ||   3
</code>```

the output will be only table 1 and 2 because in table 3, there are shalev and jacob.
i have managed to make it work only with a specific table using a condition (which table_ID)
example for tablenumber 1:

```<code>select family_name,table_ID from clients
group by table_id
having table_id = '1' and count(distinct family_name) =1
</code>```

I can do it manually for each table_ID but is it possible to do it in one query?
I am having trouble doing it

答:
you can just check the records where count of family_name is 1</p>

```<code>select Min(family_name) family_name, table_ID from clients
group by table_id
having count(family_name) = 1
</code>```

Body:
so I am working on restaurant and I have tables(I am referring to actual table not sql table) and clients in each table, I am having trouble making a query that returns the table_ID of the tables that contains only customers from the one family
for the following table named a :

costumer_name|| table_ID
-----        ||----
Levi         ||   1
Levi         ||   1
Levi         ||   1
Levi         ||   1
Cohen        ||   2
Cohen        ||   2
shalev       ||   3
shalev       ||   3
shalev       ||   3
shalev       ||   3
jacob        ||   3

the output will be only table 1 and 2 because in table 3, there are shalev and jacob.
i have managed to make it work only with a specific table using a condition (which table_ID)
example for tablenumber 1:

select family_name,table_ID from clients
group by table_id
having table_id = '1' and count(distinct family_name) =1

I can do it manually for each table_ID but is it possible to do it in one query?
I am having trouble doing it

Body:
you can just check the records where count of family_name is 1

select Min(family_name) family_name, table_ID from clients
group by table_id
having count(family_name) = 1


问:
Cron won't execute MySql in PHP Script in Centos7
Hello and thanks for looking at this.

Cron Jobs didn't execute this morning because they send emails and I didn't get them. Running Centos 7 at GoDaddy.

Here's the cron command...

/usr/local/bin/ea-php56 /home/rbigroup/public_html/cron/cron-test.php >/dev/null 2>&1

When testing the script in the browser, works fine. However when I remove the MySql in the script, the Cron works fine.

I'm totally baffled an flustered. Any help is super appreciated! Thanks for your time!

Here's the php code...

```<code><?php require $_SERVER['DOCUMENT_ROOT']."/Connections/connect.php";  ?><?php include "cron-recipients.php"; ?>
<?php

echo $_SERVER['DOCUMENT_ROOT'];
$date = date('Y-m-d',$date_start);

echo $date."<br>";

mysqli_select_db($db);
$insertSQL = sprintf("INSERT INTO test_table (text_field,`date_field`) VALUES ('Hello','$date')");

echo $insertSQL."<br>";
$Result1 = mysqli_query($db,$insertSQL) or die(mysqli_error($db));

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: noreply@rbirestaurantgroup.com' . "\r\n";

$subject = "Confirming Cron-Test Is Working on PPie Server";

$to = $RECIPIENT_SET1; //attach emails to the TO field
//$to = 'apsubmit@secureserver.net';

$message = '<html>
    <head>
      <title>Cron Report</title>
    </head>
    <body><h2>Cron Test</h2>
    Your test works.
    </body>
    </html>';

mail($to, $subject, $message, $headers);

echo "Cron Tester Complete"."<br>";

echo $to;

 ?>
</code>```

答:
Problem solved!

Hopefully this will help people in the future. It turns out that the problem was this line at the very top of my script.

```<code><?php date_default_timezone_set('America/New_York'); ?>
</code>```

I added it because I noticed that the time when the Crons at GoDaddy fire is there 3 hours earlier than my time here on the east coast. Its 3am at the server when its 6 am here. I wanted to sync the times it was going out of the server so I added the above code at the top and uploaded.

I tested the script in the browser, made the cron command, just like all the other ones, and set the time for the morning. Called it a day. Morning came. No email responses from any cron and no SQL Inserts.

I then tried to test the script with cron by setting a cron command to hit every 1 minutes but it wasn't working. No email response or SQL insert. Tried everything. Different cron commands and what not. Hit up Stack Overflow (total newbie here ;)) Sweatin...

After a few hours on the phone with GoDaddy and going thru every action, the representative realized when I mentioned the above code that it may have done some thing to the php.ini file. Sure enough it had altered it somehow, causing the cron to not fire when SQL was in the script for some odd reason. He said it added some weird characters in the file causing the server to fall back to just the server INI file. He corrected the file and boom... all back to normal.

Anyway this had me stumped. But all is well and learned a lesson. Don't mess with the cron. Thanks for everyones help. Hope this helps others!

Body:
Hello and thanks for looking at this.

Cron Jobs didn't execute this morning because they send emails and I didn't get them. Running Centos 7 at GoDaddy.

Here's the cron command...

/usr/local/bin/ea-php56 /home/rbigroup/public_html/cron/cron-test.php >/dev/null 2>&1

When testing the script in the browser, works fine. However when I remove the MySql in the script, the Cron works fine.

I'm totally baffled an flustered. Any help is super appreciated! Thanks for your time!

Here's the php code...

<?php require $_SERVER['DOCUMENT_ROOT']."/Connections/connect.php";  ?><?php include "cron-recipients.php"; ?>
<?php

echo $_SERVER['DOCUMENT_ROOT'];
$date = date('Y-m-d',$date_start);

echo $date."
";

mysqli_select_db($db);
$insertSQL = sprintf("INSERT INTO test_table (text_field,`date_field`) VALUES ('Hello','$date')");

echo $insertSQL."
";
$Result1 = mysqli_query($db,$insertSQL) or die(mysqli_error($db));

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: noreply@rbirestaurantgroup.com' . "\r\n";

$subject = "Confirming Cron-Test Is Working on PPie Server";

$to = $RECIPIENT_SET1; //attach emails to the TO field
//$to = 'apsubmit@secureserver.net';

$message = '

      <title>Cron Report</title>

Cron Test

    Your test works.

    ';

mail($to, $subject, $message, $headers);

echo "Cron Tester Complete"."
";

echo $to;

 ?>

Body:
Problem solved!

Hopefully this will help people in the future. It turns out that the problem was this line at the very top of my script.

<?php date_default_timezone_set('America/New_York'); ?>

I added it because I noticed that the time when the Crons at GoDaddy fire is there 3 hours earlier than my time here on the east coast. Its 3am at the server when its 6 am here. I wanted to sync the times it was going out of the server so I added the above code at the top and uploaded.

I tested the script in the browser, made the cron command, just like all the other ones, and set the time for the morning. Called it a day. Morning came. No email responses from any cron and no SQL Inserts.

I then tried to test the script with cron by setting a cron command to hit every 1 minutes but it wasn't working. No email response or SQL insert. Tried everything. Different cron commands and what not. Hit up Stack Overflow (total newbie here ;)) Sweatin...

After a few hours on the phone with GoDaddy and going thru every action, the representative realized when I mentioned the above code that it may have done some thing to the php.ini file. Sure enough it had altered it somehow, causing the cron to not fire when SQL was in the script for some odd reason. He said it added some weird characters in the file causing the server to fall back to just the server INI file. He corrected the file and boom... all back to normal.

Anyway this had me stumped. But all is well and learned a lesson. Don't mess with the cron. Thanks for everyones help. Hope this helps others!