text:
Q: MVC DataAnnotation RequiredIfNot I would need help to ensure CustomerCode has value only if UserTypeID is not 1
    public class FilteringViewModel
    {
        [Required]
        public int? UserID { get; set; }

        [Required]
        public string UserTypeID { get; set; }

        [RequiredIf("UserTypeID", "1")]
        public string EmployeeCode { get; set; }

        [RequiredIf("UserTypeID", "!1")]
        public string CustomerCode { get; set; }
    }

    public class RequiredIfAttribute : ValidationAttribute
    {
        RequiredAttribute _innerAttribute = new RequiredAttribute();
        public string _dependentProperty { get; set; }
        public object _targetValue { get; set; }

        public RequiredIfAttribute(string dependentProperty, object targetValue)
        {
            this._dependentProperty = dependentProperty;
            this._targetValue = targetValue;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var field = validationContext.ObjectType.GetProperty(_dependentProperty);
            if (field != null)
            {
                var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
                if ((dependentValue == null && _targetValue == null) || (dependentValue.Equals(_targetValue)))
                {
                    if (!_innerAttribute.IsValid(value))
                    {
                        string name = validationContext.DisplayName;
                        string specificErrorMessage = ErrorMessage;
                        if (string.IsNullOrEmpty(specificErrorMessage))
                            specificErrorMessage = $"{name} is required.";

                        return new ValidationResult(specificErrorMessage, new[] { validationContext.MemberName });
                    }
                }
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(FormatErrorMessage(_dependentProperty));
            }
        }
    }

*

*EmployeeCode is required if UserTypeID is 1 (this part is working fine)

*CustomerCode is required if UserTypeID is not 1 (this part is not working)

A: As per explain by Yong Shun, the logic does not affected by "!". I have change the IsValid() function as per below and now its working:

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var field = validationContext.ObjectType.GetProperty(_dependentProperty);
            if (field != null)
            {
                var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
                if (
                    (dependentValue == null && _targetValue == null)
                     || (!_targetValue.ToString().StartsWith("!") && dependentValue.Equals(_targetValue))
                     || (_targetValue.ToString().StartsWith("!") && !dependentValue.Equals(_targetValue.ToString().Substring(1)))
                     )
                {
                    //this statement means that we will proceed to do the validation
                    if (!_innerAttribute.IsValid(value))
                    {
                        string name = validationContext.DisplayName;
                        string specificErrorMessage = ErrorMessage;
                        if (string.IsNullOrEmpty(specificErrorMessage))
                            specificErrorMessage = $"{name} is required.";

                        return new ValidationResult(specificErrorMessage, new[] { validationContext.MemberName });
                    }
                }
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(FormatErrorMessage(_dependentProperty));
            }
        }


text:
Q: Compare pairs of binomial populations I have data from smokers people in different countries and through different years. $X_i$ can be viewed as a Bernoulli R.V. where $X_i=1$ if the person smokes and 0 when it does not.
The smokers in a country are then $Y= \sum_i^N{X_i}$, where N is the people living in the country. And this $Y$ follows a Binomial$(N,\mu)$.
So my data is like follows. For example USA in 2013 has 50 smokers out of 120 people and 65 out of 130 in 2014. I have similar data for the rest of countries.
The real smoking rate of a determined country is the probability of a smoker there due to advertisement campaigns, so higher number of smokers in a country may indicate a strong advertisement there.
How can I know if the true smokers global rate has increased from one year to another?
I think I have to compare the Binomials from one year to another with a t-test where the null hypothesis is that $\mu_{2013} = \mu_{2014}$ and the alternative hypothesis $\mu_{2013} < \mu_{2014}$. Once this is done for all countries, if the alternative hypothesis was accepted in majority of cases can I say that the rate has increased?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add single selection radio button on grid in gxt In my application I have a grid which contains some rows.
In each row I want to put a radio button, and only one radio button can be selected in the grid (each row has one radio button).
To do this, I tried to add a GridCellRenderer and return a radio button using the following code :
GridCellRenderer<ModelData> button = new GridCellRenderer<ModelData>() {
    @Override
    public Object render(ModelData model, String property,
            ColumnData config, final int rowIndex, int colIndex,
            ListStore<MonitorModel> store, Grid<MonitorModel> grid) {
        // TODO Auto-generated method stub
        final RadioGroup radioGroup = new RadioGroup();

        for(int i=0; i<store.getCount(); i++){
            radio = new Radio();
            radio.setBoxLabel("radio"+rowIndex);

            if(radio.getBoxLabel().equals("radio0")&& radio.getValue()== false){
                radio.setValue(true);
                //isFirstTime = true;
            }
            radioGroup.addListener(Events.Change, new Listener<FieldEvent>() {
                public void handleEvent(FieldEvent fe) {
                    if (((Boolean)fe.getValue()) == true) {
                        radio.setValue(true);
                    }
                }
            });

        }
        radioGroup.add(radio);
        return radioGroup;
    }
};

When I load my grid, the result is correct.
But the problem I encounter is that when I click on a radio button, all the other radio buttons stay checked if they were already checked. How can I make that, when I click on a button, the others buttons are deselected ?
Thanks.

A: You should define the
final RadioGroup radioGroup = new RadioGroup();

