问:
Laravel project shows flash of html without css on first load
I have a Laravel project.  When I load, it shows just HTML flash first then load CSS with little delay.  How can I fix this?

I tried preloader but it shows flash and then preloader means there is still a little flash of simple HTML between preloader.

I tried this in header file:

```<code><div class="preloader"></div>
<script>
    $(window).load(function() {
        $('.preloader').fadeOut('slow');
    });
</code>```

CSS:

```<code>.preloader {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background-image: url("../img/loader.gif");
    background-repeat: no-repeat;
    background-color: #FFF;
    background-position: center;
}
</code>```

答: Place your rest of code other than preloader inside some container, by default make that container style as display:none and as your preloader fades make that container style display:block


来源: stackexchange

问:
How to get array of dates between two dates in laravel?
I want to get dates between two dates in an array. The scenario is the following: I want to get daily sales cash collection and there is one filter of $fromdate and $todate. So even if I don't get any sales for an specific date I have to show that in the table.

答:
Use DatePeriod class to create the range of dates based on months or days

```<code><?php

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2013-10-31' );

$interval = new DateInterval('P1M');
$daterange = new DatePeriod($begin, $interval ,$end);

$dates = [];

foreach($daterange as $date){
   $dates[] = $date->format("Y-m-d");
}

var_dump($dates);

?>
</code>```

if you want the range of dates to be by days, say from 2012-08-01 to 2012-08-25 then just change the interval like this $interval = new DateInterval('P1D');.

ContentLicense: CC BY-SA 4.0

Body:
Use DatePeriod class to create the range of dates based on months or days

<?php

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2013-10-31' );

$interval = new DateInterval('P1M');
$daterange = new DatePeriod($begin, $interval ,$end);

$dates = [];

foreach($daterange as $date){
   $dates[] = $date->format("Y-m-d");
}

var_dump($dates);

?>

if you want the range of dates to be by days, say from 2012-08-01 to 2012-08-25 then just change the interval like this $interval = new DateInterval('P1D');.


问:
Ruby-like Question: Make this function shorter (ActionScript 3)
I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?

```<code>    public static function format(n:int, minimumLength:int):String {
        var retVal:String = n.toString();
        var stillNeed:int = minimumLength - retVal.length;
        for (var i:int = 0; i < stillNeed; i++) {
            retVal = "0" + retVal;
        }
        return retVal;
    }
</code>```

Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.

If anybody wants to post some extremely short equivalent in some other language, that would be fun too.

答:
The as3corelib package put out by adobe has a nice little NumberFormatter class that uses a series of STATIC classes.  In this case you could use the addLeadingZero function.

```<code>//The following method is from the NumberFormatter class of the as3corelib package by Adobe.
public static function addLeadingZero(n:Number):String
{
var out:String = String(n);

if(n < 10 && n > -1)
{
    out = "0" + out;
}

return out;
}
</code>```

I included the function just to show it's simplicity, but I would use the package instead of yoinking the function because it provides many other useful features like StringUtils, encryption methods like MD5, blowfish, etc.

You can download the package here
For newer users you must provide a classpath to where this package lives.  It is also smart to import the classes instead of using their fully qualified class names.

OwnerDisplayName: Daniel Rosenstark

ContentLicense: CC BY-SA 2.5

Body:
I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?

    public static function format(n:int, minimumLength:int):String {
        var retVal:String = n.toString();
        var stillNeed:int = minimumLength - retVal.length;
        for (var i:int = 0; i < stillNeed; i++) {
            retVal = "0" + retVal;
        }
        return retVal;
    }

Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.

If anybody wants to post some extremely short equivalent in some other language, that would be fun too.

LastEditorDisplayName: Christophe Herreman

Body:
The as3corelib package put out by adobe has a nice little NumberFormatter class that uses a series of STATIC classes.  In this case you could use the addLeadingZero function.

//The following method is from the NumberFormatter class of the as3corelib package by Adobe.
public static function addLeadingZero(n:Number):String
{
var out:String = String(n);

if(n < 10 && n > -1)
{
    out = "0" + out;
}

return out;
}

I included the function just to show it's simplicity, but I would use the package instead of yoinking the function because it provides many other useful features like StringUtils, encryption methods like MD5, blowfish, etc.

You can download the package here
For newer users you must provide a classpath to where this package lives.  It is also smart to import the classes instead of using their fully qualified class names.

OwnerDisplayName: Brian Hodge

LastEditorDisplayName: Daniel Rosenstark


问:
Android can't remove padding around custom title bar
I'm adding a custom img to the header title but no matter what I do I still have a small gap on each side of the img (also shown in this question)

Here is the xml in my strings.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello"></string>
    <string name="app_name"></string>
    <style name="LargeTitleTheme" parent="android:Theme.Light">
        <item name="android:windowTitleSize">44dip</item>
    </style>
</resources>
</code>```

Here is the code in my activity (ignore the slop - desperate coding at this point)

```<code>ViewGroup decorView = (ViewGroup) this.getWindow().getDecorView();
    LinearLayout root = (LinearLayout) decorView.getChildAt(0);
    FrameLayout titleContainer = (FrameLayout) root.getChildAt(0);
    TextView title = (TextView) titleContainer.getChildAt(0);
    title.setGravity(Gravity.CENTER);
    Drawable drawable = getResources().getDrawable(R.drawable.nav);
    drawable.setBounds(0,0,0,0);
    title.setBackgroundDrawable(drawable);
    title.setPadding(0,0,0,0);
    title.setIncludeFontPadding(false);
</code>```

答: you could try making the setPadding values to negitive numbers</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm adding a custom img to the header title but no matter what I do I still have a small gap on each side of the img (also shown in this question)

Here is the xml in my strings.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello"></string>
    <string name="app_name"></string>

</resources>

Here is the code in my activity (ignore the slop - desperate coding at this point)

ViewGroup decorView = (ViewGroup) this.getWindow().getDecorView();
    LinearLayout root = (LinearLayout) decorView.getChildAt(0);
    FrameLayout titleContainer = (FrameLayout) root.getChildAt(0);
    TextView title = (TextView) titleContainer.getChildAt(0);
    title.setGravity(Gravity.CENTER);
    Drawable drawable = getResources().getDrawable(R.drawable.nav);
    drawable.setBounds(0,0,0,0);
    title.setBackgroundDrawable(drawable);
    title.setPadding(0,0,0,0);
    title.setIncludeFontPadding(false);


问:
Sequentially select parts of a string similar to ngram
Here is the problem I am trying to solve.

For example there is this string

```<code>my_string = 'jan feb mar'
</code>```

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

```<code>my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']
</code>```

What I tried is below and it is not what I want.

```<code>my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)
</code>```

Please help me out here. Thanks.

答:
How about something like this?  Just create a lookup for sorting</p>

```<code>import itertools

def my_function(my_string):
    def subsets(s):
      output = []
      for i in range(1,len(s)+1):
        output +=  list(itertools.combinations(s, i))
      return output

    my_list = my_string.split()
    my_order = {val:ind for ind,val in enumerate(my_list)}
    print(my_order)
    output =  subsets(my_list)
    output = [' '.join(sorted(list(i), key=my_order.get)) for i in output]
    return output
my_string = 'jan feb mar'
output = my_function(my_string)

print(output)
</code>```

Body:
Here is the problem I am trying to solve.

For example there is this string

my_string = 'jan feb mar'

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']

What I tried is below and it is not what I want.

my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)

Please help me out here. Thanks.

Body:
How about something like this?  Just create a lookup for sorting

import itertools

def my_function(my_string):
    def subsets(s):
      output = []
      for i in range(1,len(s)+1):
        output +=  list(itertools.combinations(s, i))
      return output

    my_list = my_string.split()
    my_order = {val:ind for ind,val in enumerate(my_list)}
    print(my_order)
    output =  subsets(my_list)
    output = [' '.join(sorted(list(i), key=my_order.get)) for i in output]
    return output
my_string = 'jan feb mar'
output = my_function(my_string)

print(output)


问:
Github Pages website favicon not showing
I'm hosting a website using Github Pages. I connected Cloudflare to the website because of SSL. When i finally added favicon.ico to my website and the following code in  to make the favicon show up, it still doesn't show up. What can i do?

```<code><link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
</code>```

(english is not my native language)

Edit: Seems like other people can see the favicon, except me. But why?

答:
Adding a question mark at the end of the path is one workaround.

```<code><link rel="shortcut icon" type="image/png" href="coin.png?">
</code>```

Try also using a URL from a site that has the image, it might work.

Body:
I'm hosting a website using Github Pages. I connected Cloudflare to the website because of SSL. When i finally added favicon.ico to my website and the following code in  to make the favicon show up, it still doesn't show up. What can i do?

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">

(english is not my native language)

Edit: Seems like other people can see the favicon, except me. But why?

Body:
Adding a question mark at the end of the path is one workaround.

<link rel="shortcut icon" type="image/png" href="coin.png?">

Try also using a URL from a site that has the image, it might work.


问:
UITextField Programmatically won't convert into string or take any binary operators Xcode
Prior to having this issue, I was using storyboards and outlets for text fields. However, I found it easier to work on my app programmatically.  Unfortunately, as I began to convert my app such as by programmatically making a text field I ran into some issues as I still have some functions such as my login function that was made for the text fields from the storyboards.  I'm still new swift so any solutions would be helpful.

I declared my email text field as such:

```<code>    var emailTxt: UITextField!
</code>```

The other aspects of the email text field are as such in the view did load function:

```<code>    emailTxt = UITextField(frame: CGRect(x: 77.0, y: 306.0, width: 262, height: 34))
    emailTxt.backgroundColor = .white
    emailTxt.borderStyle = .roundedRect
    emailTxt.keyboardAppearance = .light
    emailTxt.keyboardType = .emailAddress
    emailTxt.placeholder = "Email"
    emailTxt.font = UIFont.systemFont(ofSize: 14.0)
    emailTxt.textColor = .systemGreen
    emailTxt.tintColor = .systemGreen
    emailTxt.delegate = self

    self.view.addSubview(emailTxt)
