问:
How to casting this Generic class for two layouts in Kotlin?
```<code>package com.hypermarket.ui.main.adapter

import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog

class ProductsGridAdapter(
    fragment: Fragment,
    val context: MainActivity,
    private val myPref: PreferencesManager,
    screenName: ScreenType,
    productInterface: ProductInterface,
    rv: RecyclerView,
    isFromDetails: Boolean,
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var items = arrayListOf<ProductModel>()
    var parentFragment: Fragment = fragment
    var bottomSheetDialog: BottomSheetDialog? = null
    var mAdapter: ProductsGridAdapter? = null
    var screenType: ScreenType
    var productInterface: ProductInterface = productInterface
    private var loading = false
    private var onLoadMoreListener: OnLoadMoreListener? = null
    private var recyclerView: RecyclerView
    private var isFromDetails: Boolean? = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        if (isFromDetails == false) {
            val itemBinding: RowItemProductGridBinding =
                RowItemProductGridBinding.inflate(layoutInflater, parent, false)
            //itemBinding.productInterface = productInterface
            return ViewHolder(itemBinding)
        } else {
            val itemBinding: RowItemSimilarProductBinding =
                RowItemSimilarProductBinding.inflate(layoutInflater, parent, false)
            //itemBinding.productInterface = productInterface
            return ViewHolder(itemBinding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (isFromDetails == true) {
            (holder as ViewHolder<RowItemSimilarProductBinding>).bind(position)
        } else {
            (holder as ViewHolder<RowItemProductGridBinding>).bind(position)

        }
    }

    fun <T> getCurrentView(binding: T): View {
        if (isFromDetails == true) {
            return (binding as RowItemSimilarProductBinding).root
        } else {
            return (binding as RowItemProductGridBinding).root
        }
    }

    fun <T> getItemSimilarProductBinding(binding: T): RowItemSimilarProductBinding {
        return binding as RowItemSimilarProductBinding
    }

    fun <T> getItemProductGridBinding(binding: T): RowItemProductGridBinding {
        return binding as RowItemProductGridBinding
    }

    inner class ViewHolder<T>(bindings: T) : RecyclerView.ViewHolder(getCurrentView(bindings)) {

        private val binding: T = bindings

        fun bind(position: Int) {

            val model: ProductModel = items[position]
            if (isFromDetails == true) {
                getItemSimilarProductBinding(binding).item = model
            } else {
                getItemProductGridBinding(binding).item = model
            }

            binding.tvMRP.paintFlags = binding.tvMRP.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
            binding.executePendingBindings()
            binding.ivProduct.setBackgroundResource(0)

            if (model.weight_based == Constants.WEIGHT_BASED) {
                binding.parentView.disabled =
                    AppValidator.toFloat(model.available_qty_weight_based) < AppValidator.toFloat(
                        model.gram_variant_en)
            } else {
                binding.parentView.disabled = AppValidator.toInt(model.available_qty) == 0
            }
            binding.ivType.setGone()

    }

}
</code>```

Here I want to use two different layout (Which you can see on onCreateViewHolder() method). two different layout has all the property named with one another. only design is different. now I want to use the layout based on isFromDetails (Which is boolean value). based on that, I want access the both layout bindings with single variable. is it possible?

```<code>private val binding: T = bindings

fun bind(position: Int) {

        val model: ProductModel = items[position]
        if (isFromDetails == true) {
            getItemSimilarProductBinding(binding).item = model
        } else {
            getItemProductGridBinding(binding).item = model
        }

        binding.tvMRP.paintFlags = binding.tvMRP.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG

        binding.ivType.setGone()

}
</code>```

here both layout has tvMRP and ivType.  Is it possible without adding boiler plate code?

Body:
package com.hypermarket.ui.main.adapter

import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog

class ProductsGridAdapter(
    fragment: Fragment,
    val context: MainActivity,
    private val myPref: PreferencesManager,
    screenName: ScreenType,
    productInterface: ProductInterface,
    rv: RecyclerView,
    isFromDetails: Boolean,
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var items = arrayListOf<ProductModel>()
    var parentFragment: Fragment = fragment
    var bottomSheetDialog: BottomSheetDialog? = null
    var mAdapter: ProductsGridAdapter? = null
    var screenType: ScreenType
    var productInterface: ProductInterface = productInterface
    private var loading = false
    private var onLoadMoreListener: OnLoadMoreListener? = null
    private var recyclerView: RecyclerView
    private var isFromDetails: Boolean? = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        if (isFromDetails == false) {
            val itemBinding: RowItemProductGridBinding =
                RowItemProductGridBinding.inflate(layoutInflater, parent, false)
            //itemBinding.productInterface = productInterface
            return ViewHolder(itemBinding)
        } else {
            val itemBinding: RowItemSimilarProductBinding =
                RowItemSimilarProductBinding.inflate(layoutInflater, parent, false)
            //itemBinding.productInterface = productInterface
            return ViewHolder(itemBinding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (isFromDetails == true) {
            (holder as ViewHolder<RowItemSimilarProductBinding>).bind(position)
        } else {
            (holder as ViewHolder<RowItemProductGridBinding>).bind(position)

        }
    }

    fun <T> getCurrentView(binding: T): View {
        if (isFromDetails == true) {
            return (binding as RowItemSimilarProductBinding).root
        } else {
            return (binding as RowItemProductGridBinding).root
        }
    }

    fun <T> getItemSimilarProductBinding(binding: T): RowItemSimilarProductBinding {
        return binding as RowItemSimilarProductBinding
    }

    fun <T> getItemProductGridBinding(binding: T): RowItemProductGridBinding {
        return binding as RowItemProductGridBinding
    }

    inner class ViewHolder<T>(bindings: T) : RecyclerView.ViewHolder(getCurrentView(bindings)) {

        private val binding: T = bindings

        fun bind(position: Int) {

            val model: ProductModel = items[position]
            if (isFromDetails == true) {
                getItemSimilarProductBinding(binding).item = model
            } else {
                getItemProductGridBinding(binding).item = model
            }

            binding.tvMRP.paintFlags = binding.tvMRP.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
            binding.executePendingBindings()
            binding.ivProduct.setBackgroundResource(0)

            if (model.weight_based == Constants.WEIGHT_BASED) {
                binding.parentView.disabled =
                    AppValidator.toFloat(model.available_qty_weight_based) < AppValidator.toFloat(
                        model.gram_variant_en)
            } else {
                binding.parentView.disabled = AppValidator.toInt(model.available_qty) == 0
            }
            binding.ivType.setGone()

    }

}

Here I want to use two different layout (Which you can see on onCreateViewHolder() method). two different layout has all the property named with one another. only design is different. now I want to use the layout based on isFromDetails (Which is boolean value). based on that, I want access the both layout bindings with single variable. is it possible?

private val binding: T = bindings

fun bind(position: Int) {

        val model: ProductModel = items[position]
        if (isFromDetails == true) {
            getItemSimilarProductBinding(binding).item = model
        } else {
            getItemProductGridBinding(binding).item = model
        }

        binding.tvMRP.paintFlags = binding.tvMRP.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG

        binding.ivType.setGone()

}

here both layout has tvMRP and ivType.  Is it possible without adding boiler plate code?


来源: stackexchange

问:
Snowflake NUMBER(x,7) number stored can have less decimal places: how to choose the most precise one?
I have a table with lat/long as NUMBER(9,7) and NUMBER(10,7) respectively.
Sometimes we store less precise coordinates, sometimes more, meaning more decimal places.
When we have similar coordinates like this:

```<code>ST_GEOHASH | LATITUDE | LONGITUDE
d3f71dbq87gk 10.3873367 -75.519661
d3f71dbq87gk 10.3873367 -75.5196609
dpsb7fr5gqs4 42.2444839 -83.1457596
dpsb7fr5gqs4 42.2444840 -83.1457596
</code>```

we would like to choose just the one that has more decimal cases on LAT/LONG or max(LAT) if they both have the same amount of decimal places.
How can I achieve that if length(number) always returns the nr defined for this column's datatype?

ContentLicense: CC BY-SA 4.0

Body:
I have a table with lat/long as NUMBER(9,7) and NUMBER(10,7) respectively.
Sometimes we store less precise coordinates, sometimes more, meaning more decimal places.
When we have similar coordinates like this:

ST_GEOHASH | LATITUDE | LONGITUDE
d3f71dbq87gk 10.3873367 -75.519661
d3f71dbq87gk 10.3873367 -75.5196609
dpsb7fr5gqs4 42.2444839 -83.1457596
dpsb7fr5gqs4 42.2444840 -83.1457596

we would like to choose just the one that has more decimal cases on LAT/LONG or max(LAT) if they both have the same amount of decimal places.
How can I achieve that if length(number) always returns the nr defined for this column's datatype?


问:
Maui ioS Overriding SendEvent and how do I access the registered services - Cannot inject either
I need to implement the SendEvent in maui ios and I have something like below
however how do access the services that got registered earlier on in the maui program?
Is there another way of doing it?</p>
```<code>public class Program
    {
        // This is the main entry point of the application.
        static void Main(string[] args)
        {
            UIApplication.Main(args, typeof(Sample), typeof(AppDelegate));
        }
    }

public class Sample : UIApplication
{
        public Sample() : base()
        {

        }

        public Sample(IntPtr handle) : base(handle)
        {
        }

        public Sample(Foundation.NSObjectFlag t) : base(t)
        {
        }
        public override void SendEvent(UIEvent uievent)
        {

            if (uievent.Type == UIEventType.Touches)
            {
                if (uievent.AllTouches.Cast<UITouch>().Any(t => t.Phase == UITouchPhase.Began))
                {
                   //dosomething here - we need to use a service that was registered earlier on
                }
            }

            base.SendEvent(uievent);
        }
    }

</code>```

Body:
I need to implement the SendEvent in maui ios and I have something like below
however how do access the services that got registered earlier on in the maui program?
Is there another way of doing it?

public class Program
    {
        // This is the main entry point of the application.
        static void Main(string[] args)
        {
            UIApplication.Main(args, typeof(Sample), typeof(AppDelegate));
        }
    }

public class Sample : UIApplication
{
        public Sample() : base()
        {

        }

        public Sample(IntPtr handle) : base(handle)
        {
        }

        public Sample(Foundation.NSObjectFlag t) : base(t)
        {
        }
        public override void SendEvent(UIEvent uievent)
        {

            if (uievent.Type == UIEventType.Touches)
            {
                if (uievent.AllTouches.Cast<UITouch>().Any(t => t.Phase == UITouchPhase.Began))
                {
                   //dosomething here - we need to use a service that was registered earlier on
                }
            }

            base.SendEvent(uievent);
        }
    }


问:
Multiple Column Form with Form Builder in Flutter
Is there anyway to have a multi-column form using Form Builder package, or any other alternative. I dont want to use native forms as it may not be a cleaner option to display 10-20 questions.

Something like this..


问:
How do I define two types of users in .NET Identity that each have different properties?
I'm using .Net Identity and I have different types of users (RegualrUser, OrganizationUser). Both of them are users.. that is, they can log in to my site.

I want to save additional information for each type, and that information is different, meaning that the first type, RegualrUser, has different properties than the second type, OrganizationUser.

Here in this answer User Claims are recommended. In fact, I am not convinced... because it is possible that these different properties are not just a value and type, but may be a relationship to another table in the database (a navigational feature).

Plus the User Claims are a difficult part for me, i didn't get what is difference between (User Claims, Identity Claims, Claims principal).

I tried to inherit from IdentityUser twice, once for the first type and once for the second. And then adding those types through the AddIdentityCore method, but it became after migration the properties were put together in the AspNetUser table, meaning Table per Hierarchy.


问:
SpringBoot password Encoder UnitTest is null

@Service
@RequiredArgsConstructor
public class MemberService {

    private final MemberRepository memberRepository;
    private final PasswordEncoder passwordEncoder;

    @Transactional
    public Member create(MemberDto memberDto) {

        memberDto.setPassword(passwordEncoder.encode(memberDto.getPassword()));

        Member member = memberDto.toEntity();

        return memberRepository.save(member);
    }

}
```
<pre class="lang-java prettyprint-override"><code>@ExtendWith(MockitoExtension.class)
@Transactional
class MemberServiceTest {

    @Mock
    private MemberRepository memberRepository;

    @InjectMocks
    private MemberService memberService;

    @Mock
    private PasswordEncoder passwordEncoder;

    @BeforeEach
    void setUp() {
        this.passwordEncoder = new BCryptPasswordEncoder();

    }

    @Test
    @DisplayName("회원가입 테스트")
    void createMember() {
        //given
        MemberDto memberDto = MemberDto.builder()
            .email("test@naver.com")
            .password("12345")
            .name("test")
            .nickname("hateTest")
            .phone("11111111")
            .build();

        //when
        memberService.create(memberDto);

        //then
        assertThat(memberRepository.findByName("test").get().getName()).isEqualTo("test");
    }
}
</code>```

java.lang.NullPointerException
    at com.stock.togetherStock.service.MemberService.create(MemberService.java:26)
    at com.stock.togetherStock.model.member.MemberServiceTest.createMember(MemberServiceTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
```

I tried hard for finding great answer about my problem and I found one which is Using BCryptPasswordEncoder in Unit Test returns a null value

but that doesn't fit on my problem.

I got null on the process of memberService.create(memberDto) in MemberServiceTest class.

that's caused by passwordEncoder.

in a way of processing password, I guess PasswordEncoder doesn't work.

but I wasn't able to find how to fix it so far(3hrs).

please help me out and let me take next coding

thank you.

3hrs, searching google, stackoverflow and so on.. but I can't find a method to fix it.

Body:
@Service
@RequiredArgsConstructor
public class MemberService {

    private final MemberRepository memberRepository;
    private final PasswordEncoder passwordEncoder;

    @Transactional
    public Member create(MemberDto memberDto) {

        memberDto.setPassword(passwordEncoder.encode(memberDto.getPassword()));

        Member member = memberDto.toEntity();

        return memberRepository.save(member);
    }

}

@ExtendWith(MockitoExtension.class)
@Transactional
class MemberServiceTest {

    @Mock
    private MemberRepository memberRepository;

    @InjectMocks
    private MemberService memberService;

    @Mock
    private PasswordEncoder passwordEncoder;

    @BeforeEach
    void setUp() {
        this.passwordEncoder = new BCryptPasswordEncoder();

    }

    @Test
    @DisplayName("회원가입 테스트")
    void createMember() {
        //given
        MemberDto memberDto = MemberDto.builder()
            .email("test@naver.com")
            .password("12345")
            .name("test")
            .nickname("hateTest")
            .phone("11111111")
            .build();

        //when
        memberService.create(memberDto);

        //then
        assertThat(memberRepository.findByName("test").get().getName()).isEqualTo("test");
    }
}

java.lang.NullPointerException
    at com.stock.togetherStock.service.MemberService.create(MemberService.java:26)
    at com.stock.togetherStock.model.member.MemberServiceTest.createMember(MemberServiceTest.java:59)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

I tried hard for finding great answer about my problem and I found one which is Using BCryptPasswordEncoder in Unit Test returns a null value

but that doesn't fit on my problem.

I got null on the process of memberService.create(memberDto) in MemberServiceTest class.

that's caused by passwordEncoder.

in a way of processing password, I guess PasswordEncoder doesn't work.

but I wasn't able to find how to fix it so far(3hrs).

please help me out and let me take next coding

thank you.

3hrs, searching google, stackoverflow and so on.. but I can't find a method to fix it.


问:
Why can't I use the WSL adapter IP to access the host services ports?
Why can't I use the WSL adapter IP to access the host services ports?

I have a proxy service running on my windows 10 host machine, and I wish to use this service in the WSL2. Many said they are in separate networks so I opened the necessary firewall ports for this proxy service.

The strange thing is, almost every post on the internet are telling me to use the "WSL adapter IP" (I mean the IP can get from cat /etc/resolv.conf or ping "$(hostname).local"). But the only way that works for me is to use Ethernet IP of the windows host. I don't know why this could happen.

I've tried the same process in different machine, but this is the first time this issue comes out.

>ipconfig

Windows IP Configuration

Ethernet adapter Ethernet (Default Switch):

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::17e4:75c9:3db3:3273%18
   IPv4 Address. . . . . . . . . . . : 192.168.0.106
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.0.1

Ethernet adapter vEthernet (WSL):

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::d573:2745:bd21:c798%32
   IPv4 Address. . . . . . . . . . . : 172.23.160.1
   Subnet Mask . . . . . . . . . . . : 255.255.240.0
   Default Gateway . . . . . . . . . :
```
<p>Version info：</p>
<pre class="lang-bash prettyprint-override"><code>Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:        20.04
Codename:       focal

> wsl --version
WSL version： 1.0.3.0
WSLg version： 1.0.47
MSRDC version： 1.2.3575
Direct3D version： 1.606.4
DXCore version： 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version： 10.0.19044.2364
</code>```

I test it by netcat：

root in ~ took 1m14s
❯ nc -zv 172.23.160.1 7890
^C

root in ~ took 5s
❯ nc -zv 192.168.0.106 7890
Connection to 192.168.0.106 7890 port [tcp/*] succeeded!
```

Body:
Why can't I use the WSL adapter IP to access the host services ports?

I have a proxy service running on my windows 10 host machine, and I wish to use this service in the WSL2. Many said they are in separate networks so I opened the necessary firewall ports for this proxy service.

The strange thing is, almost every post on the internet are telling me to use the "WSL adapter IP" (I mean the IP can get from cat /etc/resolv.conf or ping "$(hostname).local"). But the only way that works for me is to use Ethernet IP of the windows host. I don't know why this could happen.

I've tried the same process in different machine, but this is the first time this issue comes out.

>ipconfig

Windows IP Configuration

Ethernet adapter Ethernet (Default Switch):

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::17e4:75c9:3db3:3273%18
   IPv4 Address. . . . . . . . . . . : 192.168.0.106
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.0.1

Ethernet adapter vEthernet (WSL):

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::d573:2745:bd21:c798%32
   IPv4 Address. . . . . . . . . . . : 172.23.160.1
   Subnet Mask . . . . . . . . . . . : 255.255.240.0
   Default Gateway . . . . . . . . . :

Version info：

Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:        20.04
Codename:       focal

> wsl --version
WSL version： 1.0.3.0
WSLg version： 1.0.47
MSRDC version： 1.2.3575
Direct3D version： 1.606.4
DXCore version： 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version： 10.0.19044.2364

I test it by netcat：

root in ~ took 1m14s
❯ nc -zv 172.23.160.1 7890
^C

root in ~ took 5s
❯ nc -zv 192.168.0.106 7890
Connection to 192.168.0.106 7890 port [tcp/*] succeeded!


问:
Calling a subscribe method and passing value to private variable in unit testing
In my ts file inside subscribe its passing a boolean and that is by default true, Can I set it to false into this boolean variable in angular test cases

ts file

```<code>private On: boolean = true;
private Subscriptionobj: Subscription;
public ToggleSubject: Subject<boolean>;
this.ToggleSubject= new Subject<boolean>();

this.Subscriptionobj= this.ToggleSubject.subscribe((IsOn: boolean) => {
  this.On = IsOn;
});
</code>```

spec.ts

```<code>component.ToggleSubject.subscribe
((IsOn: boolean) => {
  component.On = IsOn;
});
</code>```

Body:
In my ts file inside subscribe its passing a boolean and that is by default true, Can I set it to false into this boolean variable in angular test cases

ts file

private On: boolean = true;
private Subscriptionobj: Subscription;
public ToggleSubject: Subject<boolean>;
this.ToggleSubject= new Subject<boolean>();

this.Subscriptionobj= this.ToggleSubject.subscribe((IsOn: boolean) => {
  this.On = IsOn;
});

spec.ts

component.ToggleSubject.subscribe
((IsOn: boolean) => {
  component.On = IsOn;
});


问:
Xaringan: Extra character in panel
New to Xaringan and StackOverflow.  Had a hard time figuring out how to create tabs (panels) on slides given the info available in the instructions.  But, I have it working.  However, there is a ] below the title on every Panel slide.  Why?  This seems to be causing my text to go off the bottom of the slide.  I think if I could remove it, then the slides would shift upwards and there would be enough space for my content to fit on the slide.

I have tried removing various ] brackets, but depending on which one I remove, it either removes panels and overlaps all of the content on one slide with the tables and graphs or it deletes the panel and all the content from the panel.

At first, I was unable to make more than one slides with panels.  The first slide worked perfectly fine and did not have the random ] at the top of it.  But the second slide would not create panels.  It just threw all of the content overlapping on one slide.  I was able to create two slides with panels when I found

div solution
here
, but that is when the issue with the ] started appearing.  The ] is not part of the content.

In reality, there are 4 tabs per slide in roughly the following format:

Tab 1: content and image

Tab 2: R code reactable table

Tab 3: conent and imate

Tab 4: R code ggplot2 plotly interactive graph

I expect one slide with 4 tabs that can be clicked on, but without the extra space or extra characters between the title and the tabs.

EDIT

I put my code here, but someone changed it and it no longer reflected what I had written.  I deleted it because it was no longer my code.  I also found something in the source code. There is clearly a
]
 in the source code.  How do I find that file and remove it from the source code?

Title: Xaringan: Extra character in panel


问:
How do you make a bookmarklet that makes an about: blank page and inserts an iframe onto the about: blank page
This is what i have to make the about: blank page now i need to have it make an iframe</p>
```<code>javascript: var x = window.open(''); x.document.write("DONE"); x.alert('YOOO'); function(){var script=document.createElement('SCRIPT'); type here
</code>```

Body:
This is what i have to make the about: blank page now i need to have it make an iframe

javascript: var x = window.open(''); x.document.write("DONE"); x.alert('YOOO'); function(){var script=document.createElement('SCRIPT'); type here


问:
Using an enum from another file as a parameter in PHP
I have a php file that handles mailing. The Mail() function requires a case to determine the subject and body of the email that is to be sent. To prevent the caller from giving wrong parameters I am using an enum as shown below:

```<code><?php

enum MailCase
{
    case bestOffer;
    case notForSale;
}

function Email($product_ean, MailCase $case)
{
    // TODO: Product titel in onderwerp.
    $to = 'receiver@company.com';
    $headers = 'From: sender@company.com' . "\r\n" .
        'Reply-To: sender@company.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    switch ($case) {
        case MailCase::bestOffer:
            $subject = 'Lorem ipsum 1';
            $message = '
            This body is variant 1 for case 1.
            PRODUCT: ' . $product_ean;
            break;
        case MailCase::notForSale:
            $subject = 'Lorem ipsum 2';
            $message = '
            This body is variant 2 for case 2.
            PRODUCT: ' . $product_ean;
            break;
    }
    mail($to, $subject, $message, $headers);
}
</code>```

This php file is required in the main file and is called via require_once("mailer.php");

Then, the following function calls the function that starts the mail procedure:

```<code>alertRetailer($product, MailCase::notForSale);
</code>```

Which executes this:

```<code>function alertRetailer($product, MailCase $case)
{
    Email($product, $case);
}
</code>```

When running this program the following parse error is show in the browser:

```<code>Parse error: syntax error, unexpected 'MailCase' (T_STRING) in /domain/mailer.php on line 3
</code>```

As far as I can see the file that provides the mailing functionality and the enum is required the right way and IntelliSense doesn't show an error that the file is not found. I would like to hear you guys' view on my scenario.

EDIT:

PHP version was checked:

Thanks!

Body:
I have a php file that handles mailing. The Mail() function requires a case to determine the subject and body of the email that is to be sent. To prevent the caller from giving wrong parameters I am using an enum as shown below:

<?php

enum MailCase
{
    case bestOffer;
    case notForSale;
}

function Email($product_ean, MailCase $case)
{
    // TODO: Product titel in onderwerp.
    $to = 'receiver@company.com';
    $headers = 'From: sender@company.com' . "\r\n" .
        'Reply-To: sender@company.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    switch ($case) {
        case MailCase::bestOffer:
            $subject = 'Lorem ipsum 1';
            $message = '
            This body is variant 1 for case 1.
            PRODUCT: ' . $product_ean;
            break;
        case MailCase::notForSale:
            $subject = 'Lorem ipsum 2';
            $message = '
            This body is variant 2 for case 2.
            PRODUCT: ' . $product_ean;
            break;
    }
    mail($to, $subject, $message, $headers);
}

This php file is required in the main file and is called via require_once("mailer.php");

Then, the following function calls the function that starts the mail procedure:

alertRetailer($product, MailCase::notForSale);

Which executes this:

function alertRetailer($product, MailCase $case)
{
    Email($product, $case);
}

When running this program the following parse error is show in the browser:

Parse error: syntax error, unexpected 'MailCase' (T_STRING) in /domain/mailer.php on line 3

As far as I can see the file that provides the mailing functionality and the enum is required the right way and IntelliSense doesn't show an error that the file is not found. I would like to hear you guys' view on my scenario.

EDIT:

PHP version was checked:

Thanks!


问:
Python basemap - struggling with putting a basemap on top of a satellite image
I have a satellite image taken from NWC-SAF of a certain region of the world, and 2 ndarrays that holds data about the latitudes and longitudes values of each pixel.

I try to use this information and mpl_toolkits.basemap package to accurately add land and Maritime borders to the image.

This is the script i used to build the basemap:

```<code>def add_basemap(foreground_dimensions: tuple[int, int], low_left_corner_lat, low_left_corner_lon, upper_right_corner_lat, upper_right_corner_lon, dpi):
    """
    Given a satellite image and its coordinates (corners' latitudes & longitudes), Add borders and coastlines
    """
    plt.clf()
    width, height = foreground_dimensions[0], foreground_dimensions[1]
    fig = plt.figure(figsize=(width / (dpi), height / (dpi)), dpi=dpi)
    map_figure = Basemap(projection='cyl',
                         llcrnrlat=low_left_corner_lat,
                         llcrnrlon=low_left_corner_lon,
                         urcrnrlat=upper_right_corner_lat,
                         urcrnrlon=upper_right_corner_lon,
                         resolution='i',
                         )

    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.axis('tight')
    plt.axis('off')
    plt.margins(0)
    map_figure.drawcoastlines(linewidth=dpi / 8)
</code>```

foreground_dimensions are the dimensions of the satellite image.

the result that i get is not accurate:
result

the green is the land and blue is water and as you can see the map does not fit accurately on the image.

I guess that the problem is projection differences - i use satallite image from NWC-SAF, which if i understood correctly from their website, they use "polar stereographic, map-projection". I think that the correspond projection in Basemap is either 'npstere' or 'spstere', so i tried using them, creating the following basemap:

```<code>map_figure = Basemap(projection='npstere', boundinglat=max_lat, lon_0=middle_lon, resolution='l')
</code>```

where biggest_lat is the max latitude value that appears in the satellite picture, and middle_lon is the longitude value of the middle pixel of the satellite picture.

But this gives a map that doesn't make any sense (unlike the previous map i generated which correlates to the original image but not accurate).

How can i generate an accurate map? using Basemap or maybe cartopy?

Thanks

Body:
I have a satellite image taken from NWC-SAF of a certain region of the world, and 2 ndarrays that holds data about the latitudes and longitudes values of each pixel.

I try to use this information and mpl_toolkits.basemap package to accurately add land and Maritime borders to the image.

This is the script i used to build the basemap:

def add_basemap(foreground_dimensions: tuple[int, int], low_left_corner_lat, low_left_corner_lon, upper_right_corner_lat, upper_right_corner_lon, dpi):
    """
    Given a satellite image and its coordinates (corners' latitudes & longitudes), Add borders and coastlines
    """
    plt.clf()
    width, height = foreground_dimensions[0], foreground_dimensions[1]
    fig = plt.figure(figsize=(width / (dpi), height / (dpi)), dpi=dpi)
    map_figure = Basemap(projection='cyl',
                         llcrnrlat=low_left_corner_lat,
                         llcrnrlon=low_left_corner_lon,
                         urcrnrlat=upper_right_corner_lat,
                         urcrnrlon=upper_right_corner_lon,
                         resolution='i',
                         )

    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.axis('tight')
    plt.axis('off')
    plt.margins(0)
    map_figure.drawcoastlines(linewidth=dpi / 8)

foreground_dimensions are the dimensions of the satellite image.

the result that i get is not accurate:
result

the green is the land and blue is water and as you can see the map does not fit accurately on the image.

I guess that the problem is projection differences - i use satallite image from NWC-SAF, which if i understood correctly from their website, they use "polar stereographic, map-projection". I think that the correspond projection in Basemap is either 'npstere' or 'spstere', so i tried using them, creating the following basemap:

map_figure = Basemap(projection='npstere', boundinglat=max_lat, lon_0=middle_lon, resolution='l')

where biggest_lat is the max latitude value that appears in the satellite picture, and middle_lon is the longitude value of the middle pixel of the satellite picture.

But this gives a map that doesn't make any sense (unlike the previous map i generated which correlates to the original image but not accurate).

How can i generate an accurate map? using Basemap or maybe cartopy?

Thanks


问:
.Net Api - DataAnnotations in EF or in request model
I've a question with EF Code First.

I have a controller that accepts data through a model. Then this data is validated, processed, etc and then stored in a MsSql database. Now Im a bit where I need to put the data annotations for the specific fields.

For example this is the controller data

```<code>public class RequestCreateUser {
    public string Emailaddress {get;set;}
    public string Password {get;set;}
}
</code>```

Then this is used in a controller for example:

```<code>public ActionResult CreateUser(RequestCreateUser request) {
     var result = UserService.CreateUser(request);
     return OK();
}
</code>```

In the userService, I hash the password and whatever, and then it is stored to the database with a model that EF  uses.

```<code>public class User {
    public string Emailaddress {get;set;}
    public string Password {get;set;}
    public string PasswordSalt {get;set;}
}
</code>```

Now my question is, to validate if the password is of a specific minimal length I can use the DataAnnotation [MinLength(8)].

I can put this at the EF model, the Request model or Both.

Now I would say I need to put it on the Ef model because then it uses the data annotations for database generation.

But I would also like it to have it in the Request model so automatic validation happens and the user sees an appropriate error message: "Your password should be at least 8 characters long"

So I would say: put them on both. But I also don't really like that because if I need to change it, I have to change it in multiple places.

Whats the best practage of this?

Body:
I've a question with EF Code First.

I have a controller that accepts data through a model. Then this data is validated, processed, etc and then stored in a MsSql database. Now Im a bit where I need to put the data annotations for the specific fields.

For example this is the controller data

public class RequestCreateUser {
    public string Emailaddress {get;set;}
    public string Password {get;set;}
}

Then this is used in a controller for example:

public ActionResult CreateUser(RequestCreateUser request) {
     var result = UserService.CreateUser(request);
     return OK();
}

In the userService, I hash the password and whatever, and then it is stored to the database with a model that EF  uses.

public class User {
    public string Emailaddress {get;set;}
    public string Password {get;set;}
    public string PasswordSalt {get;set;}
}

Now my question is, to validate if the password is of a specific minimal length I can use the DataAnnotation [MinLength(8)].

I can put this at the EF model, the Request model or Both.

Now I would say I need to put it on the Ef model because then it uses the data annotations for database generation.

But I would also like it to have it in the Request model so automatic validation happens and the user sees an appropriate error message: "Your password should be at least 8 characters long"

So I would say: put them on both. But I also don't really like that because if I need to change it, I have to change it in multiple places.

Whats the best practage of this?


问:
Jenkins always told me "Failed to connect to repository"
I have already created ssh key and post on the gitlab, but it's still wrong

It's error message:

```<code>Failed to connect to repository : Command "git ls-remote -h -- git@gitlab.com:GoldenMagicDogeGroup/jenkinstest.git HEAD" returned status code 128:
stdout:
stderr: Load key "/tmp/jenkins-gitclient-ssh14005393280406542908.key": invalid format
git@gitlab.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

And here is my step:

create access token in gitlab

generate ssh key in jenkins container

post public key on gitlab

add credential in jenkins, chose gitlab api token

add credential in jenkins, chose ssh username with private key

What's I lack?

And I tried command git ls-remote -h -- git@gitlab.com:GoldenMagicDogeGroup/jenkinstest.git HEAD, but it doesn't return anything, I think it maybe is a problem

I also tried command git ls-remote -- git@gitlab.com:GoldenMagicDogeGroup/jenkinstest.git, and this is return:

```<code>2ecdc0c3a369db00c992947642413196e64c8809        HEAD
2ecdc0c3a369db00c992947642413196e64c8809        refs/heads/main
</code>```

Body:
I have already created ssh key and post on the gitlab, but it's still wrong

It's error message:

Failed to connect to repository : Command "git ls-remote -h -- git@gitlab.com:GoldenMagicDogeGroup/jenkinstest.git HEAD" returned status code 128:
stdout:
stderr: Load key "/tmp/jenkins-gitclient-ssh14005393280406542908.key": invalid format
git@gitlab.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

And here is my step:

create access token in gitlab

generate ssh key in jenkins container

post public key on gitlab

add credential in jenkins, chose gitlab api token

add credential in jenkins, chose ssh username with private key

What's I lack?

And I tried command git ls-remote -h -- git@gitlab.com:GoldenMagicDogeGroup/jenkinstest.git HEAD, but it doesn't return anything, I think it maybe is a problem

I also tried command git ls-remote -- git@gitlab.com:GoldenMagicDogeGroup/jenkinstest.git, and this is return:

2ecdc0c3a369db00c992947642413196e64c8809        HEAD
2ecdc0c3a369db00c992947642413196e64c8809        refs/heads/main


问:
Meaning of mpi and openMP execution times
I have a cluster made up of 4 nodes, where each node has 2 processors, and each processor has 8 cores, for a total of 16 cores per machine. I have this application made in two versions one in mpi and the other in openMP for image convolution. When I run the mpi program with 1-2-4-8-12 and 16 cores on the cluster I get the following execution times in seconds:

```<code>1 core 9.4
2 cores 4.95
4 cores 2.55
8 cores 1.4
12 cores 0.91
16 cores 0.72
</code>```

instead when I run the openMP code with two threads I get the following execution times:

```<code>1 core 4.95
2 cores 2.65
4 cores 1.33
8 cores 0.68
12 cores 0.77
16 cores 0.64
</code>```

when I always run it with openMP with 4 threads I have the following execution times:

```<code>1 core 2.64
2 cores 1.37
4 cores 0.80
8 cores 0.66
12 cores 0.86
16 cores 1.10
</code>```

what i can't figure out why with 2 threads as the number of processors increases the time decreases, except in the case with 12 cores. Instead in the case with 4 threads up to 8 cores the times decrease, from 8 cores onwards the times start to increase. Is there anyone who can give me an explanation of these execution times? Particularly:

because in the case with 2 threads I get a higher time than with 8 cores and 16 cores

why in the case with 4 threads do the times increase from 8 cores onwards?

Thanks to whoever will answer.

Body:
I have a cluster made up of 4 nodes, where each node has 2 processors, and each processor has 8 cores, for a total of 16 cores per machine. I have this application made in two versions one in mpi and the other in openMP for image convolution. When I run the mpi program with 1-2-4-8-12 and 16 cores on the cluster I get the following execution times in seconds:

1 core 9.4
2 cores 4.95
4 cores 2.55
8 cores 1.4
12 cores 0.91
16 cores 0.72

instead when I run the openMP code with two threads I get the following execution times:

1 core 4.95
2 cores 2.65
4 cores 1.33
8 cores 0.68
12 cores 0.77
16 cores 0.64

when I always run it with openMP with 4 threads I have the following execution times:

1 core 2.64
2 cores 1.37
4 cores 0.80
8 cores 0.66
12 cores 0.86
16 cores 1.10

what i can't figure out why with 2 threads as the number of processors increases the time decreases, except in the case with 12 cores. Instead in the case with 4 threads up to 8 cores the times decrease, from 8 cores onwards the times start to increase. Is there anyone who can give me an explanation of these execution times? Particularly:

because in the case with 2 threads I get a higher time than with 8 cores and 16 cores

why in the case with 4 threads do the times increase from 8 cores onwards?

Thanks to whoever will answer.


问:
Configure Rider not to delete some unused imports
Is it possible in Rider to configure a list of namespaces that should not be deleted by executing ‘Remove unused imports’? Ideally this would also not mark them as unused. In Resharper this is possible using «Namespace that should always be imported», but I can’t seem to find an equivalent option in Rider.</p>


问:
gt table package in R produces header error
I am using the gt() table package in R and so far I love it. However for some reason when I publish the below in quarto I get an awkward table header that says "?caption" in bold. However when I run the table separately, I don't get anything.

Any thoughts?

Ignore the titles and columns names, I know it doesn't make sense with the diamonds package

```<code>library(tidyverse)
library(gt)

business_segment_summary <- diamonds %>%
  group_by(cut) %>%
  summarise(n=n(),
    sum=sum(price),
    sum_od=sum(price,na.rm=TRUE),
    prop_25=quantile(price,.25,na.rm=TRUE),
    prop_50=quantile(price,.5,na.rm=TRUE),
    prop_75=quantile(price,.75,na.rm=TRUE),
    mean=mean(price,na.rm=TRUE),
    mean_aging=mean(table),
    mean_rank=mean(depth),
    prop_od=mean(carat),
    sd=sd(price,na.rm=TRUE),
    mad=mad(price,na.rm=TRUE),
    .groups="drop"
    ) %>%
  mutate(tar_prop=sum/sum(sum),
         n_prop=n/sum(n))

business_segment_summary %>%
  select(1,n,tar_prop,n_prop,prop_od,prop_25,prop_50,prop_75) %>%
  gt::gt()
  gt::cols_label(cut="Business Segment",
                 n="Customer #",
                 tar_prop="% of TAR",
                 n_prop="% of Customers",
                 prop_od=gt::html("% of Customers<br>with overdue"),
                 prop_25="25%",
                 prop_50="50%",
                 prop_75="75%") %>%
  gt::tab_spanner(label="Customer Account Percentile ($k)",columns = c(prop_25,prop_50,prop_75)) %>%
  gt::fmt_number(c(prop_25,prop_50,prop_75),decimals = 0,scale_by = 1/1e3) %>%
  gt::fmt_number(n,decimals = 0) %>%
  gt::fmt_percent(c(3:5),decimals = 0) %>%
  gt::opt_stylize(style=1,color="red") %>%
  gt::tab_header(title="Summary of TAR by business segments") %>%
  gt::cols_align(align="left",columns = 1)

</code>```

Body:
I am using the gt() table package in R and so far I love it. However for some reason when I publish the below in quarto I get an awkward table header that says "?caption" in bold. However when I run the table separately, I don't get anything.

Any thoughts?

Ignore the titles and columns names, I know it doesn't make sense with the diamonds package

library(tidyverse)
library(gt)

business_segment_summary <- diamonds %>%
  group_by(cut) %>%
  summarise(n=n(),
    sum=sum(price),
    sum_od=sum(price,na.rm=TRUE),
    prop_25=quantile(price,.25,na.rm=TRUE),
    prop_50=quantile(price,.5,na.rm=TRUE),
    prop_75=quantile(price,.75,na.rm=TRUE),
    mean=mean(price,na.rm=TRUE),
    mean_aging=mean(table),
    mean_rank=mean(depth),
    prop_od=mean(carat),
    sd=sd(price,na.rm=TRUE),
    mad=mad(price,na.rm=TRUE),
    .groups="drop"
    ) %>%
  mutate(tar_prop=sum/sum(sum),
         n_prop=n/sum(n))

business_segment_summary %>%
  select(1,n,tar_prop,n_prop,prop_od,prop_25,prop_50,prop_75) %>%
  gt::gt()
  gt::cols_label(cut="Business Segment",
                 n="Customer #",
                 tar_prop="% of TAR",
                 n_prop="% of Customers",
                 prop_od=gt::html("% of Customers
with overdue"),
                 prop_25="25%",
                 prop_50="50%",
                 prop_75="75%") %>%
  gt::tab_spanner(label="Customer Account Percentile ($k)",columns = c(prop_25,prop_50,prop_75)) %>%
  gt::fmt_number(c(prop_25,prop_50,prop_75),decimals = 0,scale_by = 1/1e3) %>%
  gt::fmt_number(n,decimals = 0) %>%
  gt::fmt_percent(c(3:5),decimals = 0) %>%
  gt::opt_stylize(style=1,color="red") %>%
  gt::tab_header(title="Summary of TAR by business segments") %>%
  gt::cols_align(align="left",columns = 1)


问:
Add de_AT _locales to chrome extension
Is there a way to add locales to extension other than those listed at: https://developer.chrome.com/docs/webstore/i18n/#choosing-locales-to-support?

I tried de_AT but translation showed is for de. Same with en_AU, translation is for en_US.

Or maybe is its possible to redirect en_AU, en_NZ and every unsuported code to default_locale?

Title: Add de_AT _locales to chrome extension


问:
Django custom model template
I want to create a custom datetimefield. I know that models.DateTimeField use the template admin/widgets/split_datetime.html
I've modified that template to accomplish what i want.
But now i want two have the original DateTimeField in same models and a new one in anothers.
I've create my new model.

```<code>class DateTimeFieldHorizontal(models.DateTimeField):
  template_name = 'mydjango/widgets/my_split_datetime.html'
</code>```

But this model also use original split_datetime.html.
'mydjango/widgets/my_split_datetime.html' is in template folder
I didn't found how to change models template file.

Thanks.

Title: Django custom model template

Body:
I want to create a custom datetimefield. I know that models.DateTimeField use the template admin/widgets/split_datetime.html
I've modified that template to accomplish what i want.
But now i want two have the original DateTimeField in same models and a new one in anothers.
I've create my new model.

class DateTimeFieldHorizontal(models.DateTimeField):
  template_name = 'mydjango/widgets/my_split_datetime.html'

But this model also use original split_datetime.html.
'mydjango/widgets/my_split_datetime.html' is in template folder
I didn't found how to change models template file.

Thanks.


问:
How does Golang GC reclaim complete allocations when user references don't point to the start of the allocation?
How does the Go garbage collector know the beginning address of a slice's backing store, if the slice points to the middle of the original store?

Consider the following:

```<code>array := make([]int, 1000)
slice := array[999:1000]
array = nil
</code>```

We are famously warned that the GC will hang on to the entire array although the ptr part of slice points towards the end of the original array.

But where is the original address of the array kept so the GC can clear it entirely?
When the GC begins its mark phase and reaches slice, how does it mark the beginning of the array as "in use"?

Same question could be asked for other cases of the GC not collecting objects when the user only has a reference to part of them such as when the user only has references to a part of a struct or a string.

Edit:
After some discussion I suspect that in all of these cases when the GC performs the mark phase for a user reference it performs a lookup in its internal allocation block mechanisms searching for the block  within which the address of the user reference is contained and marks the entire block as "In Use"

Body:
How does the Go garbage collector know the beginning address of a slice's backing store, if the slice points to the middle of the original store?

Consider the following:

array := make([]int, 1000)
slice := array[999:1000]
array = nil

We are famously warned that the GC will hang on to the entire array although the ptr part of slice points towards the end of the original array.

But where is the original address of the array kept so the GC can clear it entirely?
When the GC begins its mark phase and reaches slice, how does it mark the beginning of the array as "in use"?

Same question could be asked for other cases of the GC not collecting objects when the user only has a reference to part of them such as when the user only has references to a part of a struct or a string.

Edit:
After some discussion I suspect that in all of these cases when the GC performs the mark phase for a user reference it performs a lookup in its internal allocation block mechanisms searching for the block  within which the address of the user reference is contained and marks the entire block as "In Use"


问:
First little program, cant seem to fix the capitalization error
This is my first little program I have created. Can anyone help me with making it so it works with the first letter being capitalized?

```<code># Rock Paper Scissors

import time
import random

user_wins = 0
computer_wins = 0

def RockPaperScissors():
    user_choice = input("Enter your choice in a game of Rock, Paper, Scissors: ")

    if user_choice == "rock" or user_choice == "paper" or user_choice == "scissors":
        print("Good choice, lets see who wins.")
        time.sleep(1.5)
    else:
        print('Please enter either "rock", "paper", or "scissors"')

    computer_choice = ["rock", "paper", "scissors"]
    rand_choice = random.choice(computer_choice)

    print("The computer chose", rand_choice)

    if user_choice == "rock" and rand_choice == "scissors":
        print("You won!")
    elif user_choice == "scissors" and rand_choice == "rock":
        print("The computer won, try again.")
    elif user_choice == "paper" and rand_choice == "rock":
        print("You won!")
    elif user_choice == "rock" and rand_choice == "paper":
        print("The computer won, try again")
    elif user_choice == "scissors" and rand_choice == "paper":
        print("You won!")
    elif user_choice == "paper" and rand_choice == "scissors":
        print("The computer won, try again")

RockPaperScissors()
</code>```

I also have a slight issue with if you capitalize the first letter, the program does not run as intended. Appreciate the help!

Body:
This is my first little program I have created. Can anyone help me with making it so it works with the first letter being capitalized?

# Rock Paper Scissors

import time
import random

user_wins = 0
computer_wins = 0

def RockPaperScissors():
    user_choice = input("Enter your choice in a game of Rock, Paper, Scissors: ")

    if user_choice == "rock" or user_choice == "paper" or user_choice == "scissors":
        print("Good choice, lets see who wins.")
        time.sleep(1.5)
    else:
        print('Please enter either "rock", "paper", or "scissors"')

    computer_choice = ["rock", "paper", "scissors"]
    rand_choice = random.choice(computer_choice)

    print("The computer chose", rand_choice)

    if user_choice == "rock" and rand_choice == "scissors":
        print("You won!")
    elif user_choice == "scissors" and rand_choice == "rock":
        print("The computer won, try again.")
    elif user_choice == "paper" and rand_choice == "rock":
        print("You won!")
    elif user_choice == "rock" and rand_choice == "paper":
        print("The computer won, try again")
    elif user_choice == "scissors" and rand_choice == "paper":
        print("You won!")
    elif user_choice == "paper" and rand_choice == "scissors":
        print("The computer won, try again")

RockPaperScissors()

I also have a slight issue with if you capitalize the first letter, the program does not run as intended. Appreciate the help!


问:
symfony 6 book, the-fast-track, 8-doctrine: symfony console make:migration: fe_sendauth: no password supplied

Below the Symfony: The Fast Track book I walk through the steps.

On point 8. Doctrine (
https://symfony.com/doc/current/the-fast-track/en/8-doctrine.html#migrating-the-database): Migrating the Database

$ symfony console make:migration
```
<p><strong>expected:</strong><br>
generated file name:</p>
<blockquote>
<p>migrations/Version20191019083640.php)</p>
</blockquote>
<p><strong>unexpected:</strong><br></p>
<pre class="lang-bash prettyprint-override"><code>In ExceptionConverter.php line 77:
An exception occurred in the driver: SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above

In Exception.php line 28:
SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above

In Driver.php line 29:
SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above
</code>```

$ symfony run psql
psql: error: connection to server at "127.0.0.1", port 50615 failed: FATAL:  password authentication failed for user "app"
command "psql" failed: exit status 2

```
<p><strong>Work Environment:</strong></p>
<p>Device: Mac, Apple M1 Max, Ventura 13.1</p>
<pre class="lang-bash prettyprint-override"><code>$ symfony server:start -d
[OK] Web server listening
      The Web server is using PHP CGI 8.1.1
      https://127.0.0.1:8000
</code>```

$ symfony proxy:start
[OK] Proxy server listening on http://localhost:7080
```
<pre class="lang-bash prettyprint-override"><code>$ docker-compose ps
guestbook-database-1  "docker-entrypoint.s…"  database running             0.0.0.0:60714->5432/tcp
</code>```

$ postgres -V
postgres (PostgreSQL) 14.6 (Homebrew)
```
<pre class="lang-bash prettyprint-override"><code>$ brew install libpq
/...
Warning: libpq 15.1 is already installed and up-to-date.
</code>```

$ docker-compose exec database psql app app
app=# SELECT version();
                                                        version
-----------------------------------------------------------------------------------------------------------------------
 PostgreSQL 14.6 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 12.2.1_git20220924-r4) 12.2.1 20220924, 64-bit
(1 row)
app=# \! psql -V
psql (PostgreSQL) 14.6
```
<pre class="lang-bash prettyprint-override"><code>$ symfony book:check-requirements
[OK] Git installed
[OK] PHP installed version 8.1.1 (/Applications/MAMP/bin/php/php8.1.1/bin/php)
[OK] PHP extension "intl" installed - required
[KO] PHP extension "amqp" not found, optional - needed only for chapter 32
[OK] PHP extension "json" installed - required
[OK] PHP extension "session" installed - required
[OK] PHP extension "xml" installed - required
[KO] PHP extension "redis" not found, optional - needed only for chapter 31
[OK] PHP extension "pdo_pgsql" installed - required
[OK] PHP extension "sodium" installed - required
[OK] PHP extension "curl" installed - optional - needed only for chapter 17 (Panther)
[OK] PHP extension "gd" installed - optional - needed only for chapter 23 (Imagine)
[OK] PHP extension "ctype" installed - required
[OK] PHP extension "tokenizer" installed - required
[OK] PHP extension "zip" installed - optional - needed only for chapter 17 (Panther)
[OK] PHP extension "mbstring" installed - required
[OK] PHP extension "xsl" installed - required
[OK] PHP extension "openssl" installed - required
[OK] Composer installed
[OK] Docker installed
[OK] Docker Compose installed
[OK] npm installed
</code>```

Body:
Below the Symfony: The Fast Track book I walk through the steps.

On point 8. Doctrine (
https://symfony.com/doc/current/the-fast-track/en/8-doctrine.html#migrating-the-database): Migrating the Database

$ symfony console make:migration

expected:

generated file name:

migrations/Version20191019083640.php)

unexpected:

In ExceptionConverter.php line 77:
An exception occurred in the driver: SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above

In Exception.php line 28:
SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above

In Driver.php line 29:
SQLSTATE[08006] [7] SCRAM authentication requires libpq version 10 or above

$ symfony run psql
psql: error: connection to server at "127.0.0.1", port 50615 failed: FATAL:  password authentication failed for user "app"
command "psql" failed: exit status 2

Work Environment:

Device: Mac, Apple M1 Max, Ventura 13.1

$ symfony server:start -d
[OK] Web server listening
      The Web server is using PHP CGI 8.1.1
      https://127.0.0.1:8000

$ symfony proxy:start
[OK] Proxy server listening on http://localhost:7080

$ docker-compose ps
guestbook-database-1  "docker-entrypoint.s…"  database running             0.0.0.0:60714->5432/tcp

$ postgres -V
postgres (PostgreSQL) 14.6 (Homebrew)

$ brew install libpq
/...
Warning: libpq 15.1 is already installed and up-to-date.

$ docker-compose exec database psql app app
app=# SELECT version();
                                                        version
-----------------------------------------------------------------------------------------------------------------------
 PostgreSQL 14.6 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 12.2.1_git20220924-r4) 12.2.1 20220924, 64-bit
(1 row)
app=# \! psql -V
psql (PostgreSQL) 14.6

$ symfony book:check-requirements
[OK] Git installed
[OK] PHP installed version 8.1.1 (/Applications/MAMP/bin/php/php8.1.1/bin/php)
[OK] PHP extension "intl" installed - required
[KO] PHP extension "amqp" not found, optional - needed only for chapter 32
[OK] PHP extension "json" installed - required
[OK] PHP extension "session" installed - required
[OK] PHP extension "xml" installed - required
[KO] PHP extension "redis" not found, optional - needed only for chapter 31
[OK] PHP extension "pdo_pgsql" installed - required
[OK] PHP extension "sodium" installed - required
[OK] PHP extension "curl" installed - optional - needed only for chapter 17 (Panther)
[OK] PHP extension "gd" installed - optional - needed only for chapter 23 (Imagine)
[OK] PHP extension "ctype" installed - required
[OK] PHP extension "tokenizer" installed - required
[OK] PHP extension "zip" installed - optional - needed only for chapter 17 (Panther)
[OK] PHP extension "mbstring" installed - required
[OK] PHP extension "xsl" installed - required
[OK] PHP extension "openssl" installed - required
[OK] Composer installed
[OK] Docker installed
[OK] Docker Compose installed
[OK] npm installed


问:
Datepicker in Django and update tables with jquery or without
Good good evening!

I've been thinking for a few days now and using different options to solve the problem - updating the table when a date interval is selected.

I have a table and a form to display data and a calendar.

I'm taking two different values from a calendar and trying to update the data in a table.
But nothing happens to me.

I would be very grateful if you manage to at least suggest something to find an error.
Save me please.

Maybe you will offer a more simplified version without using jquery - I will be very grateful.

models

```<code>from django.db import models

class EmployeeModel(models.Model):
    empid = models.IntegerField(primary_key=True)
    empname = models.CharField(max_length=50)
    salary = models.IntegerField()
    joindate = models.DateField()
    class Meta:
        db_table = "employee"
</code>```

forms

```<code>from datetime import date
from django import forms
from .models import *

today = date.today()

class StockHistorySearchForm(forms.ModelForm):
    start_date = forms.DateField(required=False)
    end_date = forms.DateField(required=False)
    class Meta:
        model = EmployeeModel
        fields = ['start_date', 'end_date']
</code>```

views

```<code>from django.shortcuts import render
from django_filters.views import FilterView
from django_tables2 import SingleTableMixin

# Create your views here.

from django.http import HttpResponse
from . import models
from .models import EmployeeModel

from .forms import StockHistorySearchForm

def showresults(request):
    header = "HYSTORY DATA"
    queryset = EmployeeModel.objects.all()
    form = StockHistorySearchForm(request.POST or None)
    context = {
        "header":header,
        "queryset":queryset,
        "form":form,
    }
    if request.method == "POST":
        queryset = EmployeeModel.objects.filter(
            joindate__range=[
                form['start_date'].value(),
                form['end_date'].value()
            ]
        )
    return render(request, "demo/index.html", context)
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en">
{% load static %}
{% load crispy_forms_tags %}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link href="static/js/jquery-ui-1.13.2/jquery-ui.min.css" rel="stylesheet">
    <link href="static/js/jquery-ui-1.13.2/jquery-ui.structure.min.css" rel="stylesheet">
    <link href="static/js/jquery-ui-1.13.2/jquery-ui.theme.min.css" rel="stylesheet">

    <script src="static/js/jquery-3.6.3.min.js"></script>
    <script src="static/js/jquery-ui-1.13.2/jquery-ui.js"></script>
    <script src="static/js/myjs.js"></script>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="header">{{header}}</div>
        <form method="POST" action="">
            {% csrf_token %}
            {{form|crispy}}
            <input type="submit" value="Search"/>
        </form>
        <hr/>
        <div class="display_table">
            <table class="table">
                <thead>
                    <tr>
                        <th>Employee Id</th>
                        <th>Employee Name</th>
                        <th>Salary</th>
                        <th>Join Date</th>
                    </tr>
                </thead>
                {% for instance in queryset %}
                <tr>
                    <td>{{ instance.empid }}</td>
                    <td>{{ instance.empname }}</td>
                    <td>{{ instance.salary }}</td>
                    <td>{{ instance.joindate }}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
</code>```

myjs.js

```<code>$(document).ready(function(){

  $(".datetimeinput").datepicker({changeYear: true,changeMonth: true, dateFormat: 'yy-mm-dd'});

});
</code>```

enter image description here

Body:
Good good evening!

I've been thinking for a few days now and using different options to solve the problem - updating the table when a date interval is selected.

I have a table and a form to display data and a calendar.

I'm taking two different values from a calendar and trying to update the data in a table.
But nothing happens to me.

I would be very grateful if you manage to at least suggest something to find an error.
Save me please.

Maybe you will offer a more simplified version without using jquery - I will be very grateful.

models

from django.db import models

class EmployeeModel(models.Model):
    empid = models.IntegerField(primary_key=True)
    empname = models.CharField(max_length=50)
    salary = models.IntegerField()
    joindate = models.DateField()
    class Meta:
        db_table = "employee"

forms

from datetime import date
from django import forms
from .models import *

today = date.today()

class StockHistorySearchForm(forms.ModelForm):
    start_date = forms.DateField(required=False)
    end_date = forms.DateField(required=False)
    class Meta:
        model = EmployeeModel
        fields = ['start_date', 'end_date']

views

from django.shortcuts import render
from django_filters.views import FilterView
from django_tables2 import SingleTableMixin

# Create your views here.

from django.http import HttpResponse
from . import models
from .models import EmployeeModel

from .forms import StockHistorySearchForm

def showresults(request):
    header = "HYSTORY DATA"
    queryset = EmployeeModel.objects.all()
    form = StockHistorySearchForm(request.POST or None)
    context = {
        "header":header,
        "queryset":queryset,
        "form":form,
    }
    if request.method == "POST":
        queryset = EmployeeModel.objects.filter(
            joindate__range=[
                form['start_date'].value(),
                form['end_date'].value()
            ]
        )
    return render(request, "demo/index.html", context)

index.html

<!DOCTYPE html>

{% load static %}
{% load crispy_forms_tags %}

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link href="static/js/jquery-ui-1.13.2/jquery-ui.min.css" rel="stylesheet">
    <link href="static/js/jquery-ui-1.13.2/jquery-ui.structure.min.css" rel="stylesheet">
    <link href="static/js/jquery-ui-1.13.2/jquery-ui.theme.min.css" rel="stylesheet">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">

{{header}}

        <form method="POST" action="">
            {% csrf_token %}
            {{form|crispy}}
            <input type="submit" value="Search"/>
        </form>

                        Employee Id
                        Employee Name
                        Salary
                        Join Date

                {% for instance in queryset %}

                    {{ instance.empid }}
                    {{ instance.empname }}
                    {{ instance.salary }}
                    {{ instance.joindate }}

                {% endfor %}

myjs.js

$(document).ready(function(){

  $(".datetimeinput").datepicker({changeYear: true,changeMonth: true, dateFormat: 'yy-mm-dd'});

});

enter image description here


问:
How to detect and print the encoding of a list of .sql files in a particular directory?
I have a list of .sql files that need to checked for their encoding before i make changes to them. They are either in utf 8 or utf 16. How can I make some changes to my code so that it enter code herereads the file and prints out on the Console what type of encoding the data in the file have?

My code now looks like below:

```<code>
string sql = "E:\\src_Vemala\\Nautilus\\Product\\dev\\Database\\Nautilus\\Scripts\\ForwardDeclaration.sql";

for (int i = 0; i < sql.Length; i++)
           {

 //reads each line
               string[] ReadText = File.ReadAllLines(sql);
               using (StreamWriter sw = new StreamWriter(sql))
               {
                   foreach (String s in ReadText)
                   {
       //carries out a particular function
                       sw.WriteLine(ReplaceView(s)); ```
```

Body:
I have a list of .sql files that need to checked for their encoding before i make changes to them. They are either in utf 8 or utf 16. How can I make some changes to my code so that it enter code herereads the file and prints out on the Console what type of encoding the data in the file have?

My code now looks like below:

string sql = "E:\\src_Vemala\\Nautilus\\Product\\dev\\Database\\Nautilus\\Scripts\\ForwardDeclaration.sql";

for (int i = 0; i < sql.Length; i++)
           {

 //reads each line
               string[] ReadText = File.ReadAllLines(sql);
               using (StreamWriter sw = new StreamWriter(sql))
               {
                   foreach (String s in ReadText)
                   {
       //carries out a particular function
                       sw.WriteLine(ReplaceView(s)); ```


问:
Making spaces between emojis in string [working with emot]
```<code>from emot.emo_unicode import UNICODE_EMOJI

tweet = "@homer #yolo good hellobye evening :-) and :) you should've"

def add_spaces(tweet):
    words = tweet.split()
    print(words)
    for i, w in enumerate(words):
        for emot in UNICODE_EMOJI:
            if w == emot:
                words[i] = " " + w + " "
    new_tweet = " ".join(words)
    print(new_tweet)

result = add_spaces(tweet)

print(result)
</code>```

With the function above i try to make spaces, but only between the emojis and the word before und behind. So the output should be:
@homer #yolo good hello   bye evening :-) and :) you should've

when i run this function i get the following output:
for new_tweet = @homer #yolo good hellobye evening :-) and :) you should've
for result = None

you see the new_tweet is the same as tweet. I hope somebody can tell me where i made a mistake.

fyi: i also tried it with this function:

```<code>def add_spaces(s):
    # split the string into a list of words, emojis, and punctuation
    words = re.findall(
        r"(?:[\w’]+[\w']+|(?:[\U0001f300-\U0001f64f])|(?:[\U0001f680-\U0001f6ff])|(?:[\.,!?:;.@#)(]))",
        s,
    )
    # loop through each word in the list
    for i, w in enumerate(words):
        # check if the word is an emoji
        if w.startswith("\\U") and not w.startwith("@"):
            # add a space before and after the emoji
            words[i] = " " + w + " "
        # check if the word is an "@" symbol
        elif w == "@":
            # do not add a space after the "@" symbol
            words[i] = w
    # join the words back together
    s = " ".join(words)
    return s
</code>```

This function works... BUT:
it also makes space between the @ and the #
So the output here is:
@ homer # yolo good hello   bye evening : ) and : ) you should've

The program recognizes the @ and the # also as some kind of emoji. Maybe it is some kind of encoding problem?!

i hope somebody can give me some nice advices to make this function work. ty :)

Body:
from emot.emo_unicode import UNICODE_EMOJI

tweet = "@homer #yolo good hellobye evening :-) and :) you should've"

def add_spaces(tweet):
    words = tweet.split()
    print(words)
    for i, w in enumerate(words):
        for emot in UNICODE_EMOJI:
            if w == emot:
                words[i] = " " + w + " "
    new_tweet = " ".join(words)
    print(new_tweet)

result = add_spaces(tweet)

print(result)

With the function above i try to make spaces, but only between the emojis and the word before und behind. So the output should be:
@homer #yolo good hello   bye evening :-) and :) you should've

when i run this function i get the following output:
for new_tweet = @homer #yolo good hellobye evening :-) and :) you should've
for result = None

you see the new_tweet is the same as tweet. I hope somebody can tell me where i made a mistake.

fyi: i also tried it with this function:

def add_spaces(s):
    # split the string into a list of words, emojis, and punctuation
    words = re.findall(
        r"(?:[\w’]+[\w']+|(?:[\U0001f300-\U0001f64f])|(?:[\U0001f680-\U0001f6ff])|(?:[\.,!?:;.@#)(]))",
        s,
    )
    # loop through each word in the list
    for i, w in enumerate(words):
        # check if the word is an emoji
        if w.startswith("\\U") and not w.startwith("@"):
            # add a space before and after the emoji
            words[i] = " " + w + " "
        # check if the word is an "@" symbol
        elif w == "@":
            # do not add a space after the "@" symbol
            words[i] = w
    # join the words back together
    s = " ".join(words)
    return s

This function works... BUT:
it also makes space between the @ and the #
So the output here is:
@ homer # yolo good hello   bye evening : ) and : ) you should've

The program recognizes the @ and the # also as some kind of emoji. Maybe it is some kind of encoding problem?!

i hope somebody can give me some nice advices to make this function work. ty :)


问:
Uploading file to Sharepoint is failing with "HTTPError: 400 Client Error: Bad Request for url: " in python
I am trying to upload a file into Sharepoint but the code fails with the below error code.

office365.runtime.client_request_exception.ClientRequestException: ('-2147024809, System.ArgumentException', 'Server relative urls must start with SPWeb.ServerRelativeUrl', "400 Client Error: Bad Request for url: https://<company_name>.sharepoint.com/sites/<site_folder>/_api/Web/getFolderByServerRelativeUrl('Shared%20Documents%2FGeneral%2F3.%20PAYMENTS%20Operations%2FTIES%2FCRS%20Report%20files')/Files/add(overwrite=true,url='%2Ftmp%2Ftmp1lsc2asr%2FXML_REPORT_df185e51-2df0-48be-ad7f-cf8a3ae31914.xml')")

I am trying to upload a file in sharepoint with the below folder structure.

Shared Documents > General > 3. PYAMENTS Operations > TIES > CRS Report files

I have written the below code snippet to upload a file into sharepoint. Please let me know where I am going wrong.

```<code>    full_url = f'https://<company_name>.sharepoint.com/sites/<site_folder>/'
    relative_url = f'Shared Documents/General/3.PAYMENTS Operations/TIES/CRS Report files'
    ctx = get_sharepoint_context_using_user()

    print(ctx)

    target_folder = ctx.web.get_folder_by_server_relative_url(relative_url)

    print(target_folder)

    # Open file in binary mode
    with open(temp_file, 'rb') as content_file:
        file_content = content_file.read()
        #print(file_content)
        target_folder.upload_file(temp_file, file_content).execute_query()
</code>```

Body:
I am trying to upload a file into Sharepoint but the code fails with the below error code.

office365.runtime.client_request_exception.ClientRequestException: ('-2147024809, System.ArgumentException', 'Server relative urls must start with SPWeb.ServerRelativeUrl', "400 Client Error: Bad Request for url: https://<company_name>.sharepoint.com/sites/<site_folder>/_api/Web/getFolderByServerRelativeUrl('Shared%20Documents%2FGeneral%2F3.%20PAYMENTS%20Operations%2FTIES%2FCRS%20Report%20files')/Files/add(overwrite=true,url='%2Ftmp%2Ftmp1lsc2asr%2FXML_REPORT_df185e51-2df0-48be-ad7f-cf8a3ae31914.xml')")

I am trying to upload a file in sharepoint with the below folder structure.

Shared Documents > General > 3. PYAMENTS Operations > TIES > CRS Report files

I have written the below code snippet to upload a file into sharepoint. Please let me know where I am going wrong.

    full_url = f'https://<company_name>.sharepoint.com/sites/<site_folder>/'
    relative_url = f'Shared Documents/General/3.PAYMENTS Operations/TIES/CRS Report files'
    ctx = get_sharepoint_context_using_user()

    print(ctx)

    target_folder = ctx.web.get_folder_by_server_relative_url(relative_url)

    print(target_folder)

    # Open file in binary mode
    with open(temp_file, 'rb') as content_file:
        file_content = content_file.read()
        #print(file_content)
        target_folder.upload_file(temp_file, file_content).execute_query()


问:
How to create a 3D button in PyQt5
It is possible to design a button that it is looking like a 3D object (example below) in PyQt5?

I have looked all around the web, but couldn't find anything.

Title: How to create a 3D button in PyQt5


问:
SSLError(1, u'Received fatal alert: protocol_version') error in shown in jython 2.7.3
I am trying to fetch the text from a https url and using urllib2. I have added all the truststore related to support TLSv1.2.

I was using jython 2.5.1 earlier and upgrading to  jython 2.7.3

the code is :

```<code>trust_managers = array([TrustAllX509TrustManager()], TrustManager)
    TRUST_ALL_CONTEXT = SSLContext.getInstance("TLSv1.2")
    TRUST_ALL_CONTEXT.init(None, trust_managers, None)
    SSLContext.setDefault(TRUST_ALL_CONTEXT)
u = urllib2.urlopen('https://<URL>);

str1 = u.read();
</code>```

This is working in Jython 2.5.1, but not working in 2.7.3. its giving the error:

SSLError(1, u'Received fatal alert: protocol_version')

Is there any other way to achieve this? I know requests is an alternative, but I am not supposed to install new packages in the env.?

Body:
I am trying to fetch the text from a https url and using urllib2. I have added all the truststore related to support TLSv1.2.

I was using jython 2.5.1 earlier and upgrading to  jython 2.7.3

the code is :

trust_managers = array([TrustAllX509TrustManager()], TrustManager)
    TRUST_ALL_CONTEXT = SSLContext.getInstance("TLSv1.2")
    TRUST_ALL_CONTEXT.init(None, trust_managers, None)
    SSLContext.setDefault(TRUST_ALL_CONTEXT)
u = urllib2.urlopen('https://<URL>);

str1 = u.read();

This is working in Jython 2.5.1, but not working in 2.7.3. its giving the error:

SSLError(1, u'Received fatal alert: protocol_version')

Is there any other way to achieve this? I know requests is an alternative, but I am not supposed to install new packages in the env.?


问:
Debugging Doctrine huge memory consumption
getting out of memory with doctrine within Symfony, but it's just like 20 rows with pagination.. How do I start debugging this?