As a class field, but not in the "render" method. Something like this:
GridCellRenderer<ModelData> button = new GridCellRenderer<ModelData>() {

    final RadioGroup radioGroup = new RadioGroup();

    @Override
    public Object render(ModelData model, String property,
            ColumnData config, final int rowIndex, int colIndex,
            ListStore<MonitorModel> store, Grid<MonitorModel> grid) {

        for(int i=0; i<store.getCount(); i++){
            radio = new Radio();
            radio.setBoxLabel("radio"+rowIndex);
    ......

Hope helpfull...

A: I got the answer, I have used following..
GridCellRenderer<ModelClass> button = new GridCellRenderer<ModelClass>() {
        @Override
        public Object render(final ModelClass model, String property,
                ColumnData config, final int rowIndex, int colIndex,
                final ListStore<ModelClass> store, Grid<ModelClass> grid) {
            Radio radio = new Radio();
            for(int i=0; i< store.getCount(); i++){
                radio = new Radio();
                radio.setName("Radio"+ i);
                radio.setHeight(16);

                if (model.get("checked").equals(Boolean.TRUE)) {
                    radio.setValue(true);
                }
                else {
                    radio.setValue(false);
                }
            }
            radio.addListener(Events.OnClick, new Listener<FieldEvent>() {
                @Override
                public void handleEvent(FieldEvent be) {
                    // TODO Auto-generated method stub
                    // Something....
                }
            });
            return radio;
        }

    };

it works..


text:
Q: Bulk insert into SQL Server from VMWare guest using distributed switch This is mostly likely not a SQL server issue but the setup seems to only be affecting BULK INSERTS to SQL Servers.
We have recently moved VM Hardware and all the guests that were moved had their virtual switches changed from standard to distributed.
I then started receiving

A fatal error occurred while reading the input stream from the
  network. The session will be terminated (input error: 64, output
  error: 0)

on a two SQL servers during BULK INSERT operations. One of the SQL servers was a VM with the new configuration and the other was a physical server. Both BULK INSERT operation originated from a VM with the new configuration. The BULK INSERTs would not fail every time, it was very random when it would.
When we changed the virtual switch to be a standard switch instead of a distributed switch the issue goes away.
I am looking for more of an explanation to why it doesn't work with a distributed switch instead of a resolution. My guess would be that the BULK INSERT operation is serial and with a distributed switch the packets are being routed through different hosts, some of which may be busier than others, and are arriving at the destination server beyond some latency threshold. (note: there is nothing in the windows event log at the times of the errors on either the source or destination server)
UPDATE: turns out the issue was due to the NIC. All of our VMs were configured with an E1000 NIC which functioned well enough on standard switches. Once we moved to distributed switches, we started seeing issues with large data transfers, not just sql queries. Changing the NIC to VMXNET3 seems to have resolved the issue.

A: I would suggest using Wireshark or Microsoft NetMon and sniffing the traffic to see what is happening here.  Could also be related to the TCP Chimney Offload feature, assuming something has changed at the NIC level:
http://support.microsoft.com/kb/942861

A: Pure vmware/networking issue, it appears.
I suggest trying to find a connectivity problem from the clients to the server that is not SQL (ping, or anything). That will help you surface a clearer troubleshooting path.

A: we have experienced this error  a week ago. our network team, security team and database team search every thing. At the end of the researching we have detected the error resource.
It is the IPS device. Ask your security team is there any signature on IPS device.


text:
Q: How to return the error validator laravel in string format In this example code:
 public function test(Request $request) {
    $rule = [
        'name' => 'required'
    ];
    $validator = Validator::make($request->all(), $rule);
    if ($validator->fails()) {
        return $validator->errors(); // <-- String format, not array
    }
    return $request->name;
}

I need that the error be a simple string.
Thanks

A: Do something like this:
return $validator->errors()->first('name');


text:
Q: Extract test python-selenium How can I extract numeric digits in Element HTLMthe text to copy it (CTRL + C) which changes every time, when the script is closed and reopened?
  5023ABCDEFSGILMOPW  `
In this example the number to extract is:  "5023"

A: Try this:
import re
import pyperclip

strrr = '5023ABCDEFSGILMOPW'

value = re.search('^\d+', strrr)[0]

pyperclip.copy(value)

for pyperclip working, it should be installed with pip:
pip install pyperclip

or get more code description, where we can extract more info to help out


text:
Q: How are the bonuses calculated? When you bought/created enough particles of a certain species, a bonus is unlocked. Each has a tooltip with something like:

Effect: +1% APS

Is this effect for the overall APS, or just for that one specific species?

A: Each bonus is for that specific particle/specie. I didn't look good enough. In the following screenshot it is clear that there is a difference between the quantum foam and neutrino's, what is exactly coming from the differences in the bonuses.


text:
Q: Sending Email using PHP, not being received by Gmail? I am trying to send an email using PHP from a free hosting account on Hostinger (hostinger.co.uk).
Here is my code:
<?php
if(isset($_POST['submit'])){

$to      = 'xxxxxxxxx@gmail.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: customer@novel.com' . "\r\n" .
    'Reply-To: customer@novel.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

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

    }
?>

For some reason when i send the email, it doesn't come through to my gmail account. It's not even in spam.
I reckon this has something to do with the headers and more specifically my from address - since if i change the from email address to the below, then i receive the email.
$headers = 'From: blux@g.com' . "\r\n" .
    'Reply-To: blux@g.com' . "\r\n" .

Please can someone show me / tell me what i am doing wrong here and why gmail doesn't like the other from address?
Thanks in advance

A: Gmail checks if sender is authorized to send mail or not for security reasons. Due to that if you use any email id whose owner has enabled SPF and DKIM it will reject mail. So try using your server name after @ in your from address.
You can set reply-to address to any address you like.


text:
Q: An existence result for solutions of elliptic equations with a mixed boundary problem Assume that $\Omega$  is a bounded domain such that
$\partial\Omega=\Gamma_1\cup \Gamma_2$, where $\Gamma_1$ and $\Gamma_2$ are disjoint and closed. Let us consider the following elliptic equations.
$$
\left\{\begin{array}{l}
\nabla\cdot (\gamma(x) \nabla u(x))=0,\quad x\in\Omega,\\
-\gamma(x) \frac{\partial u(x)}{\partial n}=k u(x),\quad x\in\Gamma_1, \\
\gamma(x)\frac{\partial u(x)}{\partial n}=q, \quad x\in\Gamma_2
\end{array}\right.
$$
There are two questions that I have about this problem:
(1) If $q\in L^2(\partial\Gamma_2)$, then can we get weak solution $u$ in $H^{3/2}(\Omega)$. From Theorem 7.3 in the book "Non-Homogeneous Boundary Value Problems and Applications" it seems that the solution exists if $\Omega$ is smooth.  The argument is just too long, because it focus on general elliptic equations of order $2m$
$$
\left\{\begin{array}{l}
Au=f\\
B_ju=g \quad 0\leq j\leq m-1
\end{array}\right.
$$
and say that the map $u\to \{Au, B_0u, B_1u,\cdots, B_{m-1}u\}$ is onto from
$H^{s}$ to $H^{s-2}(\Omega)\times H^{s-1/2-m_0}(\partial\Omega)\times  H^{s-1/2-m_1}(\partial\Omega)\cdots  H^{s-1/2-m_{m-1}}(\partial\Omega)$.
Is there any other books or material on this result? I means the ones with short proof or you think are better written.
(2) On the other hand, I know the following result, which only requrie $\Omega$ to be Lipschitz, and the boudnary data is only $L^2$.

Does similar result apply the elliptic equation above.


text:
Q: Pandas remove duplicates within the list of values and identifying id's that share the same values I have a pandas dataframe :
I used to have duplicate test_no ; so I remove the duplicates by
df['test_no'] = df['test_no'].apply(lambda x: ','.join(set(x.split(','))))

but still as you can see the duplicates are still there ; I think it's due to extra spaces and I want to clean it
Part 1:
     my_id              test_no
0   10000000000055910   461511, 461511
1   10000000000064510   528422
2   10000000000064222   528422,528422 , 528421
3   10000000000161538   433091.0, 433091.0
4   10000000000231708   nan,nan

Expected Output
     my_id              test_no
0   10000000000055910   461511
1   10000000000064510   528422
2   10000000000064222   528422, 528421
3   10000000000161538   433091.0
4   10000000000231708   nan

Part 2:
I  also want to check if any of the "my_id" share any of the test_no ;
for example :
my_id               matched_myid
10000000000064222  10000000000064510

A: You can use a regex to split:
import re

df['test_no'] = df['test_no'].apply(lambda x: ','.join(set(re.split(',\s*', x))))

# or
df['test_no'] = [','.join(set(re.split(',\s*', x))) for x in df['test_no']]

If you want to keep the original order use dict.fromkeys in place of set.
If the duplicates are successive you can also use:
df['test_no'] = df['test_no'].str.replace(r'([^,\s]+),\s*\1', r'\1', regex=True)


text:
Q: How to convert a html table to pdf? I want to generate this table into a pdf file. but it only shows one column.
In a row (
) I used 2 columns ( 	  	).
But it does not show the second column.
This is the table.

          Student Details

           <h:outputText value="Student Name"/>
           <h:outputText value="#{collect.s_name}" />

This is the script


text:
Q: Is my Mac Mini's fan okay? I replaced the HDD with a hybrid HDD/SSD about a week ago, following iFixit's guide for doing so. However, when putting it back together, I stripped one of the connectors on the fan.
My Mini gets really hot, so it makes me think the fan isn't working all the way, if at all. At the same time, my office doesn't have insulation (and it's on the second floor of my apartment) so it gets really hot. I have a fan on now, facing me and the Mini and it feels better, just a bit warm.
I just want to know if I am stressing too much, or if there is reason for concern.

A: Depending on the model year of the Mac mini, you could run Apples hardware diagnostics if supported.
Shutdown your Mac mini.  Turn back on and press and hold the keys: option + D during the grey screen before the Apple logo.
If asked join a network and let it boot into the Apple hardware test.  This will tell you if the fan is reporting an error along with other hardware tests.

A: If it were me I'd probably just replace the fan, it's typically relatively cheap and the first thing to come out of most (maybe even all) Mac Minis.


text:
Q: Is it possible to read a csv file in Vega with a custom delimiter, such as ;? I have a csv file that has a custom delimiter, such as ;.  I would like to load it into Vega a la:
"data": { "url": "https://url.csv",
          "format":{"type":"csv",
          "sep":";"
        }

Here of course the last line does not exist in the current Vega schema.
This is akin to pandas pd.read_csv(sep=';')

A: Something like this should work:
"data": { "url": "https://url.csv",
          "format":{"type":"dsv", "delimiter":";"}
        }

See https://vega.github.io/vega-lite/docs/data.html#dsv for more information.


text:
Q: Center UIImage Horizontally Constraint in UIView Not Working? So I have been using the new Xcode 6.2 Auto Layout Preview and other features to get my app ready for all screen sizes. I am trying to constrain a UIImage to look  equally the same in every screen type. I have set up the constraints, and I am looking for it look the same, although it is not. Below are the screenshots of the constraints, storyboard view, and then the final compiled product. As you can see the image is not centered.
Constraints:

Here is the compiled version, obviously off.

Any help is greatly appreciated. Thanks in advance.

A: It is possible to meet all your constraints and have a very large width for the imageView.  It has to align to a specific top and bottom edge, and then resize to width to meet the aspect ratio constraint.  It seems like the width it determines is larger than the width of the screen.  Basically, your image is in landscape, while the device is in portrait.
You could remove the bottom constraint, and add a constraint for the left and right edge.  This would make the imageView a specific width and a flexible height.


text:
Q: Unknown member 'Header' on element 'ComboBox' The below line of code is throwing such an error.
<ComboBox Header="Please Select Type" ItemsSource="{Binding Types}"/>

I didn't find more information regarding ComboBox's Header property. Does any one know what's the use of it?

A: Header property is available for Windows 8.1/VS2013 only, so it will throw error if any one tries to use in Windows 8/VS2012

A: The property is there and works fine for me. It's also there for input controls like TextBox or PasswordBox. Perhaps you are trying it out in a Windows 8.0 project.
Oh and it provides a header you can associate with your control, so it shows up in the recommended, localization-safe position (above the control) and saves you from defining a TextBlock label for each input control. Possibly to make it easier to create forms-like UIs (disclaimer - I don't really know).


text:
Q: Initialising mock objects - Mockito There are many ways to initialize a mock object using MockIto.
What is best way among these ?
1.
 public class SampleBaseTestCase {

   @Before public void initMocks() {
       MockitoAnnotations.initMocks(this);
   }

*

@RunWith(MockitoJUnitRunner.class)

*

mock(XXX.class);

suggest me if there are any other ways better than these...

A: In te lastest version of Mockito the method MockitoAnnotations.initMocks is deprecated
Preferred way is use

*

*MockitoJUnitRunner or MockitoRule for JUnit4

*MockitoExtension for JUnit5

*MockitoTestNGListener for TestNG
If you can not use dedicated runner/extension you can use MockitoSession

A: There is now (as of v1.10.7) a fourth way to instantiate mocks, which is using a JUnit4 rule called MockitoRule.
@RunWith(JUnit4.class)   // or a different runner of your choice
public class YourTest
  @Rule public MockitoRule rule = MockitoJUnit.rule();
  @Mock public YourMock yourMock;

  @Test public void yourTestMethod() { /* ... */ }
}

JUnit looks for subclasses of TestRule annotated with @Rule, and uses them to wrap the test Statements that the Runner provides. The upshot of this is that you can extract @Before methods, @After methods, and even try...catch wrappers into rules. You can even interact with these from within your test, the way that ExpectedException does.
MockitoRule behaves almost exactly like MockitoJUnitRunner, except that you can use any other runner, such as Parameterized (which allows your test constructors to take arguments so your tests can be run multiple times), or Robolectric's test runner (so its classloader can provide Java replacements for Android native classes). This makes it strictly more flexible to use in recent JUnit and Mockito versions.
In summary:

*

*Mockito.mock(): Direct invocation with no annotation support or usage validation.

*MockitoAnnotations.initMocks(this): Annotation support, no usage validation.

*MockitoJUnitRunner: Annotation support and usage validation, but you must use that runner.

*MockitoRule: Annotation support and usage validation with any JUnit runner.

See also: How JUnit @Rule works?

A: The other answers are great and contain more detail if you want/need them.
In addition to those, I would like to add a TL;DR:

*

*Prefer to use

*

*@RunWith(MockitoJUnitRunner.class)

*If you cannot (because you already use a different runner), prefer to use

*

*@Rule public MockitoRule rule = MockitoJUnit.rule();

*Similar to (2), but you should not use this anymore:

*

*@Before public void initMocks() {
    MockitoAnnotations.initMocks(this);
}

*If you want to use a mock in just one of the tests and don't want to expose it to other tests in the same test class, use

*

*X x = mock(X.class)
(1) and (2) and (3) are mutually exclusive.
(4) can be used in combination with the others.

A: 1. Using MockitoAnnotations.openMocks():
The MockitoAnnotations.initMock() method in Mockito 2 is deprecated and replaced with MockitoAnnotations.openMocks() in Mockito 3. The MockitoAnnotations.openMocks() method returns an instance of AutoClosable which can be used to close the resource after the test. Below is an example using MockitoAnnotations.openMocks().
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

class MyTestClass {

    AutoCloseable openMocks;

    @BeforeEach
    void setUp() {
        openMocks = MockitoAnnotations.openMocks(this);
        // my setup code...
    }

    @Test
    void myTest() {
        // my test code...

    }

    @AfterEach
    void tearDown() throws Exception {
        // my tear down code...
        openMocks.close();
    }

}

2. Using @ExtendWith(MockitoExtension.class):
As of JUnit5 @RunWith has been removed. Below is an example using @ExtendWith:
@ExtendWith(MockitoExtension.class)
class MyTestClass {

    @BeforeEach
    void setUp() {
        // my setup code...
    }

    @Test
    void myTest() {
        // my test code...

    }

    @AfterEach
    void tearDown() throws Exception {
        // my tear down code...
    }

}

A: For the mocks initialization, using the runner or the MockitoAnnotations.initMocks are strictly equivalent solutions. From the javadoc of the MockitoJUnitRunner :

JUnit 4.5 runner initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method.

The first solution (with the MockitoAnnotations.initMocks) could be used when you have already configured a specific runner (SpringJUnit4ClassRunner for example) on your test case.
The second solution (with the MockitoJUnitRunner) is the more classic and my favorite. The code is simpler. Using a runner provides the great advantage of automatic validation of framework usage (described by @David Wallace in this answer).
Both solutions allows to share the mocks (and spies) between the test methods. Coupled with the @InjectMocks, they allow to write unit tests very quickly. The boilerplate mocking code is reduced, the tests are easier to read. For example:
@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock(name = "database") private ArticleDatabase dbMock;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @InjectMocks private ArticleManager manager;

    @Test public void shouldDoSomething() {
        manager.initiateArticle();
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        manager.finishArticle();
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: The code is minimal
Cons: Black magic. IMO it is mainly due to the @InjectMocks annotation. With this annotation  "you loose the pain of code" (see the great comments of @Brice)

The third solution is to create your mock on each test method.
It allow as explained by @mlk in its answer to have "self contained test".
public class ArticleManagerTest {

    @Test public void shouldDoSomething() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator,
                                                    userProvider,
                                                    database);

        // when
        manager.initiateArticle();

        // then
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator,
                                                    userProvider,
                                                    database);

        // when
        manager.finishArticle();

        // then
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (BDD...)
Cons: there is more boilerplate code. (The mocks creation)

My recommandation is a compromise. Use the @Mock annotation with the @RunWith(MockitoJUnitRunner.class), but do not use the @InjectMocks :
@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock private ArticleDatabase database;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @Test public void shouldDoSomething() {
        // given
        ArticleManager manager = new ArticleManager(calculator,
                                                    userProvider,
                                                    database);

        // when
        manager.initiateArticle();

        // then
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleManager manager = new ArticleManager(calculator,
                                                    userProvider,
                                                    database);

        // when
        manager.finishArticle();

        // then
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (How my ArticleManager is instantiated). No boilerplate code.
Cons: The test is not self contained, less pain of code

A: A little example for JUnit 5 Jupiter, the "RunWith" was removed you now need to use the Extensions using the "@ExtendWith" Annotation.
@ExtendWith(MockitoExtension.class)
class FooTest {

  @InjectMocks
  ClassUnderTest test = new ClassUnderTest();

  @Spy
  SomeInject bla = new SomeInject();
}

A: MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:
XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

A: There is a neat way of doing this.

*

*If it's an Unit Test you can do this:
@RunWith(MockitoJUnitRunner.class)
public class MyUnitTest {

    @Mock
    private MyFirstMock myFirstMock;

    @Mock
    private MySecondMock mySecondMock;

    @Spy
    private MySpiedClass mySpiedClass = new MySpiedClass();

    // It's gonna inject the 2 mocks and the spied object per reflection to this object
    // The java doc of @InjectMocks explains it really well how and when it does the injection
    @InjectMocks
    private MyClassToTest myClassToTest;

    @Test
    public void testSomething() {
    }
}

*EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("aplicationContext.xml")
public class MyIntegrationTest {

    @Mock
    private MyFirstMock myFirstMock;

    @Mock
    private MySecondMock mySecondMock;

    @Spy
    private MySpiedClass mySpiedClass = new MySpiedClass();

    // It's gonna inject the 2 mocks and the spied object per reflection to this object
    // The java doc of @InjectMocks explains it really well how and when it does the injection
    @InjectMocks
    private MyClassToTest myClassToTest;

    @Before
    public void setUp() throws Exception {
          MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSomething() {
    }
}


text:
Q: UnicodeEncodeError Python? I get the following error when try to write in file:
UnicodeEncodeError('ascii', u'B\u1ea7u cua (B\u1ea7u cua 2017 )', 1, 2, 'ordinal not in range(128)'))

I try to write this text Bầu cua in file:
f = codecs.open("13.txt", "a", "utf-8")
f.write("{}\n".format(title))

Also I tried to use title.encode()
It gives me a new error:
When I use .encode(text) I get the following error: `
UnicodeDecodeError('ascii', 'B\xe1\xba\xa7u cua (B\xe1\xba\xa7u cua 2017 )\n', 1, 2, 'ordinal not in range(128)'))
`

A: As described this answer to "Writing Unicode text to a text file?", you have many solutions.
Basically, you have 2 issues:
The str.format() method must be used on an unicode object
u'{}\n'.format('Bầu cua')

The file you write to also must be opened with the right encoding:
f = open('13.txt', 'a', encoding='utf-8')

As a result, this works for Python 3:
data = 'Bầu cua'
f = open('13.txt', 'a', encoding='utf-8')
line = u'{}\n'.format(data)
f.write(line)
f.close()

A: Try with these two lines at the beginning of the file. It works well for Python2.7
#!/usr/bin/env python
# -*- coding: utf-8 -*-

data = u'Bầu cua'
f = open('test.txt', 'a')
line = u'{}\n'.format(data)
f.write(line.encode('utf8'))
f.close()


text:
Q: Is there any better way to get header and footer data from database
The image is the design of my homepage.
There will be about 100 pages for this website.
My Clients want an admin page(different domain) from where he can edit data in header and footer.
So if I fetch header and footer data from the database for every page then I think it will not be a proper way to do it and it can make the website slow.
So is there any other way to do it. Thank you.


text:
Q: How to determine the Time and Space complexity of rotate string algorithm Can anybody explain the time and space complexity for the below rotate string code snippet.
The book from which this example is taken says that
Complexity Analysis
Time Complexity: O(N^2), where N is the length of A.
Space Complexity: O(N), the space used building A+A.
But I don't understand it. Can anybody please explain?
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
public class RotateString {
public static void main(String[] args) {
    System.out.println(rotateString("abcd","dabc"));
}
 public static boolean rotateString(String a, String b) {
       return a.length()==b.length() && (a+a).contains(b);
 }

}

A: Space complexity is O(N) because you are adding two strings of length N which will create a new string of length 2*N. Any constant * N is still O(N).
Time complexity is N *N because of the time taken by contains() check. You are checking if string of length 2*N contains another string of length N. To do this using simple for loops, you will have to start checking at each of the 2*N positions and see if next N characters match the target string of length N. So number of comparisons would be 2*N times N = 2 * N ^ 2 ~= O(N^2).


text:
Q: Удаление определенного элемента массива по нажатию на кнопку Есть карточки, каждая карточка это элемент массива, в каждой карточке есть кнопка которая должна удалять этот элемент из массива, у каждой карточки есть айди заданный через html, многое перепробовал, но в итоге ничего, можете помочь?
HTML

   <button class="cart-page__item__delete"></button>
   <button class="cart-page__item__delete cart-page__item__delete_m"></button>

   <button class="cart-page__item__delete"></button>
   <button class="cart-page__item__delete cart-page__item__delete_m"></button>

JS
const cartPageItemDeleteBtn = document.querySelectorAll('.cart-page__item__delete');
cartPageItemDeleteBtn.forEach(btn => {
    const cartPageItemArr = Array.from(cartPageItem);
    btn.addEventListener('click', () => {
        const cartItem = btn.closest('.cart-page__item');
        for (let i = 0; i < cartPageItemArr.length; i++) {
            let cartId = cartItem.id;
            if(cartId === cartPageItemArr[i].id) {
                console.log(cartPageItemArr.length);
                cartPageItemArr.splice(0, 1);
                console.log(cartPageItemArr.length);
            }
        }
    });
});

A: Проблема в строчке :
cartPageItemArr.splice(0, 1);

Вы всегда удаляете первый элемент массива. А вам необходимо удалять тот элемент, который совпал по условию:
cartPageItemArr.splice(i, 1);

A: Вот тут:
const cartPageItemArr = Array.from(cartPageItem);

вы создаёте копию. И что бы вы с ней не делали, оригинал не изменится.

Основной вопрос теперь в том, что же такое cartPageItem.
Если массив, то удаление выглядит как:
const index = cartPageItem.findIndex(el => el.id === cartItem.id);
cartPageItem.splice(i, 1);

Если NodeList, то действия те же, но удаление из DOM:
const index = [...cartPageItem].findIndex(el => el.id === cartItem.id);
cartPageItem[index].parentNode.removeChild(cartPageItem[index]);

Во втором случае, так как мы знаем, где находится кнопка, можно найти контейнер от неё:
const item = btn.parentNode;
item.parentNode.removeChild(item);

Итого
Удаление из копии массива

const cartPageItem = document.querySelectorAll('.cart-page__item');
const cartPageItemDeleteBtn = document.querySelectorAll('.cart-page__item__delete');
cartPageItemDeleteBtn.forEach(btn => {
    const cartPageItemArr = Array.from(cartPageItem);
    btn.addEventListener('click', () => {
        const cartItem = btn.closest('.cart-page__item');
        let index = cartPageItemArr.indexOf(cartItem);
        console.log('before', cartPageItemArr.length, cartPageItemArr);
        cartPageItemArr.splice(index, 1);
        console.log('after', cartPageItemArr.length, cartPageItemArr);
    });
});

   <button class="cart-page__item__delete">x</button>
   <button class="cart-page__item__delete cart-page__item__delete_m">xm</button>

   <button class="cart-page__item__delete">x</button>
   <button class="cart-page__item__delete cart-page__item__delete_m">xm</button>

Удаление из DOM

const cartPageItemDeleteBtn = document.querySelectorAll('.cart-page__item__delete');
cartPageItemDeleteBtn.forEach(btn => {
    btn.addEventListener('click', () => {
        const cartItem = btn.closest('.cart-page__item');
        cartItem.parentNode.removeChild(cartItem);
    });
});

   <button class="cart-page__item__delete">x</button>
   <button class="cart-page__item__delete cart-page__item__delete_m">xm</button>

   <button class="cart-page__item__delete">x</button>
   <button class="cart-page__item__delete cart-page__item__delete_m">xm</button>


text:
Q: Making python library available to rqworker I have this module foo from which I want to import foo.jobs, the file structure is this.
foo
  | - __init__.py
  | - jobs.py
  | - ...

the problem is, I want to import it from outside of my program in a rqworker running on another folder.
I've tried adding this to my code:
import sys
sys.path.insert(0, "/path/to/foo")

and I've tried adding this to ~/.profile
export PYTHONPATH=$PYTHONPATH:/path/to/foo

Like I've seen here: https://askubuntu.com/questions/470982/how-to-add-a-python-module-to-syspath
but nothing works. Any idea on what could be happening? I'm using Ubuntu 16

A: After a lot of searching and playing with it, I discovered that you can put this in a config file so I created a file rq_config.py with the following code:
import sys
sys.path.insert(0, "/path/to/foo")

QUEUES = ['names','of','queues']

and it's working fine


text:
Q: Windows 8 app tile clock with seconds I want to develop an Windows 8 app that displays clock running with seconds in the tile. Any ideas?

A: It's not possible if your app is not running, even with the background task refresh frequency is 15 minutes.
For now this scenario is simply not supported.


text:
Q: How to safely insert code in mySQL database I'm building a website where users can store code snippets, using PHP and a mySQL database. But I can't figure out how to safely insert user inputed code into my database. I can't transform the input with the 'safety' functions I normally use (trim, stripslashes, etc.) because the whole point is that you can view the code as it's inputed in the database. I've looked at my_real_escape_string() but I saw that it does not escape the % and _, which can be used as MySQL wildcards. Does that pose a threat, or can I just use my_real_escape_string? Thanx in advance.

A: Wildcards only take effect when used in SELECT queries and then only when using certain functions. So for inserting the code it will be fine to use mysql_real_escape_string() as they will have no effect.
To make it better I would recommend that you use PHPs PDO so that you can use parameter binding. The following example is from the PHP manual:
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;
$stmt->execute();

// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

A: Using mysql_real_escape_string() provides complete protection for string values. The fact that there may be % and _ in the data is not relevant, they do not pose a security threat.
For int values, you need to either validate whether they actually are numbers, or wrap them into quotes:
$intValue = mysql_real_escape_string($_POST["intValue"]);
$query = mysql_query("INSERT INTO table SET intValue ='$intValue'");
                                                        // note the quotes

Without the quotes, mysql_real_escape_string() is useless on numeric values!
However, as @Daniel A. White already said, if you are just starting out, consider using the PDO library instead. It's newer than the old mySQL functions and offers parametrized queries that, if used properly, make SQL injection impossible.

A: Use a parameterized insert statement. Actually, use parameterized even for your selects and updates.
it will automatically handle these things for you.

A: Using PDO:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('INSERT INTO fruit(name, colour, calories) VALUES(?, ?);');
$sth->execute(Array($calories, $colour));

A: This is what worked for me, [adscript] is a code snippet.
<textarea rows="6" cols="80"><input name="adscript" type="text/javascript" class="text-input textarea" id="adscript"  value="<?php echo htmlentities($row['adscript']);?>" size="80" height="40" maxlength="1000"></textarea>


text:
Q: getaddrinfo() thread failed to start while building docker image This is my Dockerfile
FROM linuxserver/code-server:latest

RUN curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash - &&\
    apt-get install -y nodejs

I run the build command
docker build -t node-ide .

On the local computer (Windows 11) and it works fine.
But when I upload it to ubuntu server and run the same, I get an error
Sending build context to Docker daemon  2.048kB
Step 1/2 : FROM linuxserver/code-server:latest
 ---> 997b7b90cb65
Step 2/2 : RUN curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash - &&    apt-get install -y nodejs
 ---> Running in d0ec2365c9d1
curl: (6) getaddrinfo() thread failed to start
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package nodejs
The command '/bin/sh -c curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash - &&    apt-get install -y nodejs' returned a non-zero code: 100

Why is this happening?

A: It's seems a network issue, you can use 'ping deb.nodesource.com' command to test it.

A: As per the comment of @yong, I downgraded, now it works like this:
FROM linuxserver/code-server:4.4.0-ls125
RUN curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash - &&\
    sudo apt-get install -y nodejs

A: Me helped option --security-opt seccomp=unconfined for docker run
sudo docker run -it --security-opt seccomp=unconfined ubuntu

For docker-compose.yml
services:
  example:
    build: .
    security_opt:
      - seccomp:unconfined


text:
Q: Reduce file size of imported graphics and their fonts I am looking to reduce the file size of the final version of my thesis as much as possible without real hassle and any loss of quality. At the moment it is around 7 MB. I read much about it (pdfsizeopt, gs, PGF/TikZ, \pdfcompresslevel) but still feel like you can give helpful advice.
One main issue is the Libertinus font set, which adds up to 3 MB, and how to avoid this. Consequently I am looking for a way to embed my graphics without accumulating redundant font data.
Preconditions:

*

*Loss in quality is generally no option for me since I am a
perfectionist ;-)

*Windows, TeXLive, pdflatex, KOMA Script, matplotlib, Libertinus
font set. I own Adobe CS4 with Acrobat 9.0, PS, AI, ID, Affinity Suite
and am experienced in (vector) graphics.

Relevant LaTeX packages:
\usepackage{siunitx}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage[firstpage=true]{background} + setup
\usepackage{textgreek}
\usepackage[osf]{libertinus}
\usepackage{libertinust1math}
\usepackage[activate={true,nocompatibility},final,tracking=true,kerning=true,spacing=true,factor=1100,stretch=10,shrink=10]{microtype}
\usepackage[colorlinks=false, pdfborder={0 0 0}, unicode]{hyperref}

I import:

*

*A background with many vector circles for my title pages

*A Python generated .svg file, converted to .pdf for simplicity (not using .svg import in LaTeX; .svg is 600kB, .pdf 300kB.)
I think I could shrink the effective file size by using less of the pattern and substitute the rest with transformed variants (like rotated or flipped); but that would require much work in LaTeX. Perhaps I could try to make a .pdf which can "deduplicate" that?

*University's logo (PDF), text is already paths, 300kB. I could just manipulate the curves to be simpler, but that also would touch copyright, I think.

*Two photos with some marks (vector). Done in Affinity Photo, exported as .pdf to keep vector marks. Photo data is compressed with JPG at export. Perhaps e.g. Adobe software could use JPG2000 algorithm to squeeze the last bits out of it? They are around 800kB now, perhaps I can reduce quality a bit more

*A diagram, made with LucidChart. 32kB and strange.

*Libertinus Sans` without special characters. Font file size (300 bits!) and AI say, that the text is also paths. Acrobat can copy the text, so I think there is a meta-overlay like in OCR documents. The embedded font and font shown when editing with Acrobat is Helvetica. SVG export has also text as paths. But ok, 32kB should not inflate my final PDF so much.

*Two drawings made with Affinity Designer. 80kB, 62 kB from fonts: embedded subgroups of Libertinus Sans and Lato (Type 1) + Arial MT from embedded element (TrueType CID, Identity-H).

*A figure made with some AngularJS package.HTML +CSS with JS, that generates a SVG element. When copying the SVG code from Chrome Inspector, I get errors in any other graphic software, even if handling CSS correctly. So I use print to PDF from Chrome and to some tweaks this Affinity Publisher then. File is 120kB with 100kB from Libertinus Sans (regular and italic)

*Dozens of plots from matplotlib. I use text.usetex: True and a subset of my preamble to get my Libertinus look. Export as PDF, pdf.compress 9, font type 42 (as this shall make less trouble with later editing; but I will not need this I think). Each is around 1.6MB with 98% from fonts since Libertinus Sans and LibertinusT1Math are fully embedded. Using Acrobat optimizer, I get 1MB total (fonts subset, T1, for Sans additionally CID + Identity-H) but it breaks any whitespaces. And pdflatex does it job since the size does not accumulate obviously and there is just one fontset in Acrobat for each style.

One option is to use PGF/TikZ to get the plots into pdflatex with minor overhead. For my final version this is of course an option, for every day use I would prefer PDFs since I can quickly view and share them. xpdf export for PS does not work on Windows for me (running this on Linux is possible if it is worth it). But PS anyway seems to be odd if using pdflatex.
When finished, I definitely will try pdfsizeopt, gs and optimize in Acrobat. But some options break hyperlinks and bookmarks.
tl;dr
Do you prefer PDF or SVG (and if possible PGF/TikZ) to get a small output PDF if handling large fontsets?
What I already read:
How to make the PDFs produced by pdfLaTeX smaller?
How to create small PDF files for the Internet
Reduce pdf file size for large image produced by pgfplots
How do I make smaller pdf file sizes with pdflatex? (Or, how do I make pdflatex use CFF fonts?)
moderncv - filesize of pdf too big


text:
Q: Is there any difference between $.trim and trim? I have this simple example below which uses trim. As per the title of the question, is there any difference between them?. As you can see below they have the same output. If the answer is "No", which one is much better to use?
Currently I use .trim() because it's my first time seeing $.trim().

var SampleTrim = '     TRIM         ';

console.log(SampleTrim.trim());
console.log($.trim(SampleTrim));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: String.prototype.trim is not available below IE9, otherwise they are the same.
The recommended String.prototype.trim polyfill on MDN is exactly the same as that used in jQuery source.
In most cases, the native implementation would be faster to use. This JSPerf by Sumit Gulati suggests that too.
Realistically, the difference in performance would be quite negligible and I wouldn't base my decision on performance. However, it would be better to use the native implementation so that there's no dependency on jQuery. The large websites have dropped support for IE8 and I think it's safe to follow suit (:

A: jQuery's trim() function was available long before JavaScript's native trim() function was added, which is available in browsers above IE9 and the like.
Use the native trim function for future projects.

A: As I know, SimpleTrim.trim() is a native way to trim a string that modern brower support.
And $.trim(SimpleTrim) is another way that jQuery help user in the past to trim string, when browser does not support native trim.


text:
Q: camel file component how to send entire folder I have the following folder hierarchy :

*

*D

*

*D1

*

*D1doc1.txt

*D1doc2.otherext

*Readme.txt

*D2

*

*D2doc1.txt

*othertext.txt

Using Camel file component, I would like to send the repertory D1 and its content to another endpoint. So far I manage to send file independently or a whole content of a repertory, but I don't know how to send with the prvious structure the repertory D1 and its content (not just the content)
To send all the content of D1, i am writing :
from("file://D/D1/?noop=true&recursive=true").to(.....)

and it sends everything inside D1 correctly. Now to send D1 as a full directory with the contents, I tried :
from("file://D/?fileName=D1&noop=true&recursive=true").to(.....)

of course not working as camel file is apparently designed to work for file only and not directories like I saw on this link :
http://grokbase.com/t/camel/users/1485bjq5zr/polling-a-directory-for-inner-directories
However, it looks annoying and strange to me as I have to make a hack changing the previous hierarchy into :

*

*D

*

*D1

*

*D1

*

*D1doc1.txt

*D1doc2.otherext

*Readme.txt

*D2

*

*D2

*

*D2doc1.txt

*othertext.txt

so that when I use :
from("file://D/D1/?noop=true&recursive=true").to(.....)

it finally does what I want sending the directory as well.
Is there really not a cleaner way to do this ? If no, what is the reason behind ?

A: Use recursive to tell Camel to travel down sub directories. And you can use the min/max depth options to control from and how far you go down.
This is the clean solution using the correct options for what they are intended.
For example on unix the find command also has minx/max depth options and its the similar concept in the Camel file component.
More details at: http://camel.apache.org/file2
And if you do not want to build the directory structured on the 'other side' you can use the flattern option.

A: It's a kinda old thread but I'm sure it will help someone
from("file:D:\\INPUTFOLDER?noop=false&recursive=true&maxDepth=NUMBEROFSUBDIR").process(new MyProcessor()).to("file:D:\\OUTPUTFOLDER");

in here NUMBEROFSUBDIR.. will be +1 from the main
  directory(INPUTFOLDER) and it won't copy the folder unless you have
  file present in it, as it supports FTP.


text:
Q: mysql foreign key concept CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;

I dont understand the meaning of putting ENGINE = INNODB here, and why do we use ON DELETE CASCADE?

A: engine=innodb will ensure you get foreign key support. The default MyISAM engine doesn't support foreign keys. On delete cascade will remove the child row if the referenced row in the parent table is removed.

A: MySQL is the DB engine.  It can use multiple storage engines.  MyISAM is the default storage engine for MySQL and it does not support foreign keys.  InnoDB is another storage engine that does support foreign keys.   You must specify ENGINE=InnoDB because MySQL will use MyISAM by default.
ON DELETE CASCADE will delete all rows in a table that have a foreign key that references a key that is deleted.  I think it is dangerous and defeats a lot of the purpose of foreign key restriction, so I would avoid using it, but this is just my personal opinion.
Say you have:
+-------+-------+
| ordID | proID |
+-------+-------+
|     1 |     1 |
|     2 |     1 |
|     3 |     1 |
|     4 |     2 |
|     5 |     2 |
+-------+-------+

And on OrdersItems it has FOREIGN KEY (proID) REFERENCES Products (proID) ON DELETE CASCADE.
Then if someone runs
DELETE FROM Products WHERE proID = 2

Then rows with ordID 4 and 5 will also be deleted (it cascades).


text:
Q: Modify JSON.stringify() for specific components I have a React component state that holds many different classes that needs to be stringify()'d. Most of the components need to be specially treated before they can be put into the JSON object. I believe that using the replacer() and if statements to check the type and then modify the output would be too cumbersome. Short of creating a custom parsing system, is there a way to customize the stringify() in what it parses?
The idea would be to have a custom function (toString() for example) in each class that when the parser reaches the class, instead of going through the key-value pairs, would call the function and append it to the JSON object.

A: From JSON.stringify description
If the value has a toJSON() method, it's responsible to define what data will be serialized.
Usage
JSON.stringify({ toJSON() {return {a: 'eureka'}}})


text:
Q: Best match Mongodb in complex objects I have a database with about 50k records about candidates like the example bellow:
[
{
    "_id":{
       "$oid":"5744eff20ca7832b5c7452321"
    },
    "name":"Candidate 1",
    "characteristics":[
       {
          "name":"personal skills",
          "info":[
             "Great speaker",
             "Very friendly",
             "Born to be a leader"
          ]
       },
       {
          "name":"education background",
          "info":[
             "Studied Mechanical Engineering",
             "Best of his class 2001"
          ]
       }
    ]
},
... thousands more objects with same structure
]

And given some personal skills I would like to search the best matches for that input:
Example of input:
   ["speaker", "leader"]
Expected output:
   list of candidates (whole object) descenting from the best match.
I basically need to search only the field "personal skills".
What could be a good approach for this problem using MongoDB? Or is there another database that fits better this problem?

A: The below query using regex brings us the matching records of  speaker and leader.
db.collection_name.find(
   { $and :
      [
        {"characteristics.info": /.*speaker.*/},
        {"characteristics.info": /.*leader.*/}
      ]
   }
)

To have a better performance we can have a Text Index as shown below, but please note that there is only one Text Index allowed per collection
db.collection_name.createIndex({"characteristics":"text"});

After our Text Index has been created we can see that it is used in our search
Using explain to view the use of Text Index
db.collection_name.find({ $and: [{"characteristics.info": /.*speaker.*/}, {"characteristics.info": /.*leader.*/}]}).explain()

Mongo shell output with query plan explained
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "test.a",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "$and" : [
                                {
                                        "characteristics.info" : {
                                                "$regex" : ".*speaker.*"
                                        }
                                },
                                {
                                        "characteristics.info" : {
                                                "$regex" : ".*leader.*"
                                        }
                                }
                        ]
                },
                "winningPlan" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "$and" : [
                                        {
                                                "characteristics.info" : {
                                                        "$regex" : ".*speaker.*"
                                                }
                                        },
                                        {
                                                "characteristics.info" : {
                                                        "$regex" : ".*leader.*"
                                                }
                                        }
                                ]
                        },
                        "direction" : "forward"
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "PC369236",
                "port" : 27017,
                "version" : "3.6.1",
                "gitVersion" : "025d4f4fe61efd1fb6f0005be20cb45a004093d1"
        },
        "ok" : 1
}