</code>```

Text field functions outside the view did load:

```<code>func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
}
</code>```

Finally the area where I get the issues.

First, it says that for the guard statement there must be an else statement.

Then it says (Binary operator '!=' cannot be applied to operands of type 'UITextField?' and 'String') Then in the else statement it says (Closure expression is unused)

Finally, in the auth statement it gives the error: Cannot convert value of type 'UITextField' to expected argument type 'String' while underlining the email

Here is the code for that:

```<code>    guard let email = emailTxt
    email != "",
    let password = passwordTxt
    password != ""
        else {
            AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
            return

    }

    Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
        guard error == nil else {
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }
</code>```

答:
Your error is self explanatory, you are trying to use the UITextField type as String. Here what you need to use is the .hasText property of UIKeyInput protocol which UITextField conforms to. Here's how:

```<code>guard emailTxt.hasText,
passwordTxt.hasText
    else {
        AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
        return
}
let email = emailTxt.text!
let password = passwordTxt.text!
</code>```

You can force unwrap the text of UITextField because it defaults to empty String "". Even if it's set to nil it returns an empty string.

Body:
Prior to having this issue, I was using storyboards and outlets for text fields. However, I found it easier to work on my app programmatically.  Unfortunately, as I began to convert my app such as by programmatically making a text field I ran into some issues as I still have some functions such as my login function that was made for the text fields from the storyboards.  I'm still new swift so any solutions would be helpful.

I declared my email text field as such:

    var emailTxt: UITextField!

The other aspects of the email text field are as such in the view did load function:

    emailTxt = UITextField(frame: CGRect(x: 77.0, y: 306.0, width: 262, height: 34))
    emailTxt.backgroundColor = .white
    emailTxt.borderStyle = .roundedRect
    emailTxt.keyboardAppearance = .light
    emailTxt.keyboardType = .emailAddress
    emailTxt.placeholder = "Email"
    emailTxt.font = UIFont.systemFont(ofSize: 14.0)
    emailTxt.textColor = .systemGreen
    emailTxt.tintColor = .systemGreen
    emailTxt.delegate = self

    self.view.addSubview(emailTxt)

Text field functions outside the view did load:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
}

Finally the area where I get the issues.

First, it says that for the guard statement there must be an else statement.

Then it says (Binary operator '!=' cannot be applied to operands of type 'UITextField?' and 'String') Then in the else statement it says (Closure expression is unused)

Finally, in the auth statement it gives the error: Cannot convert value of type 'UITextField' to expected argument type 'String' while underlining the email

Here is the code for that:

    guard let email = emailTxt
    email != "",
    let password = passwordTxt
    password != ""
        else {
            AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
            return

    }

    Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
        guard error == nil else {
            AlertController.showAlert(self, title: "Error", message: error!.localizedDescription)
            return
        }

Body:
Your error is self explanatory, you are trying to use the UITextField type as String. Here what you need to use is the .hasText property of UIKeyInput protocol which UITextField conforms to. Here's how:

guard emailTxt.hasText,
passwordTxt.hasText
    else {
        AlertController.showAlert(self, title: "Missing Info", message: "Please fill out all fields")
        return
}
let email = emailTxt.text!
let password = passwordTxt.text!

You can force unwrap the text of UITextField because it defaults to empty String "". Even if it's set to nil it returns an empty string.


问:
How to copy matching properties from one object to another
I have these two objects:

```<code>obj1 = {a: '', b: ''}
obj2 = {a: '1', b: '2', c: '3'}
</code>```

I want to copy all matching properties from obj2 to obj1. What is the best way of doing that in Typescript?

答:
I think @basarat meant to iterate over the target properties not the source ones like this

Actually he is testing for key matching it won't matter.

For performance we probably want to pick the shortest list of the keys.

Body:
I have these two objects:

obj1 = {a: '', b: ''}
obj2 = {a: '1', b: '2', c: '3'}

I want to copy all matching properties from obj2 to obj1. What is the best way of doing that in Typescript?


答:
A simple loop will do it:

```<code>v <- x.orig
for(i in seq_along(v)) v[i] <- sum(head(v, i))
</code>```

which results in this zoo object:

```<code>> v
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07
         1          3          7        111        126        253       1501
2020-01-08 2020-01-09 2020-01-10
      2010       4020       8042
</code>```

rollapply

If you wanted to wrap this within a rollapplyr of width 3, say:

```<code>accum <- function(x) { for(i in seq_along(x)) x[i] <- sum(head(x, i)); tail(x, 1) }
rollapplyr(x.orig, 3, accum)
</code>```

Title: Result-feeding rolling window or rollapply with cumsum

Body:
Suppose I have the following zoo object:

x.orig <- read.zoo(data.frame(date=seq(as.Date('2020-01-01'), as.Date('2020-01-10'), 1), v=c(1,2,3,100,4,5,1000,8,8,10)))
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10
         1          2          3        100          4          5       1000          8          8         10

I would like to compute a rolling sum of width=seq_along(x.orig) as follows:

2020-01-01 1
2020-01-02 1 + 2                                   #2020-01-01 + 2020-01-02
2020-01-03 1 + (1 + 2) + 3                         #2020-01-01 + 2020-01-02 + 2020-01-03
2010-01-04 1 + (1 + 2) + (1 + (1 + 2) + 3) + 100   #2020-01-01 + 2020-01-02 + 2020-01-03 + 2020-01-04
...

I would imagine the way to do this would be to result-feed x in some way so that x is updated after each rollapply loop so that the next rollapply iteration picks up the modified value in its window but am just not sure how to write it...

Body:
A simple loop will do it:

v <- x.orig
for(i in seq_along(v)) v[i] <- sum(head(v, i))

which results in this zoo object:

> v
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07
         1          3          7        111        126        253       1501
2020-01-08 2020-01-09 2020-01-10
      2010       4020       8042

rollapply

If you wanted to wrap this within a rollapplyr of width 3, say:

accum <- function(x) { for(i in seq_along(x)) x[i] <- sum(head(x, i)); tail(x, 1) }
rollapplyr(x.orig, 3, accum)


问:
How do I correctly call a function that takes a "custom enum" as argument using ctypes and ctypes based enums?
I really hope some Python/Ctypes/C expert can help me with this one, it is probably my lack of knowledge on the typing structure to correctly use Ctypes when using Python to interact with C libraries.

Objective: I need to access few library functions loading a DLL using ctypes and interacting with it. The idea works fine most of the time, but there are few functions that take enums as parameters and those enums are very sensitive when it comes to int type. Here is a fake example:

```<code>typedef enum led_property : uint8_t {
  LED_OFF = 0
  LED_POWER
}

int32_t configure_led(const led_property, const int32_t value)
</code>```

This is the kind of enum the functions receive, not only for uint8_t, but also for int32_t, int_64t and so on.

From a python recipe I found online, I managed to "adapt" python enums with ctypes types:

```<code>class EnumerationTypeUInt8(type(c_uint8)):
def __new__(metacls, name, bases, dict):
    if not "_members_" in dict:
        _members_ = {}
        for key, value in dict.items():
            if not key.startswith("_"):
                _members_[key] = value
        dict["_members_"] = _members_
    cls = type(c_uint8).__new__(metacls, name, bases, dict)
    for key, value in cls._members_.items():
        globals()[key] = value
    return cls

def __contains__(self, value):
    return value in self._members_.values()

def __repr__(self):
    return "<Enumeration {}>".format(self.__name__)

def EnumerationUInt8(c_uint8):
__metaclass__ = EnumerationTypeUInt8
_members_ = {}

def __init__(self, value):
    for k, v in self._members_.items():
        if v == value:
            self.name = k
            break
    else:
        raise ValueError("No enumeration member with value {}".format(value))
    c_uint8.__init__(self, value)

@classmethod
def from_param(cls, param):
    if isinstance(param, EnumerationUInt8):
        if param.__class__ != cls:
            raise ValueError("Can not mix enumeration members")
        else:
            return param
    else:
        return cls(param)

def __repr__(self):
    return "<member {}={} of {}".format(self.name, self.value, self.__class__)
</code>```

I'm loading the library and decorating its functions as follows:

```<code>class LedProperty(EnumerationUInt8):
   LED_OFF = c_uint8(0)
   LED_POWER = c_uint8(1)

lib = "library.dll"
self._lib = CDLL(lib)
configure_led = self._lib.configure_led
configure_led.argtypes = [LedProperty, c_int32]
configre_led.restype = c_int32
</code>```

The problem is that I tried all that I could and I can never call that configure_led python function properly, most of the time I get the following error:

```<code>ctypes.ArgumentError class 'ValueError' No enumeration member with value c_ubyte(1)
or
ctypes.ArgumentError class 'ValueError' No enumeration member with value 1
</code>```

That is happening because I can see when debugging that the "EnumerationUInt8" "self.members.items()" is always an empty dict. So probably this custom enums with ctypes are not loading their members properly. I'm always ending on that "else: return cls(param)"

Tried:

```<code>configure_led(LedProperty.LED_POWER, 5)
configure_led(LedProperty.LED_POWER.value, 5)
configure_led(c_uint8(LedProperty.LED_POWER), 5)
</code>```

... and so on! Nothing seems to be correct.

Does anyone knows how to properly declare Enums using cytpes types and later use those enums as arguments for functions?

Obs.: I'm currently using Python 3.8.3
Thanks in advance!

答:
Assuming this implementation, test.cpp:

```<code>#include <stdint.h>

enum led_property : uint8_t {
    LED_OFF = 0,
    LED_POWER
};

extern "C" __declspec(dllexport) int32_t configure_led(enum led_property prop, int32_t value) {
    return prop * value;
}
</code>```

This will allow only LED values for the first parameter:

```<code>from ctypes import *
from enum import Enum,auto

class LED(Enum):

    OFF = 0
    POWER = auto()  # autoincrement from last value

    @classmethod
    def from_param(cls,obj):
        if not isinstance(obj,LED):
            raise TypeError('not an LED enumeration')
        return c_int8(obj.value)

dll = CDLL('./test')
dll.configure_led.argtypes = LED,c_int32
dll.configure_led.restype = c_int32