text:
Q: How to add calendar events by their id and delete them by their id? (Android 4.0) With this code my team mate was adding calendar events. This works without problems. The calendar events are shown in the google calendar.
    TimeZone timeZone = TimeZone.getDefault();
        ContentResolver cr = getContentResolver();
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
        values.put(CalendarContract.Events.DTSTART, startInMillis);
        values.put(CalendarContract.Events.DTEND, endInMillis);
        values.put(CalendarContract.Events.TITLE, title);
        values.put(CalendarContract.Events.EVENT_LOCATION, "Raum: " + location);
        values.put(CalendarContract.Events.DESCRIPTION,
                "Dauer der Veranstaltung: " + duration + " min" + "---|---Dozent: "
                        + organizer.trim() + "---|---Course added by UNIDATE---|");
        values.put(CalendarContract.Events.CALENDAR_ID, 1);
        Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
        ContentUris.withAppendedId(uri, id);

But now I want to delete these events by their id. I've used this code (among others):
long selectedEventId = 1;
String[] selArgs = new String[]{Long.toString(selectedEventId)};
int deleted = getContentResolver().delete(CalendarContract.Events.CONTENT_URI, Events._ID + " =? ", selArgs);

This doesn't work. I also tried to add
values.put(CalendarContract.Events._ID, id);