print(dll.configure_led(LED.OFF,5))   # prints 0
print(dll.configure_led(LED.POWER,5)) # prints 5
print(dll.configure_led(0,5))         # not an LED enumeration
</code>```

Body:
I really hope some Python/Ctypes/C expert can help me with this one, it is probably my lack of knowledge on the typing structure to correctly use Ctypes when using Python to interact with C libraries.

Objective: I need to access few library functions loading a DLL using ctypes and interacting with it. The idea works fine most of the time, but there are few functions that take enums as parameters and those enums are very sensitive when it comes to int type. Here is a fake example:

typedef enum led_property : uint8_t {
  LED_OFF = 0
  LED_POWER
}

int32_t configure_led(const led_property, const int32_t value)

This is the kind of enum the functions receive, not only for uint8_t, but also for int32_t, int_64t and so on.

From a python recipe I found online, I managed to "adapt" python enums with ctypes types:

class EnumerationTypeUInt8(type(c_uint8)):
def __new__(metacls, name, bases, dict):
    if not "_members_" in dict:
        _members_ = {}
        for key, value in dict.items():
            if not key.startswith("_"):
                _members_[key] = value
        dict["_members_"] = _members_
    cls = type(c_uint8).__new__(metacls, name, bases, dict)
    for key, value in cls._members_.items():
        globals()[key] = value
    return cls

def __contains__(self, value):
    return value in self._members_.values()

def __repr__(self):
    return "<Enumeration {}>".format(self.__name__)

def EnumerationUInt8(c_uint8):
__metaclass__ = EnumerationTypeUInt8
_members_ = {}

def __init__(self, value):
    for k, v in self._members_.items():
        if v == value:
            self.name = k
            break
    else:
        raise ValueError("No enumeration member with value {}".format(value))
    c_uint8.__init__(self, value)

@classmethod
def from_param(cls, param):
    if isinstance(param, EnumerationUInt8):
        if param.__class__ != cls:
            raise ValueError("Can not mix enumeration members")
        else:
            return param
    else:
        return cls(param)

def __repr__(self):
    return "<member {}={} of {}".format(self.name, self.value, self.__class__)

I'm loading the library and decorating its functions as follows:

class LedProperty(EnumerationUInt8):
   LED_OFF = c_uint8(0)
   LED_POWER = c_uint8(1)

lib = "library.dll"
self._lib = CDLL(lib)
configure_led = self._lib.configure_led
configure_led.argtypes = [LedProperty, c_int32]
configre_led.restype = c_int32

The problem is that I tried all that I could and I can never call that configure_led python function properly, most of the time I get the following error:

ctypes.ArgumentError class 'ValueError' No enumeration member with value c_ubyte(1)
or
ctypes.ArgumentError class 'ValueError' No enumeration member with value 1

That is happening because I can see when debugging that the "EnumerationUInt8" "self.members.items()" is always an empty dict. So probably this custom enums with ctypes are not loading their members properly. I'm always ending on that "else: return cls(param)"

Tried:

configure_led(LedProperty.LED_POWER, 5)
configure_led(LedProperty.LED_POWER.value, 5)
configure_led(c_uint8(LedProperty.LED_POWER), 5)

... and so on! Nothing seems to be correct.

Does anyone knows how to properly declare Enums using cytpes types and later use those enums as arguments for functions?

Obs.: I'm currently using Python 3.8.3
Thanks in advance!

Body:
Assuming this implementation, test.cpp:

#include <stdint.h>

enum led_property : uint8_t {
    LED_OFF = 0,
    LED_POWER
};

extern "C" __declspec(dllexport) int32_t configure_led(enum led_property prop, int32_t value) {
    return prop * value;
}

This will allow only LED values for the first parameter:

from ctypes import *
from enum import Enum,auto

class LED(Enum):

    OFF = 0
    POWER = auto()  # autoincrement from last value

    @classmethod
    def from_param(cls,obj):
        if not isinstance(obj,LED):
            raise TypeError('not an LED enumeration')
        return c_int8(obj.value)

dll = CDLL('./test')
dll.configure_led.argtypes = LED,c_int32
dll.configure_led.restype = c_int32

print(dll.configure_led(LED.OFF,5))   # prints 0
print(dll.configure_led(LED.POWER,5)) # prints 5
print(dll.configure_led(0,5))         # not an LED enumeration


问:
unable to call a function on an object in a vector of objects
I have a class called AI which has a save function:

```<code>void save(string name) {
       string fileName = "AIs/"+name+".AI";
       ofstream mySave;
       mySave.open(fileName);
       mySave << "id\n" << id << "\n";
       mySave << "pid\n" << pid <<  "\n";
       mySave << "numInpNds\n" << numInpNds << "\n";
       mySave << "numOutNds\n" << numOutNds << "\n";
       mySave << "numLayers\n" << numLayers << "\n";
       mySave << "layerSize\n";
       for (int i = 0; i < numLayers; i++) {
           mySave << layerSize[i] << "\n";
       }
       mySave << "inpLayer\n";
       mySave << nurNet["inpLayer"]<<"\n";
       for (int i = 0; i < numLayers; i++) {
           mySave << "layer"+to_string(i+1)+"Weights\n";
           mySave << nurNet["layer" + to_string(i + 1) + "Weights"] << "\n";
           mySave << "layer" + to_string(i + 1) + "Biases\n";
           mySave << nurNet["layer" + to_string(i + 1) + "Biases"] << "\n";
           mySave << "layer" + to_string(i + 1) << "\n";
           mySave << nurNet["layer" + to_string(i + 1)] << "\n";
       }
       mySave << "outLayerWeights\n";
       mySave << nurNet["outLayerWeights"] << "\n";
       mySave << "outLayerBiases\n";
       mySave << nurNet["outLayerBiases"] << "\n";
       mySave << "outLayer\n";
       mySave << nurNet["outLayer"] << "\n";
       mySave.close();
   }
</code>```

Their is also a vector of AIs called 'AIs'.
I'm trying to iterate through this vector and save all the AIs:

```<code>        for (int i = 0; i < settings["generationSize"]; i++) {;
           AIs[i].save("AIs/" + to_string(i) + ".AI");
        }
</code>```

when i try and run my code it outputs this error:

binary '[': no operator found which takes a left-hand operand of type 'std::vector' (or there is no
  acceptable conversion)

答: I managed to fix the error by moving my vector definition beneath my class definition.</p>

Body:
I have a class called AI which has a save function:

void save(string name) {
       string fileName = "AIs/"+name+".AI";
       ofstream mySave;
       mySave.open(fileName);
       mySave << "id\n" << id << "\n";
       mySave << "pid\n" << pid <<  "\n";
       mySave << "numInpNds\n" << numInpNds << "\n";
       mySave << "numOutNds\n" << numOutNds << "\n";
       mySave << "numLayers\n" << numLayers << "\n";
       mySave << "layerSize\n";
       for (int i = 0; i < numLayers; i++) {
           mySave << layerSize[i] << "\n";
       }
       mySave << "inpLayer\n";
       mySave << nurNet["inpLayer"]<<"\n";
       for (int i = 0; i < numLayers; i++) {
           mySave << "layer"+to_string(i+1)+"Weights\n";
           mySave << nurNet["layer" + to_string(i + 1) + "Weights"] << "\n";
           mySave << "layer" + to_string(i + 1) + "Biases\n";
           mySave << nurNet["layer" + to_string(i + 1) + "Biases"] << "\n";
           mySave << "layer" + to_string(i + 1) << "\n";
           mySave << nurNet["layer" + to_string(i + 1)] << "\n";
       }
       mySave << "outLayerWeights\n";
       mySave << nurNet["outLayerWeights"] << "\n";
       mySave << "outLayerBiases\n";
       mySave << nurNet["outLayerBiases"] << "\n";
       mySave << "outLayer\n";
       mySave << nurNet["outLayer"] << "\n";
       mySave.close();
   }

Their is also a vector of AIs called 'AIs'.
I'm trying to iterate through this vector and save all the AIs:

        for (int i = 0; i < settings["generationSize"]; i++) {;
           AIs[i].save("AIs/" + to_string(i) + ".AI");
        }

when i try and run my code it outputs this error:

binary '[': no operator found which takes a left-hand operand of type 'std::vector' (or there is no
  acceptable conversion)


问:
RedirectToAction is not sending users to correct page
I want to redirect the user if the date is past 5/25/2020
otherwise they get the current view

```<code>    public ActionResult Login()
    {
        DateTime dt = DateTime.Now;
        DateTime expirationDate = new DateTime(2020, 05, 25);

        if (dt > expirationDate)
        {
            return RedirectToAction("ThankYou", "Home");
        }
        else
        {

        }
        return View();
    }
</code>```

Code from HomeController.cs

```<code>    public IActionResult Index()
    {
        var userId = User.Identity.Name;
        string userIdfromCache = SaveToCache("UserID", userId);
        return RedirectToAction("Login", "Authentication");
    }

    public IActionResult ThankYou()
    {
        return View();
    }
</code>```

The IActionResult ThankYou() is not redirecting the user. It should display a static HTML file

答: I guess your problem is somewhere else, I tried your code it works just fine!</p>

Body:
I want to redirect the user if the date is past 5/25/2020
otherwise they get the current view

    public ActionResult Login()
    {
        DateTime dt = DateTime.Now;
        DateTime expirationDate = new DateTime(2020, 05, 25);

        if (dt > expirationDate)
        {
            return RedirectToAction("ThankYou", "Home");
        }
        else
        {

        }
        return View();
    }

Code from HomeController.cs

    public IActionResult Index()
    {
        var userId = User.Identity.Name;
        string userIdfromCache = SaveToCache("UserID", userId);
        return RedirectToAction("Login", "Authentication");
    }

    public IActionResult ThankYou()
    {
        return View();
    }

The IActionResult ThankYou() is not redirecting the user. It should display a static HTML file


问:
Fill image with nearest value within region
I'd like fill in an image outside a circular area with the nearest value within the circle.  The effect is something like skimage's mode='edge' but applying to a circular area of an image instead of a rectangular area.

Simple code which does the right thing - extremely slowly:

```<code>def circle_pad(img, xc, yc, r):
    img_out = img.copy()

    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            d = math.sqrt( (i-yc)**2 + (j-xc)**2 )
            if d > r:
                i1, j1 = int( yc + (i-yc)*(r/d) ), int( xc + (j-xc)*(r/d) )
                img_out[i,j] = img[i1,j1]

    return img_out
</code>```

How to speed this up with numpy? (probably avoid looping over each pixel in python code; typical images are tens of millions pixels)

I thought of using something along the lines of meshgrid as a starting point to calculate the coordinates of the value to fill in at each point, but the way to do it isn't clear.

答:
Solved using mgrid - not pretty but blazing fast.  Just in case it's useful as an example for other folks with similar image processing problesm:

```<code>def circle_pad(img, xc, yc, r):
    mg = np.mgrid[:img.shape[0],0:img.shape[1]]
    yi, xi = mg[0,:,:], mg[1,:,:]

    mask = ((yi-yc)**2 + (xi-xc)**2) < r**2

    d = np.sqrt( (yi-yc)**2 + (xi-xc)**2 )
    d = np.clip(d, r, None)
    ye = yc + (yi-yc)*(r/d)
    xe = xc + (xi-xc)*(r/d)

    ye = np.clip(ye.astype(int), 0, img.shape[0])
    xe = np.clip(xe.astype(int), 0, img.shape[1])

    img_out = img * mask + img[ye,xe] * (~mask)
    return img_out
</code>```

The key parts are:

create a meshgrid-like index arrays xi, yi with np.mgrid - each has the same size as the image

calculate the arrays of coordinates xe, ye of the nearest edge pixel by doing math of xi, yi

replace values by subscripting the image, like this: img[ye,xe]

Body:
I'd like fill in an image outside a circular area with the nearest value within the circle.  The effect is something like skimage's mode='edge' but applying to a circular area of an image instead of a rectangular area.

Simple code which does the right thing - extremely slowly:

def circle_pad(img, xc, yc, r):
    img_out = img.copy()

    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            d = math.sqrt( (i-yc)**2 + (j-xc)**2 )
            if d > r:
                i1, j1 = int( yc + (i-yc)*(r/d) ), int( xc + (j-xc)*(r/d) )
                img_out[i,j] = img[i1,j1]

    return img_out

How to speed this up with numpy? (probably avoid looping over each pixel in python code; typical images are tens of millions pixels)

I thought of using something along the lines of meshgrid as a starting point to calculate the coordinates of the value to fill in at each point, but the way to do it isn't clear.

Body:
Solved using mgrid - not pretty but blazing fast.  Just in case it's useful as an example for other folks with similar image processing problesm:

def circle_pad(img, xc, yc, r):
    mg = np.mgrid[:img.shape[0],0:img.shape[1]]
    yi, xi = mg[0,:,:], mg[1,:,:]

    mask = ((yi-yc)**2 + (xi-xc)**2) < r**2

    d = np.sqrt( (yi-yc)**2 + (xi-xc)**2 )
    d = np.clip(d, r, None)
    ye = yc + (yi-yc)*(r/d)
    xe = xc + (xi-xc)*(r/d)

    ye = np.clip(ye.astype(int), 0, img.shape[0])
    xe = np.clip(xe.astype(int), 0, img.shape[1])

    img_out = img * mask + img[ye,xe] * (~mask)
    return img_out

The key parts are:

create a meshgrid-like index arrays xi, yi with np.mgrid - each has the same size as the image

calculate the arrays of coordinates xe, ye of the nearest edge pixel by doing math of xi, yi

replace values by subscripting the image, like this: img[ye,xe]


问:
Regular Expression to match two words in either order with a specific third word between them
I looked through a lot of other questions and just didn't quite see what I think would work for me.  Basically I want to match three words exactly: "cat", "and", "dog" where "and" is always in the middle but "cat" and "dog" can be on either side.  I have used lookarounds to match "cat" and "dog" in either order, but I can't figure out how to integrate a test for the "and" in the middle.  What I currently have is this:

^(?=.*\bcat\b)(?=.*\bdog\b).*$

but this accepts any word between the two.

答:
If duplicates are not a problem,
\b((cat\sand\sdog)|(dog\sand\scat))\b
is the simplest solution, otherwise
\b((cat\sand\sdog)|(dog\sand\scat))\b</p>


问:
Not able to get response with @Controller, while @RestController works fine
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
```

<p>The above code returns a 404 when I try to access <code>localhost:8080/function/hash</code>.</p>

<p>I also tried</p>

<pre class="lang-java prettyprint-override"><code>@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
</code>```

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

答:
@RestController is combination of @Controller + @ResponseBody. While using @Controller we have to add the @ResponseBody with our methods. You can find more details here

```<code>@Controller
public class MappingController {

    @RequestMapping("/endpoint1") //returns 404
    public String endPoint1() {
        return "Hello endpoint1";
    }

    @RequestMapping("/endpoint2") //works well because of @ResponseBody
    public @ResponseBody String endPoint2() {
        return "Hello endpoint2";
    }
}
</code>```

Add @ResponseBody and these both should work fine

```<code>@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public @ResponseBody String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public @ResponseBody String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
</code>```

Body:
I am trying to map the URL /function/hash in my project to a specific HTML page html/hashcode.html. This is a spring boot project without using thymeleaf.

This is my code:

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

The above code returns a 404 when I try to access localhost:8080/function/hash.

I also tried

@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

which also yields a 404 when I go to localhost:8080/function/hash.

Directly using @RequestMapping("/hash") to map the page to /hash works, in case you wonder if the return value of the function is incorrect.

I also find that using multiple layer url like @RequestMapping("/api/test") is working in @RestController classes, but somehow it doesn't work in this @Controller class above.

Body:
@RestController is combination of @Controller + @ResponseBody. While using @Controller we have to add the @ResponseBody with our methods. You can find more details here

@Controller
public class MappingController {

    @RequestMapping("/endpoint1") //returns 404
    public String endPoint1() {
        return "Hello endpoint1";
    }

    @RequestMapping("/endpoint2") //works well because of @ResponseBody
    public @ResponseBody String endPoint2() {
        return "Hello endpoint2";
    }
}

Add @ResponseBody and these both should work fine

@Controller
public class FunctionController {
    @RequestMapping("/function/hash")
    public @ResponseBody String hashPage(Model m) {
        return "html/hashcode.html";
    }
}

@Controller
@RequestMapping("/function")
public class FunctionController {
    @RequestMapping("/hash")
    public @ResponseBody String hashPage(Model m) {
        return "html/hashcode.html";
    }
}


问:
MySQL Insert query doesn't work with WHERE clause
What's wrong with this query:

```<code>INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
</code>```

It works without the WHERE clause. I've seemed to have forgot my SQL.

答:
You can do that with the below code:</p>

```<code>INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition
</code>```

OwnerDisplayName: Ronald

Body:
What's wrong with this query:

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

It works without the WHERE clause. I've seemed to have forgot my SQL.

Body:
You can do that with the below code:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition


问:
Creating computed class properties from array
I have an array of string literals that I'd like to use as property names for a class.

const propNames = ["a", "b", "c"] as const;
```

<p>I would like to create a class like</p>

<pre class="lang-js prettyprint-override"><code>class Test {
    [name in typeof propNames[number]]: any;
}
</code>```

But this gives the errors (in WebStorm inspection):

```<code>TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.
TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.
TS2693: 'number' only refers to a type, but is being used as a value here.
</code>```

I can instead define a type with those properties like

type Test = {
    [name in typeof propNames[number]]: any;
}
```

<p>But I don't know a way of turning this into a class with those properties.</p>

<p>I have an extra question that I don't think is possible currently, but could I create those property names by concatenating another string literal to them?</p>

<pre class="lang-js prettyprint-override"><code>type Test = {
    [name + 'Prop' in typeof propNames[number]]: any;
}
</code>```

答:
I got around this (including the extra question) by defining intermediate types and using them like namespaces:

const propNames = ["a", "b", "c"] as const;

// using DOM types for demonstration
type Canvases {
    [name in typeof propNames[number]]?: HTMLCanvasElement;
}
type Contexts {
    [name in typeof propNames[number]]?: CanvasRenderingContext2D;
}

// define class
class Test {
    canvases: Canvases = {};
    ctxs: Contexts = {};
}

// now access on instances
const t = new Test();
t.canvases.a; // HTMLCanvasElement
t.ctxs.b;     // CanvasRenderingContext2D
```

Body:
I have an array of string literals that I'd like to use as property names for a class.

const propNames = ["a", "b", "c"] as const;

I would like to create a class like

class Test {
    [name in typeof propNames[number]]: any;
}

But this gives the errors (in WebStorm inspection):

TS1166: A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type.
TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
TS2361: The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.
TS2693: 'number' only refers to a type, but is being used as a value here.

I can instead define a type with those properties like

type Test = {
    [name in typeof propNames[number]]: any;
}

But I don't know a way of turning this into a class with those properties.

I have an extra question that I don't think is possible currently, but could I create those property names by concatenating another string literal to them?

type Test = {
    [name + 'Prop' in typeof propNames[number]]: any;
}


问:
Mangopay: not possible to a card
I'm trying to add Mangopay to my react-native app.

When I try to add by HTTPie a card, I get an error. Here is how I proceed:

I pre-register the card with:

```<code>echo '{
  "UserId": "67844304",
  "Currency": "EUR",
  "CardType": "CB_VISA_MASTERCARD"
}' | http -a filoo:myApiKey POST https://api.sandbox.mangopay.com/v2.01/filoo/cardregistrations
</code>```

It works and I can ask to add a new card with the informations I get:

```<code> echo '{
        "PreregistrationData": "dtxlzFRSvUcdNkJimn-i_L64-_r7M5oECwslrv8Q04NgHVv1mxYX6qXicHf0SGAMS4wCy-yiraxeE65tmxOe8A",
        "AccessKey": "1X0m87dmM2LiwFgxPLBJ",
        "cardNumber": "4706750000000009",
        "cardExpirationDate": "1221",
        "cardCvx": "123"
    }' | http -a filoo:myApiKey POST https://homologation-webpayment.payline.com/webpayment/getToken
</code>```

But I get this very comprehensive error code inside the body of the response (with a 200 HTTP status code): errorCode=09101

答:
I got the same issue and I resolved this problem by passing HTTP params as querystring.

Try to pass this way https://flaviocopes.com/axios-urlencoded/

Title: Mangopay: not possible to a card

Body:
I'm trying to add Mangopay to my react-native app.

When I try to add by HTTPie a card, I get an error. Here is how I proceed:

I pre-register the card with:

echo '{
  "UserId": "67844304",
  "Currency": "EUR",
  "CardType": "CB_VISA_MASTERCARD"
}' | http -a filoo:myApiKey POST https://api.sandbox.mangopay.com/v2.01/filoo/cardregistrations

It works and I can ask to add a new card with the informations I get:

 echo '{
        "PreregistrationData": "dtxlzFRSvUcdNkJimn-i_L64-_r7M5oECwslrv8Q04NgHVv1mxYX6qXicHf0SGAMS4wCy-yiraxeE65tmxOe8A",
        "AccessKey": "1X0m87dmM2LiwFgxPLBJ",
        "cardNumber": "4706750000000009",
        "cardExpirationDate": "1221",
        "cardCvx": "123"
    }' | http -a filoo:myApiKey POST https://homologation-webpayment.payline.com/webpayment/getToken

But I get this very comprehensive error code inside the body of the response (with a 200 HTTP status code): errorCode=09101


Title: Trying to remove the radius of this SVG Icon - any ideas how?

Body:
Does anyone know why this social icon in SVG format has slight curved radius border? I'd like a square icon. How do I edit this to be a square? Using CSS or just edit the actual code in the SVG? Thanks