A: A simple solution will be to first clear the calendar events, and then add the relevant events.
Clearing the calendar events can be done by calling this:
context.getContentResolver().delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events.CALENDAR_ID + " = ?", new String[]{String.valueOf(calendarId)});


text:
Q: Unable to get the values from SQLite Database in BlackBerry I am trying to get the table values from the SQlite database, but it is unable to open the URI at DatabaseFactory.open().
I wrote the below code:
    URI myURI = null;
    Cursor cursor = null;
    try
    {
        myURI = URI.create("/SDCard/databases/itemdb.db");

        try
        {
            if(DatabaseFactory.exists(myURI))
            {
                Database sqliteDb = DatabaseFactory.open(myURI);
                try
                {
                    Statement st=sqliteDb.createStatement(query);
                    st.prepare();
                    Logger.out("Grocery", "it is comin here ---- 12");
                    cursor = st.getCursor();
                }
            }
        }
    }

A: It would be better if you included the error message you get when the open() call fails.
Based on this comment:

yes..That itemdb.db is created by my app only. And already i mounted SD card. And when i am inserting the values in the db it is properly happening. I am able to see those values also. But only problem at the time of retrieving..

I am guessing you already have the database open from the insertions.  Make sure the insertion code is properly closing the database, and that you have synchronization so that the read does not try to run at the same time as the insertion code.