<svg height="512" viewBox="0 0 512 512" width="512" xmlns="http://www.w3.org/2000/svg"><rect height="512" rx="64" ry="64" width="512" fill="#0083be"/><g fill="#fff"><path d="M61.05316483 178.66808913h85.76013915v257.9625333H61.05316483zM104.5127998 54.28063176c-29.34185723 0-48.512575 19.29035996-48.512575 44.5737057 0 24.75194797 18.5880448 44.57370568 47.37675114 44.57370568h.55470467c29.9027771 0 48.5156826-19.8217577 48.5156826-44.5737057-.55470467-25.28334572-18.6113517-44.57370568-47.9345634-44.57370568zM357.27944394 172.60209055c-45.4904445 0-65.8669069 25.01764686-77.27642064 42.58951v-36.52349588h-85.73838603c1.13737765 24.1972433 0 257.9625333 0 257.9625333h85.73683224V292.56591023c0-7.7114826.55470468-15.4198576 2.82790618-20.93116706 6.1872101-15.39965828 20.30498783-31.35246744 43.9925865-31.35246744 31.01218643 0 43.43632805 23.66429176 43.43632805 58.3278955v138.02046672h85.74149362v-147.9305687c0-79.2373094-42.30516557-116.0979787-98.7203399-116.0979787z"/></g></svg>

Body:
Remove the rx and ry parameters from rect tag.

<svg height="512" viewBox="0 0 512 512" width="512" xmlns="http://www.w3.org/2000/svg"><rect height="512" width="512" fill="#0083be"/><g fill="#fff"><path d="M61.05316483 178.66808913h85.76013915v257.9625333H61.05316483zM104.5127998 54.28063176c-29.34185723 0-48.512575 19.29035996-48.512575 44.5737057 0 24.75194797 18.5880448 44.57370568 47.37675114 44.57370568h.55470467c29.9027771 0 48.5156826-19.8217577 48.5156826-44.5737057-.55470467-25.28334572-18.6113517-44.57370568-47.9345634-44.57370568zM357.27944394 172.60209055c-45.4904445 0-65.8669069 25.01764686-77.27642064 42.58951v-36.52349588h-85.73838603c1.13737765 24.1972433 0 257.9625333 0 257.9625333h85.73683224V292.56591023c0-7.7114826.55470468-15.4198576 2.82790618-20.93116706 6.1872101-15.39965828 20.30498783-31.35246744 43.9925865-31.35246744 31.01218643 0 43.43632805 23.66429176 43.43632805 58.3278955v138.02046672h85.74149362v-147.9305687c0-79.2373094-42.30516557-116.0979787-98.7203399-116.0979787z"/></g></svg>


问:
debugging error: Licenses.licx : unable to resolve type
I am using a ComponentOne FlexGrid, it automatically registered in its license

C1.Win.C1FlexGrid.C1FlexGrid, C1.Win.C1FlexGrid.2,
  Version=2.6.20122.716, Culture=neutral,
  PublicKeyToken=79882d576c6336da

I also use a custom control that inherits the C1FlexGrid, but on run-time it tries to register

DataTree.C1FlexDataTree, fpstudio, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null

in the license file, which ultimately creates an error:

Error 51  Unable to resolve type 'DataTree.C1FlexDataTree, fpstudio,
  Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'  C:_DEVELOPMENT_FP_DRAFT12\COMPONENT1_WORKING_MERGED\fpstudio\Properties\licenses.licx 3   Freepour
  Studio

How can I tell this class not to try to license the control as it already is inherited and is licensed itself. I have already removed [LicenseProvider()] from the DataTree Class

答:
I found the solutions was to open a new blank form in the project, add to that form every object that comes with your library.
Then perform a "Build" and Visual Studio updates your .licx file with the correct info on the added objects, overwriting any old date held in that file.
All "non-resolved" types associated with your file will be removed.</p>


问:
How to customize tool tip window to have arrow in wpf
How to customize tooltip window to have a corner arrow like shown below in WPF(xaml).

I have my code like below

```<code> <Image x:Name="imgInfoTab">
            <Image.ToolTip>
      <ToolTip Background="WhiteSmoke" HasDropShadow="True"
       Cursor="Hand">
          <TextBlock Width="250" Height="250"
      TextWrapping="WrapWithOverflow"
       Cursor="Hand">
        </TextBlock>
        </ToolTip>
       </Image.ToolTip>
        </Image>
</code>```

It looks as below with above code,

答:
Try this:

```<code><Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="CornflowerBlue">
    <Grid.ToolTip>
        <ToolTip Placement="MousePoint" HorizontalOffset="50">
            <ToolTip.Template>
                <ControlTemplate TargetType="ToolTip">
                    <Grid>
                        <Path Fill="White" Data="M 0,10 L 40,10 50,0 60,10 100,10 100,60 0,60" />
                        <TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Grid>
                </ControlTemplate>
            </ToolTip.Template>
        </ToolTip>
    </Grid.ToolTip>
</Grid>
</code>```

If you want it auto-sizing then you'll need to do a bit more work, but that will get you started.

Body:
How to customize tooltip window to have a corner arrow like shown below in WPF(xaml).

I have my code like below

 <Image x:Name="imgInfoTab">
            <Image.ToolTip>
      <ToolTip Background="WhiteSmoke" HasDropShadow="True"
       Cursor="Hand">
          <TextBlock Width="250" Height="250"
      TextWrapping="WrapWithOverflow"
       Cursor="Hand">
        </TextBlock>
        </ToolTip>
       </Image.ToolTip>
        </Image>

It looks as below with above code,

Body:
Try this:

<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="CornflowerBlue">
    <Grid.ToolTip>
        <ToolTip Placement="MousePoint" HorizontalOffset="50">
            <ToolTip.Template>
                <ControlTemplate TargetType="ToolTip">
                    <Grid>
                        <Path Fill="White" Data="M 0,10 L 40,10 50,0 60,10 100,10 100,60 0,60" />
                        <TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Grid>
                </ControlTemplate>
            </ToolTip.Template>
        </ToolTip>
    </Grid.ToolTip>
</Grid>

If you want it auto-sizing then you'll need to do a bit more work, but that will get you started.


问:
How make a view for editing different models' settings?
This is an example of my general problem:

I have different implementations of ITextSearcher to search for something. Each implementation has different settings that can be edited by the user. So I can't make a general editable view for the implementations (because the settings can't be abstracted by an interface).

I have developed a simple library that helps in this situations. It allows to declaratively tag a class and it's properties with view information. A view generator uses this information to render the class. This is an example:

```<code>[Editable]
internal class TermSearcher : ITextSearcher
{
    [Editable(Name="Search Expression", Order = 1)]
    public string Expression
    {...}

    [Editable(Name="Match Similar Characters", Order = 2)]
    public bool MatchSimilarChars
    {...}

    // rest of the implementation ...
}
</code>```

Is there a better solution?

答:
Yes. In WPF or Silverlight you can create a DataTemplate for the various instantiations of ITextSearcher. You can then use a DataTemplateSelector to pick the appropriate DataTemplate given an instance of an ITextSearcher

Since you tagged the post with MVVM I'm assuming you are using WPF

Body:
This is an example of my general problem:

I have different implementations of ITextSearcher to search for something. Each implementation has different settings that can be edited by the user. So I can't make a general editable view for the implementations (because the settings can't be abstracted by an interface).

I have developed a simple library that helps in this situations. It allows to declaratively tag a class and it's properties with view information. A view generator uses this information to render the class. This is an example:

[Editable]
internal class TermSearcher : ITextSearcher
{
    [Editable(Name="Search Expression", Order = 1)]
    public string Expression
    {...}

    [Editable(Name="Match Similar Characters", Order = 2)]
    public bool MatchSimilarChars
    {...}

    // rest of the implementation ...
}

Is there a better solution?


问:
Failed to start PostgreSQL Cluster 10-main when booting
when I try to boot Ubuntu, it never finishes the boot process because it appears the message "Failed to start PostgreSQL Cluster 10-main." I also get the same message with 9.5-main. But lets focus on 10.

When I execute:

```<code>systemctl status postgresql@10-main.service
</code>```

I get the following message:

```<code>postgresql@10-main.service - PostgreSQL Cluster 10-main
  Loaded: loaded (/lib/systemd/system/postgresql@.service; indirect; vendor preset: enabled)
  Active: failed (Result: protocol) since Wed 2020-02-19 17:57:22 CET; 30 min ago
 Process: 1602 ExecStart=/usr/bin/pg_ctlcluster --skip-systemctl-redirect 10-main start (code_exited, status=1/FAILURE)
PC_info systemd[1]: Starting PostgreSQL Cluster 10-main...
PC_info postgresql@10-main[1602]: Error: /usr/lib/postgresql/10/bin/pg_ctl /usr/lib/postgresql/10/bin/pg_ctl start -D /var/lib/postgresql/10/main -l /var/log/postgresql/postgresql-19-main.log -s -o -c config_file="/etc/postgresql/10/main/postgresql.conf" exit with status 1:
PC_info systemd[1]: postgresql@10-main.service: Can't open PID file /var/run/postgresql/10-main.pid (yet?) after start: No such file or directory
PC_info systemd[1]: postgresql@10-main.service: Failed with result 'protocol'.
PC_info systemd[1]: Failed to start PostgreSQL Cluster 10-main.
</code>```

PC_info is information about my computer (user, date..) not relevant

I got this error from one day to an other without touching anything related to Database Servers.
I tried to fix it by my self but nothing worked

Writing the command

```<code>service postgresql@10-main start
</code>```

I get

```<code>Job for postgresql@10-main.service failed because the service did not take the steps required by its unit configuration
See "systemctl status postgresql@10-main.service" and "journalctl -xe"  for details.
</code>```

Running this two command I get the message from the beginning.

Anyone has an idea of what is happening? How I can fix it?

答:
as mentioned by @gruentee in comment above,

```<code>/usr/lib/postgresql/10/bin/pg_ctl restart -D /var/lib/postgresql/10/main -l /var/log/postgresql/postgresql-10-main.log -s -o  '-c config_file="/etc/postgresql/10/main/postgresql.conf"'
</code>```

started the postgresSql DB. Dont forget to

```<code>sudo -i -u postgres
</code>```

before issuing above command

Body:
when I try to boot Ubuntu, it never finishes the boot process because it appears the message "Failed to start PostgreSQL Cluster 10-main." I also get the same message with 9.5-main. But lets focus on 10.

When I execute:

systemctl status postgresql@10-main.service

I get the following message:

postgresql@10-main.service - PostgreSQL Cluster 10-main
  Loaded: loaded (/lib/systemd/system/postgresql@.service; indirect; vendor preset: enabled)
  Active: failed (Result: protocol) since Wed 2020-02-19 17:57:22 CET; 30 min ago
 Process: 1602 ExecStart=/usr/bin/pg_ctlcluster --skip-systemctl-redirect 10-main start (code_exited, status=1/FAILURE)
PC_info systemd[1]: Starting PostgreSQL Cluster 10-main...
PC_info postgresql@10-main[1602]: Error: /usr/lib/postgresql/10/bin/pg_ctl /usr/lib/postgresql/10/bin/pg_ctl start -D /var/lib/postgresql/10/main -l /var/log/postgresql/postgresql-19-main.log -s -o -c config_file="/etc/postgresql/10/main/postgresql.conf" exit with status 1:
PC_info systemd[1]: postgresql@10-main.service: Can't open PID file /var/run/postgresql/10-main.pid (yet?) after start: No such file or directory
PC_info systemd[1]: postgresql@10-main.service: Failed with result 'protocol'.
PC_info systemd[1]: Failed to start PostgreSQL Cluster 10-main.

PC_info is information about my computer (user, date..) not relevant

I got this error from one day to an other without touching anything related to Database Servers.
I tried to fix it by my self but nothing worked

Writing the command

service postgresql@10-main start

I get

Job for postgresql@10-main.service failed because the service did not take the steps required by its unit configuration
See "systemctl status postgresql@10-main.service" and "journalctl -xe"  for details.

Running this two command I get the message from the beginning.

Anyone has an idea of what is happening? How I can fix it?

Body:
as mentioned by @gruentee in comment above,

/usr/lib/postgresql/10/bin/pg_ctl restart -D /var/lib/postgresql/10/main -l /var/log/postgresql/postgresql-10-main.log -s -o  '-c config_file="/etc/postgresql/10/main/postgresql.conf"'

started the postgresSql DB. Dont forget to

sudo -i -u postgres

before issuing above command


答:
add @ResponseBody annotation, The @Controller is a common annotation which is used to mark a class as Spring MVC Controller while the @RestController is a special controller used in RESTFul web services and the equivalent of @Controller + @ResponseBody

if u add @ResponseBody  it will work. use below code

```<code>// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {

    @RequestMapping("/function/hash")
    public @ResponseBody String hashPage(Model m) {
        return "html/hashcode.html";
    }
}
</code>```

Title: Not able to get response with @Controller, while @RestController works fine

Body:
add @ResponseBody annotation, The @Controller is a common annotation which is used to mark a class as Spring MVC Controller while the @RestController is a special controller used in RESTFul web services and the equivalent of @Controller + @ResponseBody

if u add @ResponseBody  it will work. use below code

// package ...;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FunctionController {

    @RequestMapping("/function/hash")
    public @ResponseBody String hashPage(Model m) {
        return "html/hashcode.html";
    }
}


问:
php shorten all urls with is.gd api in a string and linkify them
As the title says I'm trying to shorten all urls with is.gd api in a string and linkify them.

```<code>function link_isgd($text)
{
    $regex = '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)@';
    preg_match_all($regex, $text, $matches);

    foreach($matches[0] as $longurl)
    {
        $tiny = file_get_contents('http://isnot.gd/api.php?longurl='.$longurl.'&format=json');
        $json = json_decode($tiny, true);

        foreach($json as $key => $value)
        {
            if ($key == 'errorcode')
            {
                $link = $longurl;
            }
            else if ($key == 'shorturl')
            {
                $link = $value;
            }
        }
    }
    return preg_replace($regex, '<a href="'.$link.'" target="_blank">'.$link.'</a>', $text);
}

$txt = 'Some text with links https://www.abcdefg.com/123 blah blah blah https://nooodle.com';

echo link_isgd($txt);

</code>```

This is what I have got so far, linkifying works and so does shortening if only 1 url is in the string, however if theres 2 or more they all end up the same.

Note: the is.gd was not allowed in post, SO thought I was posting a short link which is not allowed here,  so I had to change it to isnot.gd.

答:
Your variable $link is not array so it takes only last assigned value of $link. You can replace preg_replace with str_replace and pass arrays with matches and links.

You can also use preg_replace_callback() and you can pass $matches directly to function which will replace with link. https://stackoverflow.com/a/9416265/7082164

```<code>function link_isgd($text)
{
    $regex = '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)@';
    preg_match_all($regex, $text, $matches);

    $links = [];

    foreach ($matches[0] as $longurl) {
        $tiny = file_get_contents('http://isnot.gd/api.php?longurl=' . $longurl . '&format=json');
        $json = json_decode($tiny, true);

        foreach ($json as $key => $value) {
            if ($key == 'errorcode') {
                $links[] = $longurl;
            } else if ($key == 'shorturl') {
                $links[] = $value;
            }
        }
    }
    $links = array_map(function ($el) {
        return '<a href="' . $el . '" target="_blank">' . $el . '</a>';
    }, $links);

    return str_replace($matches[0], $links, $text);
}
</code>```

Body:
As the title says I'm trying to shorten all urls with is.gd api in a string and linkify them.

function link_isgd($text)
{
    $regex = '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)@';
    preg_match_all($regex, $text, $matches);

    foreach($matches[0] as $longurl)
    {
        $tiny = file_get_contents('http://isnot.gd/api.php?longurl='.$longurl.'&format=json');
        $json = json_decode($tiny, true);

        foreach($json as $key => $value)
        {
            if ($key == 'errorcode')
            {
                $link = $longurl;
            }
            else if ($key == 'shorturl')
            {
                $link = $value;
            }
        }
    }
    return preg_replace($regex, ''.$link.'', $text);
}

$txt = 'Some text with links https://www.abcdefg.com/123 blah blah blah https://nooodle.com';

echo link_isgd($txt);

This is what I have got so far, linkifying works and so does shortening if only 1 url is in the string, however if theres 2 or more they all end up the same.

Note: the is.gd was not allowed in post, SO thought I was posting a short link which is not allowed here,  so I had to change it to isnot.gd.

Body:
Your variable $link is not array so it takes only last assigned value of $link. You can replace preg_replace with str_replace and pass arrays with matches and links.

You can also use preg_replace_callback() and you can pass $matches directly to function which will replace with link. https://stackoverflow.com/a/9416265/7082164

function link_isgd($text)
{
    $regex = '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)@';
    preg_match_all($regex, $text, $matches);

    $links = [];

    foreach ($matches[0] as $longurl) {
        $tiny = file_get_contents('http://isnot.gd/api.php?longurl=' . $longurl . '&format=json');
        $json = json_decode($tiny, true);

        foreach ($json as $key => $value) {
            if ($key == 'errorcode') {
                $links[] = $longurl;
            } else if ($key == 'shorturl') {
                $links[] = $value;
            }
        }
    }
    $links = array_map(function ($el) {
        return '<a href="' . $el . '" target="_blank">' . $el . '</a>';
    }, $links);

    return str_replace($matches[0], $links, $text);
}


问:
C++: regex matching code, printing multiple matches?
I'm using the following code which is similar to Stroustrup's C++ 4th Edition Page 127&128.  Per output log below, it prints the first match, however not the match for the trailing -XXXX digits.

Does anyone know why the trailing digits are not matched and/or printed??

Thanks

```<code>#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char *argv[])
{
    // ZIP code pattern: XXddddd-dddd and variants
    regex pat (R"(\w{2}\s*\d{5}(−\d{4})?)");
    int lineno = 0;

    for (string line; getline(cin,line);) {
    ++lineno;
    smatch matches; // matched strings go here
    if (regex_search(line, matches, pat)) // search for pat in line
        for (auto p : matches) {
            cout << p << " ";
        }
    cout << endl;
//      cout << lineno << ": " << matches[0] << '\n';
    }

    return 0;
}
</code>```

Output log:

```<code>$ ./a.out
AB00000-0000
AB00000
</code>```

答:
− is not -. That are two different symbols. You have − in the code and - in the input. Here I fixed the code:

```<code>#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char *argv[])
{
    // ZIP code pattern: XXddddd-dddd and variants
    regex pat (R"(\w{2}\s*\d{5}(-\d{4})?)");
    int lineno = 0;

    for (string line; getline(cin,line);) {
    ++lineno;
    smatch matches; // matched strings go here
    if (regex_search(line, matches, pat)) // search for pat in line
        for (auto p : matches) {
            cout << p << " ";
        }
    cout << endl;
//      cout << lineno << ": " << matches[0] << '\n';
    }

    return 0;
}
</code>```

Body:
I'm using the following code which is similar to Stroustrup's C++ 4th Edition Page 127&128.  Per output log below, it prints the first match, however not the match for the trailing -XXXX digits.

Does anyone know why the trailing digits are not matched and/or printed??

Thanks

#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char *argv[])
{
    // ZIP code pattern: XXddddd-dddd and variants
    regex pat (R"(\w{2}\s*\d{5}(−\d{4})?)");
    int lineno = 0;

    for (string line; getline(cin,line);) {
    ++lineno;
    smatch matches; // matched strings go here
    if (regex_search(line, matches, pat)) // search for pat in line
        for (auto p : matches) {
            cout << p << " ";
        }
    cout << endl;
//      cout << lineno << ": " << matches[0] << '\n';
    }

    return 0;
}

Output log:

$ ./a.out
AB00000-0000
AB00000

Body:
− is not -. That are two different symbols. You have − in the code and - in the input. Here I fixed the code:

#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char *argv[])
{
    // ZIP code pattern: XXddddd-dddd and variants
    regex pat (R"(\w{2}\s*\d{5}(-\d{4})?)");
    int lineno = 0;

    for (string line; getline(cin,line);) {
    ++lineno;
    smatch matches; // matched strings go here
    if (regex_search(line, matches, pat)) // search for pat in line
        for (auto p : matches) {
            cout << p << " ";
        }
    cout << endl;
//      cout << lineno << ": " << matches[0] << '\n';
    }

    return 0;
}


问:
Easy way to convert Iterable to Collection
In my application I use 3rd party library (Spring Data for MongoDB to be exact).

Methods of this library return Iterable<T>, while the rest of my code expects Collection<T>.

Is there any utility method somewhere that will let me quickly convert one to the other? I would like to avoid creating a bunch of foreach loops in my code for such a simple thing.

答:
I came across a similar situation while trying to fetch a List of Projects, rather than the default Iterable<T> findAll() declared in CrudRepository interface. So, in my ProjectRepository interface (which extends from CrudRepository), I simply declared the findAll() method to return a List<Project> instead of Iterable<Project>.

```<code>package com.example.projectmanagement.dao;

import com.example.projectmanagement.entities.Project;
import org.springframework.data.repository.CrudRepository;
import java.util.List;

public interface ProjectRepository extends CrudRepository<Project, Long> {

    @Override
    List<Project> findAll();
}
</code>```

This is the simplest solution, I think, without requiring conversion logic or usage of external libraries.

Body:
I came across a similar situation while trying to fetch a List of Projects, rather than the default Iterable<T> findAll() declared in CrudRepository interface. So, in my ProjectRepository interface (which extends from CrudRepository), I simply declared the findAll() method to return a List<Project> instead of Iterable<Project>.

package com.example.projectmanagement.dao;

import com.example.projectmanagement.entities.Project;
import org.springframework.data.repository.CrudRepository;
import java.util.List;