text:
Q: Datasets for cache hit-rate evaluation I'm implementing a new eviction strategy for caches. In order to compare its hit ratio to a regular LRU cache, I would like to use data traces from actual systems (like server requests or virtual memory accesses), that I can replay with my cache and measure needed metrics.
Surprisingly, I found very few such traces, the biggest one is Wikipedia access traces.
What are other sources for such traces?
What are common benchmarks for evaluating cache efficiency?


text:
Q: Error: Expected argument of type "int", "App\Entity\Provincie" given at property path "provincie_id" Error: Expected argument of type "int", "App\Entity\Provincie" given at property path "provincie_id".
I use an entity to create a selectbox in my form. It loads fine, when I submit the form I get the above error.
I generated my entity with symfony CLI commands.
Here is the code I use.
src/Controller/UserController.php
<?php

namespace App\Controller;

use App\Form\ProfielType;
use App\Entity\Profiel;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
* Controller used to manage current user.
*
* @Route("/profile")
* @IsGranted("ROLE_USER")
*
* @author Romain Monteil <monteil.romain@gmail.com>
*/
class UserController extends AbstractController
{

 /**
 * @Route("/edit_profile_meta", methods={"GET", "POST"}, name="user_edit_meta")
 */
public function edit_profile_meta(Request $request): Response
{

    $user = $this->getUser();
    $profielId = $user->getId();
    $profile = $this->getDoctrine()
        ->getRepository(Profiel::class)
        ->findOneBy(['user_id' => $profielId]);

    $form = $this->createForm(ProfielType::class, $profile);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($profile);
        $entityManager->flush();

        $this->addFlash('success', 'user.updated_successfully');

        return $this->redirectToRoute('blog_index');
    }