public interface ProjectRepository extends CrudRepository<Project, Long> {

    @Override
    List<Project> findAll();
}

This is the simplest solution, I think, without requiring conversion logic or usage of external libraries.


问:
gstreamer with openCV in rpi4
I am trying to build software using GStreamer and OpenCV in C++ in rpi4. But the problem is I don't have the root access so I am not able to install any packages for GStreamer. What I am trying is to copy all the libs for GStreamer and then try to build my software. I am using the following code:

```<code>cv::VideoCapture cap;
cap.open("videotestsrc ! appsink",CAP_GSTREAMER);
</code>```

But it is not working. I have tried the same with my laptop after installing GStreamer and it is working. So my guess is the problem is that the GStreamer is not setup correctly. Is there any way to use GStreamer without installing the packages by just copying the libs and bin files?

Thanks in advance.

Didn't get any solution till now.

答: If you don't have root access, then there's not much you can do here. Sorry. </p>

Title: gstreamer with openCV in rpi4

Body:
I am trying to build software using GStreamer and OpenCV in C++ in rpi4. But the problem is I don't have the root access so I am not able to install any packages for GStreamer. What I am trying is to copy all the libs for GStreamer and then try to build my software. I am using the following code:

cv::VideoCapture cap;
cap.open("videotestsrc ! appsink",CAP_GSTREAMER);

But it is not working. I have tried the same with my laptop after installing GStreamer and it is working. So my guess is the problem is that the GStreamer is not setup correctly. Is there any way to use GStreamer without installing the packages by just copying the libs and bin files?

Thanks in advance.

Didn't get any solution till now.


问:
For XSS protection, do I need to escape before populating for edit
I have an infected text that I'm testing with.

In display mode, I get the data from the database and display it on the page, and I get the XSS as expected.

In edit mode, I use the same form I used for initial entry and I populate the value from the database into the input fields (textarea in this case), but I'm not getting the XSS. Is this normal? Are form fields data not susceptible to XSS because the text is being displayed inside the form field? so no need for the XSS protection I use in normal display?

By the way, the specific XSS I'm testing with is this. I got it from the cheat sheet for XSS on hackers, the fisrt one.

```<code>';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
</code>```

答:
No, the form fields are suspectible for XSS, so you need to escape them  as well

Template sample:

```<code><input type="text" name="foo" value="{$value}" />
</code>```

Value sample:

```<code>" /><script>alert(123);</script><input attr="
</code>```

Result:

```<code><input type="text" name="foo" value="" /><script>alert(42);</script><input attr="" />
</code>```

Body:
I have an infected text that I'm testing with.

In display mode, I get the data from the database and display it on the page, and I get the XSS as expected.

In edit mode, I use the same form I used for initial entry and I populate the value from the database into the input fields (textarea in this case), but I'm not getting the XSS. Is this normal? Are form fields data not susceptible to XSS because the text is being displayed inside the form field? so no need for the XSS protection I use in normal display?

By the way, the specific XSS I'm testing with is this. I got it from the cheat sheet for XSS on hackers, the fisrt one.

';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'>

Body:
No, the form fields are suspectible for XSS, so you need to escape them  as well

Template sample:

<input type="text" name="foo" value="{$value}" />

Value sample:

" /><script>alert(123);</script><input attr="

Result:

<input type="text" name="foo" value="" /><script>alert(42);</script><input attr="" />


问:
Some Truffle Commands do nothing
So Ive been dealing with a very odd problem that seems to have happened out of nowhere. My truffle compile, test, and migrate commands do literally nothing. However my other commands like develop, networks, console etc work properly. When I type truffle migrate in the console this happens:
Nothing happens and the the terminal line just goes to a new line

And this is what happens when I run truffle develop:
Works as expected

I did the same withh an out of the box drizzle app. Its config file looks like this:

```<code>const path = require("path");

module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
contracts_build_directory: path.join(__dirname, "app/src/contracts"),
solc: {
  optimizer: {
    enabled: true,
    runs: 200
  }
},
networks: {
  development: {
    host: "LOCALHOST",
    port: 8545,
    network_id: "5777", // Match any network id
  }
}};
</code>```

And the migration file looks like this:

```<code>const SimpleStorage = artifacts.require("SimpleStorage");
const TutorialToken = artifacts.require("TutorialToken");
const ComplexStorage = artifacts.require("ComplexStorage");

module.exports = function(deployer) {
  deployer.deploy(SimpleStorage);
  deployer.deploy(TutorialToken);
  deployer.deploy(ComplexStorage);
};
</code>```

Everything looks fairly normal and I cant seem to figure out what the problem is. Apps that used to work before, now cant seem to run truffle compile, migrate or test commands.

So I initially thought it might be a problem with my npm packet or maybe requires a new update. So I uninstalled and reinstalled truffle@latest. I started noticing I was getting a specific error sometimes when i download certain packages:

```<code>/Users/aditya/.nvm/versions/node/v11.10.0/bin/truffle ->
/Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/build/cli.bundled.js

> keccak@1.4.0 install /Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak
> npm run rebuild || echo "Keccak bindings compilation fail. Pure JS implementation will be used."

> keccak@1.4.0 rebuild /Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak
> node-gyp rebuild

gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak/build'
gyp ERR! System Darwin 18.2.0
gyp ERR! command "/Users/aditya/.nvm/versions/node/v11.10.0/bin/node" "/Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak
gyp ERR! node -v v11.10.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! keccak@1.4.0 rebuild: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the keccak@1.4.0 rebuild script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Keccak bindings compilation fail. Pure JS implementation will be used.
+ truffle@5.0.5
added 91 packages from 305 contributors in 7.797s
</code>```

This node-gyp error kept showing up numerous times when installing specific packages. So I did a complete overhaul of my npm, by uninstalling and reinstalling npm. This changed nothing and this error still keeps on showing up. Im not sure if this error has anything to do with the Truffle command problem.

答:
I know this is late answer, but i am posting for newcommers, here the issue might be with the ownership of a directory, so
To minimize the chance of permissions errors, you can configure npm to use a different directory

On the command line, in your home directory, create a directory for global installations:

```<code> mkdir ~/.npm-global
</code>```

Configure npm to use the new directory path:

```<code> npm config set prefix '~/.npm-global'
</code>```

add this line:

```<code> export PATH=~/.npm-global/bin:$PATH
</code>```

On the command line, update your system variables:

```<code> source ~/.profile
</code>```

To test your new configuration, install a package globally without using sudo:

```<code> npm install -g node-gyp
</code>```

Title: Some Truffle Commands do nothing

Body:
So Ive been dealing with a very odd problem that seems to have happened out of nowhere. My truffle compile, test, and migrate commands do literally nothing. However my other commands like develop, networks, console etc work properly. When I type truffle migrate in the console this happens:
Nothing happens and the the terminal line just goes to a new line

And this is what happens when I run truffle develop:
Works as expected

I did the same withh an out of the box drizzle app. Its config file looks like this:

const path = require("path");

module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
contracts_build_directory: path.join(__dirname, "app/src/contracts"),
solc: {
  optimizer: {
    enabled: true,
    runs: 200
  }
},
networks: {
  development: {
    host: "LOCALHOST",
    port: 8545,
    network_id: "5777", // Match any network id
  }
}};

And the migration file looks like this:

const SimpleStorage = artifacts.require("SimpleStorage");
const TutorialToken = artifacts.require("TutorialToken");
const ComplexStorage = artifacts.require("ComplexStorage");

module.exports = function(deployer) {
  deployer.deploy(SimpleStorage);
  deployer.deploy(TutorialToken);
  deployer.deploy(ComplexStorage);
};

Everything looks fairly normal and I cant seem to figure out what the problem is. Apps that used to work before, now cant seem to run truffle compile, migrate or test commands.

So I initially thought it might be a problem with my npm packet or maybe requires a new update. So I uninstalled and reinstalled truffle@latest. I started noticing I was getting a specific error sometimes when i download certain packages:

/Users/aditya/.nvm/versions/node/v11.10.0/bin/truffle ->
/Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/build/cli.bundled.js

> keccak@1.4.0 install /Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak
> npm run rebuild || echo "Keccak bindings compilation fail. Pure JS implementation will be used."

> keccak@1.4.0 rebuild /Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak
> node-gyp rebuild

gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak/build'
gyp ERR! System Darwin 18.2.0
gyp ERR! command "/Users/aditya/.nvm/versions/node/v11.10.0/bin/node" "/Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/aditya/.nvm/versions/node/v11.10.0/lib/node_modules/truffle/node_modules/keccak
gyp ERR! node -v v11.10.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! keccak@1.4.0 rebuild: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the keccak@1.4.0 rebuild script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Keccak bindings compilation fail. Pure JS implementation will be used.
+ truffle@5.0.5
added 91 packages from 305 contributors in 7.797s

This node-gyp error kept showing up numerous times when installing specific packages. So I did a complete overhaul of my npm, by uninstalling and reinstalling npm. This changed nothing and this error still keeps on showing up. Im not sure if this error has anything to do with the Truffle command problem.

Body:
I know this is late answer, but i am posting for newcommers, here the issue might be with the ownership of a directory, so
To minimize the chance of permissions errors, you can configure npm to use a different directory

On the command line, in your home directory, create a directory for global installations:

 mkdir ~/.npm-global

Configure npm to use the new directory path:

 npm config set prefix '~/.npm-global'

add this line:

 export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

 source ~/.profile

To test your new configuration, install a package globally without using sudo:

 npm install -g node-gyp


问:
Using datetime index in where clause MySQL
I have a table with 200 million rows where index is created in "created_at" column which is datetime datatype.

show create table [tablename] outputs:

```<code> create table `table`
 (`created_at` datetime NOT NULL)
 PRIMARY KEY (`id`)
 KEY `created_at_index` (`created_at`)
 ENGINE=InnoDB AUTO_INCREMENT=208512112 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
</code>```

created_at ranges from 2020-04-01 ~ 2020-05-28.

I want to get only rows that are beyond 2020-05-15 23:00:00.

when I run :

```<code>EXPLAIN SELECT created_at
          FROM table
         where created_at >= '2020-05-15 23:00:00';
</code>```

it says it outputs:

```<code>rows       Extra
200mil   Using Where
</code>```

My understanding is that in RDMS if no index rows are not ordered but when you create an index on a column it is in sorted order therefore right after finding '2020-05-15 23:00:00' it will simply return all rows after that.

Also since its cardinalty is 7mil I'd thought using an index would be better than full table scan.

Is it because I've inputted date as a string? but when I try

```<code> where created_at >= date('2020-05-15 23:00:00');
</code>```

still the same.

and