    return $this->render('user/edit_meta.html.twig', [
        'profile' => $profile,
        'form' => $form->createView(),
    ]);
}

}

src/Form/ProfielType.phpp
<?php

namespace App\Form;

use App\Entity\Profiel;
use Symfony\Component\Form\AbstractType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use App\Entity\Provincie;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
* Defines the form used to edit an user.
*
* @author Romain Monteil <monteil.romain@gmail.com>
*/
class ProfielType extends AbstractType
{
    /**
    * {@inheritdoc}
    */
    public function buildForm(FormBuilderInterface $builder, array $options): void
{

    $builder
        ->add('provincie_id', EntityType::class, [
                'class' => Provincie::class,
            ]
        )
    ;

}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver): void
{
    $resolver->setDefaults([
        'data_class' => Profiel::class,
    ]);
}
}

src/Entity/Provincie.php
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="App\Repository\ProvincieRepository")
*/
class Provincie
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="text")
 */
private $naam;

/**
 * @ORM\Column(type="integer")
 */
private $land_id;

public function getId(): ?int
{
    return $this->id;
}

public function getNaam(): ?string
{
    return $this->naam;
}

public function setNaam(string $naam): self
{
    $this->naam = $naam;

    return $this;
}

public function getLandid(): ?int
{
    return $this->land_id;
}

public function setLandid(int $land_id): self
{
    $this->land_id = $land_id;

    return $this;
}

public function __toString()
{
    return $this->getNaam();
}
}


text:
Q: System.InvalidOperationException: Could not read Sitecore configuration I have installed sitecore, created website in iis(6.1) and then mapped properly to the physical folder. When i add a test file (default.aspx) and browse, file load up. But when i try to open content editor (eg: http://localhost:XXXX/sitecore), I see the error
System.InvalidOperationException: Could not read Sitecore configuration
I'm guessing that, a small configuration is missing which is taking me through long go.
Can anyone help me on this?
Thanks in advance

A: Yes, as Patrick says, It was just an permission set to the proj folder. I have unchecked Read Only property of the folder.


text:
Q: Interface Vpc Endpoint - Logs We have VPC Endpoint enabled for several AWS services for example: execute-api for API Gateway. I would like to log all the api calls made to VPC Endpoint into CloudWatch, is there a way?
A couple of things that I can think of:

*

*VPC Flow Logs contains just the IP addresses which is not enough,

*CloudTrail doesn't log these.

I can log at individual service level for example API Gateway Logs, however, if incorrect requests are made to VPC Endpoint and they won't reach the final service in this case API Gateway and there is not trace I can find on what requests are made with that parameters.
Please let me know if I am missing options.

A: No such log exists. VPC Endpoints is pure network configuration so no Data Plane service exists. You can only use VPC flow logs to debug. Also, connectivity between VPC Endpont and service is under AWS responsibility so you have no visibility of that part.


text:
Q: Should deep links on comercial sites be flagged as spam if there is no added value I stumbled over the following answer, which I would suspect being an attempt just to to place a link, since there is no answer or blog at all.
I am just not sure if this is just paranoia.
The question, is should suspected spam be flagged rather too often than too rarely.

A: Disregarding the fact that the example you linked wasn't actually an answer... Yes, links that do not add value or context to an answer need to be removed or flagged as spam (preferably just edit (or suggest an edit) before flagging).
Commonly new users think they can get some free Google juice by dropping a link to one of their sites into a StackOverflow question or answer, what they don't realise is that the system automatically inserts a rel="nofollow" into the anchor for all authors until they pass a certain rep level (5K IIRC).


text:
Q: Laravel + Flatpicker: How to Install using NPM Did is what I did so far

*

*npm i flatpickr --save

*Add @import "~flatpickr/dist/flatpickr.css"; to the app.scss

*index.blade.php

@section('content')

Loaned
<input type="date" class="form-control" name="loaned" id="loaned">

@endsection

@section('scripts')

@endsection

I get an error, "flatpickr is not defined". I read the documentation but it, I don't know what to do with this part:
// commonjs
const flatpickr = require("flatpickr");

// es modules are recommended, if available, especially for typescript
import flatpickr from "flatpickr";

A: You can add do this in one of two ways:
In your app.js (usually under the resources folder):
import flatpckr from 'flatpickr';
window.flatpckr = flatpckr;

This will expose the flatpckr function in your global window object.
An alternative is to add all your script code in your script files instead of in the blade files e.g.:
import flatpckr from 'flatpickr';

// Maybe add conditions on when to run this
flatpckr('#loaned');

This way you don't "pollute" your window object with a bunch of libraries without needing to.

A: In this case I add the following line to webpack.mix.js
mix.copy('node_modules/flatpickr/dist/flatpickr.css', 'public/css/flatpickr.css');

and import the css file the regular way.
<link rel="stylesheet" href="/css/flatpickr.css" />

Addition: of course you need to run npm run dev and if you use versioning, add the file to your git.

A: This works for me:

*

*npm i flatpickr --save

*Register flatpickr in the resources/js/app.js
require('./bootstrap');
require('alpinejs');
require("flatpickr");

*Add an import flatpickr in the resources/css/app.css
@import 'flatpickr/dist/flatpickr.css';

*Run the npm run dev or npm run watch.


text:
Q: How can I make this AJAX to work? I am trying to make a small piece of AJAX to work. It alerts me the correct url but I could not get the page to load.
This is the ajax.js :
$(document).ready(function() {
    $('#sidebar-content ul li a').click(function(){
     var toLoad = $(this).attr('href');
    $('#content').load(toLoad);
    return false;
});
});

I use Laravel here is my default.template.php :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>{{$title}}</title>
    <meta name="description" content="Empire - XHTML Template" />
    {{ HTML::style('css/style.css') }}
    {{ HTML::script('js/jquery.min.js') }}
    {{ HTML::script('js/ajax.js') }}

    <meta charset="UTF-8">

{{ $content }}

<a href="<?php echo URL::to_route('articles'); ?>">ANASAYFA

<a href="<?php echo URL::to_route('abouts'); ?>">HAKKIMIZDA

HİZMETLERİMİZ

Eğitim Hizmetlerimiz

Neurofeedback

Biofeedback

There is an animation when you enter the page. When I click links , If I click with alert the addresses are shown correct but  no content opens and java console shows all the script files loaded again. Can you check it ?

A: It looks like you forgot to prevent the A-tags default behavior, which is redirection. Modify your click event like so:
$('#sidebar-content ul li a').click(function (e) {
    e.preventDefault(); // Prevents link's default behavior.
    var toLoad = $(this).attr('href');
    $('#content').load(toLoad);
    return false;
});

If it is still not working, use console.log() for debugging, like so:
$('#sidebar-content ul li a').click(function (e) {
    e.preventDefault(); // Prevents link's default behavior.
    var toLoad = $(this).attr('href');
    console.log(toLoad); // whats in toLoad?
    console.log($("#content")); // maybe content isnt there?
    $('#content').load(toLoad);
    return false;
});


text:
Q: List all peerID in rtmfp group How can I get list of all peerID`s who now connected into rtmfp group?
Or variant get a group ID, but such as stored on the server.
I tried use sam groupspec.toString(); but this command return result not like in server. Server Cumulus.

A: I assuming you're talking about ActionScript here? The RTMFP protocol in Flash is essentially a rendezvous service - meaning it helps you connect to other clients and that's it. It's not connected to a server as such so it's not aware of who's connected at any given time (and it has no need to know). The messages get passed around by the clients between themselves as opposed to the server.
Making a 'user list' is possible, as described here; http://cookbooks.adobe.com/post_User_List_with_RTMFP_Groups-17535.html
Hope this helps!


text:
Q: Saddle points and negative scalar curvature Let $(M^n,g), n \geq 3$ be a closed Riemannian manifold. Assume that there is a function $\phi : M \to \mathbb{R}$ of class $C^2$ such that $\phi$ has a saddle point. Then, is necessarily true that in this point $M$ has negative scalar curvature?
It seems true, but I just have an intuition about it, like saddle points have a two plane with negative sectional curvature...

A: Take any closed Riemannian manifold $N$ equippped with a function $g \colon N \to \mathbb{R}$ which has a saddle point at $y_0 \in N$, and assume that $N$ has scalar curvature $R_0 < 0$ at $y_0$.  Scale the round metric on $S^2$ so that it has constant scalar curvature $S > 0$, and choose a base point $x_0 \in S^2$ and a smooth function $f \colon S^2 \to \mathbb{R}$ so that $df_{x_0}$ has rank 1.
Now set $M = S^2 \times N$ and define $\phi \colon M \to \mathbb{R}$ by $\phi(x, y) = f(x) + g(y)$.  Then $\phi$ has a saddle point at $(x_0, y_0)$, but the scalar curvature of $M$ at this point is $R_0 + S$; choosing the scale factor $S$ large enough will ensure this is positive.


text:
Q: Using ActionLink and specifying the DELETE Constraint I'm using RestfulRoutes written by Steve Hodgkiss. So far so good but I do have a question. I have a Session Controller that I want to use to destroy a users session when they click the logout button. How can I do this with and action link?
So far I have the following.
<%= Html.ActionLink("Logout", "Destroy", "Session") %>

I need to hit the following route.
Session/{id} and have a DELETE constraint.
I hope this makes sense.
Mike

A: An anchor tag in HTML can only ever issue a GET, it cannot issue any other verbs (unless you intervene with JavaScript).


text:
Q: Expo EAS: How do I get users with builds attached to older production release channels to get the latest changes I want? I have an Expo app and use EAS updates to send over-the-air (OTA) updates to users.
As per the docs, I change the production release channel whenever I add a native module to the codebase, for example, I recently changed the production release channel from 4 to 5. When I put out this new build on the iOS app store, new users who downloaded the app were on the latest production release channel (5), so I could OTA new changes to this new release channel.
How do I get users with builds attached to older production release channels to get the latest changes I want? For example, I want to get users on release channels 1 - 4 to get the same changes as those on release channel 5. I can't OTA to those older channels since my current codebase has new native code changes that will break those older builds.
Is prompting them to manually download the latest version from the app store the only way? Is there a more effective strategy to use release channels / OTA updates so all users can be on the same version?
Attached below is my eas.json
{
  "build": {
    "production": {
      "releaseChannel": "5",
      "env": {
        "ENV": "PROD"
      },
      "cache": {
        "key": "newkey"
      }
    },
    "testflight": {
      "releaseChannel": "1",
      "env": {
        "ENV": "PROD"
      },
      "cache": {
        "key": "anything"
      }
    },
    "staging": {
      "releaseChannel": "staging",
      "ios": {
        "distribution": "internal"
      },
      "android": {
        "distribution": "internal"
      },
      "env": {
        "ENV": "STAGING"
      }
    },
    "development": {
      "ios": {
        "cache": {
          "key": "anything"
        },
        "developmentClient": true,
        "distribution": "internal"
      },
      "android": {
        "developmentClient": true,
        "distribution": "internal"
      }
    },
    "developmentiOSSimulator": {
      "ios": {
        "developmentClient": true,
        "simulator": true,
        "cache": {
          "key": "anything"
        }
      }
    }
  },
  "cli": {
    "version": ">= 0.34.1",
    "requireCommit": true
  }
}

Specs:

*

*Managed Build

*Expo SDK: 44

*expo-cli: 5.3.0

*eas-cli: eas-cli/2.1.0 darwin-arm64 node-v16.14.0
Any help would be greatly appreciated!


text:
Q: sendmail threshold questions in ubuntu on aws ec2 I have sendmail (I know, not postfix, but it's what I've got) up and running on an ubuntu ec2 instance on aws.  Everything is working but I have a couple of questions on whether or not the following are configurable options (and how/where to configure):
As a practical example, I have a php script in my crontab that runs once a week and sends an email to 140+ users.  When I run mailq or sendmail -v -q I can see that all of the emails are queued up.  It seems that the emails are only sent out 1 per 3 minutes, though.
Now for the questions:

*

*Is it possible to have sendmail "blast" out the emails to all unique recipients without waiting 3 minutes between?

*Is it possible to adjust the 3 minute wait time between emails to the same recipient? (Some admin users receive more than one email with different reports).
I've poked around in /etc/mail/sendmail.cf but couldn't figure out what setting to tweak (or if I was even looking in the right place).
Thank you all in advance for the assist.

A: Amazon limits outbound mail from EC2s. From their FAQ:

Q: Are there any limitations in sending email from EC2 instances?
A: Yes.[...] we enforce default limits on the amount of email that can
  be sent

They have a form where you can ask for your limit to be increased, but that isn't the correct way to do it- the correct way is to use Simple Email Service. You can access it with a SMTP endpoint, so it should be fairly trivial to implement.
AWS even has documentation to assist you: "Integrating Amazon SES with Sendmail".


text:
Q: PowerBI - Create a table of dates based off a date range within another data set I need some help with creating a table based off values from another data set. I have a data set that has a start and end date. Based off the start and end data AND current, how would I create a table that list all the dates within the start and end date range? The screenshot is the data set. The data below is what I am trying to get. Please help if possible!

********
Date
********
3/28/2021
3/29/2021
3/30/2021
3/31/2021
4/1/2021
4/2/2021
4/3/2021
4/4/2021
4/5/2021
4/6/2021
4/7/2021
4/8/2021
4/9/2021

A: Load into powerquery using data .. from table/range
use the arrow atop the isCurrentSprint column to [x] select Current
Add column .. custom column with formula
 = {Number.From([Iteration Start Date]) .. Number.From([Iteration End Date])}

right click the new column and Remove Other columns
Use arrows atop the remaining column to expand to new rows
click column and transform .. data type .. date
file close and load
sample code
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Filtered Rows" = Table.SelectRows(Source, each ([isCurrentSprint] = "Current")),
#"Added Custom" = Table.AddColumn(#"Filtered Rows", "Custom", each {Number.From([Iteration Start Date]) .. Number.From([Iteration End Date])}),
#"Removed Other Columns" = Table.SelectColumns(#"Added Custom",{"Custom"}),
#"Expanded Custom" = Table.ExpandListColumn(#"Removed Other Columns", "Custom"),
#"Changed Type" = Table.TransformColumnTypes(#"Expanded Custom",{{"Custom", type date}})
in #"Changed Type"


text:
Q: Creating div with jQuery I've been trying to create a function when button is pressed to create a div inside existing div. That div should be loaded from external source(miniclip.com). I've tried a quite few things and nothing seems to be working.
I would greatly appreciate any help.
Here is all my code:

<meta charset="UTF-8">

<link href="main.css" rel="stylesheet" type="text/css"/>

    <meta type="viewport" content="width=device-width, initial-scale=1.0">

<title>Title?</title>

      <button type="button" id="igra1" class="button1">Opcija 1</button>
        <button type="button" id="igra2" class="button1">Opcija 2</button>
        <button type="button" id="igra3" class="button1">Opcija 3</button>

Za početak odaberi igru

prijmer banera

prijmer banera

A: Using Jquery you can create elements to inside a div by appending the new element

      $('#igra1').click(function()
      {
        $('#okvir').show(1000);
      });

      $('#igra2').click(function()
      {
        $('#okvir').show(1000);
        $("#okvir").append("
NEW DIV
");

      });

      <button type="button" id="igra1" class="button1">Opcija 1</button>
        <button type="button" id="igra2" class="button1">Opcija 2</button>
        <button type="button" id="igra3" class="button1">Opcija 3</button>

Za početak odaberi igru

prijmer banera

prijmer banera


text:
Q: setting adapter gives null exception in retrofit 2 call back method? I am new to android and I have been using retrofit 2 to get data from the server, in my app when activity starts or on create of activity, a method is called to fetch data from server and on-Response of this call I am getting data and setting the data to the spinner and it gets successful and the list of data is visible in user interface when running the app.
Now I have to add Autocomplete text-view so that on typing a character the spinner gives that list of data according to the typed characters in Autocomplete text-view.
I have added array adapter with data and I set it to the spinner it works, below this using same array adapter I set it to the Autocomplete text-view but gives an error of null pointer exception. So for my understanding adapter is somehow setting it early which points to the null error.
 public void fetch_information() {
    ApiInterface2 = ApiClient.getApiClient().create(Api.class);

    Call<List<City>> call = ApiInterface2.GetCities();

    call.enqueue(new Callback<List<City>>() {
        @Override
        public void onResponse(Call<List<City>> call, Response<List<City>> response) {
            CityList = new ArrayList<City>();
            CityList = response.body();
            City myCustomObject = new City();
            myCustomObject.setCityName("Select Country");
            CityList.add(myCustomObject);
            ArrayList<String> CityNames = new ArrayList<String>();

            cities = new String[CityList.size()];
            citiesid = new String[CityList.size()];
            for (int i = 0; i < CityList.size(); i++) {
                cities[i] = CityList.get(i).getCityName();
                citiesid[i] = CityList.get(i).getCityId();
                 CityNames.add(CityList.get(i).getCityName());

            }

            city_adapter = new ArrayAdapter<String>(AddKhataPurchase.this, android.R.layout.simple_list_item_1, cities);
            city_adapter.setDropDownViewResource(R.layout.spinner_dropdown_layout);
            city_spinner.setAdapter(city_adapter);
            city_spinner.setSelection(cities.length - 1);

          //  fetch_searchable_spinner_cities();
            if(CityNames.size()> 1) {
                ArrayAdapter myAdapter = new ArrayAdapter<String>(AddKhataPurchase.this,
                        android.R.layout.simple_spinner_dropdown_item, CityNames);

//here not able to set the adapter as null pointer exception happens

                myAutoCompleteTextView.setAdapter(myAdapter);
            }
}

        @Override
        public void onFailure(Call<List<City>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

}

Activity opens, the method (fetch_information) gets called and here onResponse city spinner after setting array adapter shows the list of cities in UI but when i try to do the same below it by setting array adapter to myAutoCompleteTextview null pointer exception although got the data but still error.
Can i set Autocomplete Textview after the response call finishes?


text:
Q: how to submit "multipart/form-data" from VueJs I am using VueJs / axios in frontend and multer in nodejs for a simple file upload to work.
So far all tries has been unsuccessful.
While this can be achieved in 100 ways in angular 1/2 using ng-upload and other similar plugins. But VueJs seems to be lacking this basic functionality.
Based on my research axios doesnt support "multipart/form-data". Ref https://github.com/mzabriskie/axios/issues/789 .
multer and other nodejs libraries seems to work with "multipart/form-data" seamlessly from angular 1/2. However same functionality is not working from VueJs.
Is there any other alternative other than axios which support "multipart/form-data" aka -- WebKitFormBoundary  ??
Many Thanks

A: You can use FormData for that and it is pretty easy.
Let me show you an example:
// html
<button ref="uploadBtn" @onChange="upload">Upload Files</button>

// js
methods: {
    upload () {
        let files = this.$refs.uploadBtn.files
        let formData = new FormData()

        // if you want to upload multiple files at once loop
        // through the array of files
        formData.append('attachment', files[0])
        axios.post(url, formData).then(response => ...)
    }
}

This should do the trick and you don't really need a 3rd party plugin for that.

A: I found two ways of achieving this in VueJs. There might be more.
Option 1. Using Axios. Based on answer by Bert Evans above

const formData = new FormData();
  formData.append("file", _file);
  formData.append("id", 7878);
  axios.post("/api/uploadFile", formData)
    .then(function (result) {
      console.log(result);
    }, function (error) {
      console.log(error);
    });

Option 2. Using Native XMLHttpRequest()`

 var formData = new FormData();
  formData.append("file", _file);
  formData.append("id", 7878);
  var request = new XMLHttpRequest();
  request.open("POST", "/api/uploadFile");
  request.send(formData);
  request.onreadystatechange = function () {
    if (request.readyState === 4) {
      if (request.status === 200 && request.statusText === 'OK') {
        console.log('successful');
      } else {
        console.log('failed');
      }
    }
  }

An interesting point of FormData() browser support here caniuseFormData
Also for those trying like me to make it work with content-type = "multipart/form-data" with axios. It won't work.

A: i have also faced the an issue where i have to send some other info along with image. i would like to share what i did.
I am trying to upload image, kind, name and eventID.
let logo1 = new FormData
logo1.append('image', this.logo1)
logo1.append('kind', 'logo1')
logo1.append('name', this.$refs.logo1.files[0].name )
logo1.append('eventID',eventID)

axios.post(`/upload`, logo1,

  {
    headers:{
      'Authorization' : `${token}`,
      'Content-Type': `multipart/form-data; boundary=${logo1._boundary}`
 },

 }).then((res) => {

     console.log(res)

}).catch((error) => {

    console.log(error)

})

Note: The postdata param format should be (url , FormData) and not (url, {data: FormData})


text:
Q: Linking Object to UI What is the best method to use to link a class to a user form?
Sorry to be hypothetical, but using actual code will lead to a question that is pages long.
Let's say I have a class that holds data about a person.
<<class Person>>
Public FirstName as String
Public LastName as String
Public PhoneNumber as String
<<end class>>

I put that data into a VBA UserForm listview.
Now, let's say I want to change the phone number to 555-555-1234 if the user clicks on that record in the listview.
I can read the interaction with the listview with the item click event.
Private Sub lvExample_ItemClick(ByVal Item As MSComctlLib.ListItem)
  ' Change the phone number
End Sub

What is the best way to get from Item in the above code to my actual object?  Should I add an GUID to each object and put that in the tag of the listitem, then look it up?  Should I add the listitem from the listview into the class so I can loop through all my people and then see if the Item from _ItemClick equals the Item from the object?

A: The easiest way is to use either the Index property, if you don't have any unique identifier, or the Key property if you do, of the ListItem.
If you choose to use the Index property, then you can't (or at least it will greatly complicate it) add any functionality to rearrange the order of list items.
You would have populated the ListView based on the objects in a collection/recordset via the ListView.ListItems.Add method. You can use the Index property to get back to that original object based on the order of items in ListItems corresponding to the order of items in your original collection of objects.
Alternatively, if you prefer the greater flexibility of using a unique key but don't wish to modify the underlying object, then you can trivially construct a unique key (the simplest being CStr(some incrementing number)) as you add each object to ListItems, storing the keys alongside the objects.
You can then use the .Key property of the ListItem. The benefit here is the user can be allowed to modify what items are in, delete stuff etc without you having to invalidate your control and re-add all objects in order to keep the linkage between Index in source and index in the list.
E.g.:
Private persons As Collection
Private Sub lvExample_ItemClick(ByVal Item As MSComctlLib.ListItem)
    ' Change the phone number:

    'Method 1, using the index of listitem within listitems
    'to tie back to index in persons collection
    'Don't allow rearranging/sorting of items with this method for simplicity
    With persons.Item(Item.Index)
        .PhoneNumber = "555-555-1234"
        '...some stuff
    End With

    'Method 2, using a unique key
    'that you generate, as the underlying person object doesn't have a necessarily unique one
    'Items would have been added in a method similar to AddItemsExample1() below
    With persons.Item(Item.Key)
        .PhoneNumber = "555-555-1234"
        '...some stuff
    End With

End Sub

Sub AddItemsExample1()
    'Storage requirements vs. your existing recordset or whatever
    'are minimal as all it is storing is the reference to the underlying
    'person object

    'Adapt per how you have your existing objects
    'But basically get them into a keyed collection/dictionary

    Dim i As Long
    Set persons = New Collection
    For Each p In MyPersonsSource
        persons.Add p, CStr(i)
        i = i + 1
    Next p

    'By keying them up, you can allow sorting / rearranging
    'of the list items as you won't be working off of Index position

End Sub

Finally, another way if you have them in a recordset returned by a DB is to add a new field (I imagine you have an existing object field) and do run an UPDATE query on your records populating it with an incrementing number (this should only effect the local recordset (check the recordset settings first of course!)). Use this as the key.
You mention in a comment to your question that you get the data from SQL. For all normal purposes with a list box it is still probably easiest to just run them through a Collection object as detailed above, but if you have e.g. 4 fields from SQL for a record in a recordset then you don't hav an 'object' in the sense of being able to call properties on it. Please specify in your question or in a comment to this if you do so, as there may be a better treatment to answer your question or the actual update operation will likely require different syntax or semantics (particularly if you need to propagate any update back to the source) :)

A: I would use a event driven approach.
Person will have properties instead of variables and assigning those properties will raise a event.
User form will have WithEvents Person, so that changes in related person will trigger user form code.
Person class:
Public Event Changed()
Private pFirstName As String
Private pLastName As String
Private pPhoneNumber As String

Public Property Get FirstName() As String
    FirstName = pFirstName
End Property

Public Property Let FirstName(ByVal v As String)
    pFirstName = v
    RaiseEvent Changed
End Property

Public Property Get LastName() As String
    LastName = pLastName
End Property

Public Property Let LastName(ByVal v As String)
    pLastName = v
    RaiseEvent Changed
End Property

Public Property Get PhoneNumber() As String
    PhoneNumber = pPhoneNumber
End Property

Public Property Let PhoneNumber(ByVal v As String)
    pPhoneNumber = v
    RaiseEvent Changed
End Property

Event catching in user form:
Public WithEvents ThisPerson As Person

Private Sub ThisPerson_Changed()
    'Update user form
End Sub

So whenever you assign YourForm.RelatedObject = SomePerson, any changes done to SomePerson will trigger code in YourForm.

A: Since you can't change returned ListItem, I have another solution:
Add a related ListItem to your Person class:
Public FirstName as String
Public LastName as String
Public PhoneNumber as String
Public RelatedObject As Object

When populating TreeView, assign it:
Set SomeListItem = SomeTreeView.ListItems.Add(...)
Set SomePerson.RelatedObject = SomeListItems

So whenever you have a change in a ListItem:
Private Sub SomeListView_ItemClick(ByVal Item As MSComctlLib.ListItem)
    Dim p As Person
    For Each p In (...)
        If p.RelatedObject Is Item Then
            'Found, p is your person!
            p.PhoneNumber = ...
        End If
    Next
End Sub

Alternatively, if you don't want to change your Person class, you can encapsulate it in another class, eg, PersonToObject:
Public Person As Person
Public RelatedObject As Object

And use PersonToObject as link objects.


text:
Q: Finding square roots in surd form I'm trying to build a program that let's you multiply two square roots and display the answer in surd form if the answer isn't an integer.
I've seen answers here and here, although I don't understand C++ and C#, so I don't have a clue on what to do. The first thing I've done is multiply the two numbers inside the square roots together, then I can display the answer if it is an integer, but if it isn't it completely messes up.

A: I don't see a better way than by factoring the given numbers, summing the multiplicities of the prime factors, extracting the even parts of the multiplicities and forming the square root of the products.
E.g.
√(84.375)=√(2²3.7.3.5³)=√(2²3²5³7)=2.3.5√(5.7)=30√35

A: Try using SymPy:
>>>import sympy
>>>sympy.sqrt(8)
2*sqrt(2)


text:
Q: best way to handle url in codeigniter even special characters in codeigniter i want to write url for my project base on product title fetch by google bing and amazon by API.
i don't know how to handle and what type of url is best
if  title url have special character and any type of critical url Whatever.
i have some idea for write url i don't know best way or not .
first when we add record in database those time we add title according url sporting replace special characters and any other types in future create trouble by using str_replace preg_repalce and any other ways.
second those time when we write url we handle it by using str_replace preg_repalce
third we handle in this way $config['permitted_uri_chars'] = 'a-z 0-9~%.:_()@\-';
if any one have more ideas and best way to handle critical url  please share experience

A: Codeigniter comes with a very handy URL helper. One of the functions is for doing just that. (Removes any illegal characters, replaces spaces and can force lowercase which I always use).
$title = "This is my best product";

$url_title = url_title($title, '-', TRUE);

// Produces: this-is-my-best-product

The first argument is your string, the second is the word separator you want to use ( '_', '-', '', etc) and the third argument forces lower case to be used.
You can read about it here:
http://www.codeigniter.com/user_guide/helpers/url_helper.html#url_title
Hope that helps,
Paul.