```<code> where created_at >= datetime('2020-05-15 23:00:00');
</code>```

outputs syntax error.

Did mysql just decide it would be more efficient to do a full table scan?

EDIT:

using equals

```<code>EXPLAIN SELECT created_at
          FROM table
         where created_at = '2020-05-15';
</code>```

outputs:

```<code>key_len    ref     rows     Extra
  5        const    51
</code>```

In where clause if I change string to date('2020-05-15') it outputs:

```<code>key_len    ref     rows     Extra
  5        const    51      Using index condition
</code>```

does this mean that first equal query one didn't use an index?

答:
If the values are evenly distributed, about 25% of the rows are >= '2020-05-15 23:00:00'  Yes, Mysql will prefer a full table scan to using the index when you have such a large percentage of the table needed.

See Why does MySQL not always use index for select query?

In a DATE context, date('2020-05-15 23:00:00') is the same as '2020-05-15'.

In a DATETIME context, datetime('2020-05-15 23:00:00') is the same as '2020-05-15 23:00:00'.

Using index means that the INDEX is "covering", which means that the entire query can be performed entirely in the index's BTree -- without reaching over to the data's BTree.

Using index condition means something quite different -- it has to do with a minor optimization relating to the two layers ("handler" and "engine") in MySQL's design.  (More details in "ICP" aka "Index Condition Pushdown".)

Body:
I have a table with 200 million rows where index is created in "created_at" column which is datetime datatype.

show create table [tablename] outputs:

 create table `table`
 (`created_at` datetime NOT NULL)
 PRIMARY KEY (`id`)
 KEY `created_at_index` (`created_at`)
 ENGINE=InnoDB AUTO_INCREMENT=208512112 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'

created_at ranges from 2020-04-01 ~ 2020-05-28.

I want to get only rows that are beyond 2020-05-15 23:00:00.

when I run :

EXPLAIN SELECT created_at
          FROM table
         where created_at >= '2020-05-15 23:00:00';

it says it outputs:

rows       Extra
200mil   Using Where

My understanding is that in RDMS if no index rows are not ordered but when you create an index on a column it is in sorted order therefore right after finding '2020-05-15 23:00:00' it will simply return all rows after that.

Also since its cardinalty is 7mil I'd thought using an index would be better than full table scan.

Is it because I've inputted date as a string? but when I try

 where created_at >= date('2020-05-15 23:00:00');

still the same.

and

 where created_at >= datetime('2020-05-15 23:00:00');

outputs syntax error.

Did mysql just decide it would be more efficient to do a full table scan?

EDIT:

using equals

EXPLAIN SELECT created_at
          FROM table
         where created_at = '2020-05-15';

outputs:

key_len    ref     rows     Extra
  5        const    51

In where clause if I change string to date('2020-05-15') it outputs:

key_len    ref     rows     Extra
  5        const    51      Using index condition

does this mean that first equal query one didn't use an index?


问:
How can I add a search field on my processing page?
I have created a custom processing page called "Kardex Process", by default it doesn't add a search field, and I want to include it.

See the screenshot below:

I want to include it as well as on the Release AP Documents screen, see the screen below:

Can you help me with this?

答:
You need to define FastFilterFields property in the grid control and list fields that you want to be included in the search.</p>

```<code><px:PXGrid ID="grid" runat="server" DataSourceID="ds" ... SkinID="PrimaryInquire"       FastFilterFields="RefNbr,VendorID,VendorID_Vendor_acctName">
</code>```

Body:
You need to define FastFilterFields property in the grid control and list fields that you want to be included in the search.

<px:PXGrid ID="grid" runat="server" DataSourceID="ds" ... SkinID="PrimaryInquire"       FastFilterFields="RefNbr,VendorID,VendorID_Vendor_acctName">


问:
Is there a way to read a file in C without a bunch of checks for sscanf and fgets?
In a program I'm writing, I'm currently doing the part of parsing an input file. I have to do input validation (to some degree), checking if sscanf parses the right number of variables and fgets isn't null. But as a result, the main outline looks like this:

```<code>int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
    if (camFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz, dx, dy, dz, dt;
        if (sscanf(line, "%f %f %f %f %f %f %f\n", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        // do stuff with input
    }
    if (lightFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz;
        unsigned char r, g, b;
        if (sscanf(line, "%f %f %f %hhu %hhu %hhu\n", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        if (fgets(line, LINE_LENGTH, fp) == NULL)) return 1;
        int n;
        if (sscanf(line, "%d\n", &n) != 1) return 1;
        // etc...
    }
}
</code>```

and as a result, half the lines are checking input. Is there a good way to avoid this?

答:
Since you are following a pattern:

```<code>    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
</code>```

You could make your own function to combine the calls and checks of the fgets and sscanf functions into one, that way the code would be less verbose.

Something like:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

int LINE_LENGTH = 100;
int checked_fgets_sscanf(FILE *fp, int count, const char *fmt, ...)
{
    //char* line = calloc(LINE_LENGTH, sizeof(char));
    char line[LINE_LENGTH];
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    va_list ap;
    va_start(ap, fmt);
    int rc = vsscanf(line, fmt, ap);
    va_end(ap);
    //free(line);
    return rc != count;
}

int main()
{

    int a, b;
    if(checked_fgets_sscanf(stdin, 2, "%d %d", &a, &b)) return 1;

    return 0;
}
</code>```

Where the parameter count of the function receives the number of variadic arguments used in the sscanf function.

Body:
In a program I'm writing, I'm currently doing the part of parsing an input file. I have to do input validation (to some degree), checking if sscanf parses the right number of variables and fgets isn't null. But as a result, the main outline looks like this:

int LINE_LENGTH = 100;
int parseInput(FILE* fp, FILE* output) {
    char* line = calloc(LINE_LENGTH, sizeof(char));
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;
    if (camFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz, dx, dy, dz, dt;
        if (sscanf(line, "%f %f %f %f %f %f %f\n", &cx, &cy, &cz, &dx, &dy, &dz, &dt) != 7) return 1;
        // do stuff with input
    }
    if (lightFlag) {
        if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
        double cx, cy, cz;
        unsigned char r, g, b;
        if (sscanf(line, "%f %f %f %hhu %hhu %hhu\n", &cx, &cy, &cz, &r, &g, &b) != 6) return 1;
        // do stuff with this data
    }
    for (int i = 0; i < frames; i++) {
        if (fgets(line, LINE_LENGTH, fp) == NULL)) return 1;
        int n;
        if (sscanf(line, "%d\n", &n) != 1) return 1;
        // etc...
    }
}

and as a result, half the lines are checking input. Is there a good way to avoid this?

Body:
Since you are following a pattern:

    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    int camFlag, lightFlag;
    if (sscanf(line, "%d %d %d\n", &frames, &camFlag, &lightFlag) != 3) return 1;

You could make your own function to combine the calls and checks of the fgets and sscanf functions into one, that way the code would be less verbose.

Something like:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

int LINE_LENGTH = 100;
int checked_fgets_sscanf(FILE *fp, int count, const char *fmt, ...)
{
    //char* line = calloc(LINE_LENGTH, sizeof(char));
    char line[LINE_LENGTH];
    if (fgets(line, LINE_LENGTH, fp) == NULL) return 1;
    va_list ap;
    va_start(ap, fmt);
    int rc = vsscanf(line, fmt, ap);
    va_end(ap);
    //free(line);
    return rc != count;
}

int main()
{

    int a, b;
    if(checked_fgets_sscanf(stdin, 2, "%d %d", &a, &b)) return 1;

    return 0;
}

Where the parameter count of the function receives the number of variadic arguments used in the sscanf function.


问:
Convert signed cobol number in ruby
I have an ascii file that is a dump of data from a cobol based system.

There is a field that the docs say is PIC S9(3)V9(7)..

Here are two examples of the fields in hex (and ascii) and the resulting number they represent (taken from another source).

```<code>Hex                                Reported value

30 32 38 36 38 35 38 34 35 46      28.687321
ascii : 028685845F

30 39 38 34 35 36 31 33 38 43      -98.480381
ascii : 098456138C
</code>```

I'm using ruby, and even after adding the Implied Decimal, I seem to be getting the numbers incorrect. I'm trying to parse IBM Cobol Docs but I would appreciate help.

Given an Implied Decimal Cobol field of "PIC S9(3)V9(7).", how can I convert it into a signed float using ruby?

答:
```<code>028685845F
098456138C
</code>```

It's likely that the 2 strings in ASCII was converted from EBCDIC.

These are zone numbers with a sign nibble turn into a byte at the end.  Like others have said, the F and C are the sign nibbles.

Check this webpage http://www.simotime.com/datazd01.htm

F is for "unsigned"

C is for "signed positive"

The PIC S9(3)V9(7) is telling you that it's ddd.ddddddd (3 digits before decimal point, 7 digits after, the whole thing is signed.)

It's possible that the 2 "string" are of different PIC, you will need to check the COBOL source that produced the numbers.

It would be best to get the original, hexadecimal dump of the COBOL data (likely in EBCDIC), and post those.  (But, I also realize this is a 7.5year old post, the OP probably moved on already.)  What I wrote above is for whoever in the future that bump into this thread.

Title: Convert signed cobol number in ruby

Body:
I have an ascii file that is a dump of data from a cobol based system.

There is a field that the docs say is PIC S9(3)V9(7)..

Here are two examples of the fields in hex (and ascii) and the resulting number they represent (taken from another source).

Hex                                Reported value

30 32 38 36 38 35 38 34 35 46      28.687321
ascii : 028685845F

30 39 38 34 35 36 31 33 38 43      -98.480381
ascii : 098456138C

I'm using ruby, and even after adding the Implied Decimal, I seem to be getting the numbers incorrect. I'm trying to parse IBM Cobol Docs but I would appreciate help.

Given an Implied Decimal Cobol field of "PIC S9(3)V9(7).", how can I convert it into a signed float using ruby?

Body:
028685845F
098456138C

It's likely that the 2 strings in ASCII was converted from EBCDIC.

These are zone numbers with a sign nibble turn into a byte at the end.  Like others have said, the F and C are the sign nibbles.

Check this webpage http://www.simotime.com/datazd01.htm

F is for "unsigned"

C is for "signed positive"

The PIC S9(3)V9(7) is telling you that it's ddd.ddddddd (3 digits before decimal point, 7 digits after, the whole thing is signed.)

It's possible that the 2 "string" are of different PIC, you will need to check the COBOL source that produced the numbers.

It would be best to get the original, hexadecimal dump of the COBOL data (likely in EBCDIC), and post those.  (But, I also realize this is a 7.5year old post, the OP probably moved on already.)  What I wrote above is for whoever in the future that bump into this thread.