text:
Q: Why Android Threading work and async not work i got a list that contain A, B and C, and i send it via WCF to aSp.NET.
when i use async task i got A, C and C, but when i use threading it work well.
here is my code:
case R.id.btn_Reception:
            {
                for(Pers_Ordre p : ListOrdres){
                    dbcon.open();

                    p.setLe_Statut("1");
                    p.setLe_Camion(sharePref_Camion.getString("CammionSetting",""));

                    ordreItem = p;

                    dbcon.createItmes(p);
                    dbcon.close();

                    // call AsynTask to perform network operation on separate thread

                    // new HttpAsyncTask().execute("http://myseite/Service.svc/FA/SaveData");

                      new Thread(new Runnable() {
                            public void run() {
                                 runOnUiThread(new Runnable() {
                                        public void run() {

                                        }
                                    });

                                 POST("http://myseite/Service.svc/FA/SaveData", ordreItem);

                            }
                          }).start();
                }

                  ListOrdres.clear();
                  m_adapter = new CustomListAdapter(this, ListOrdres);
                  m_adapter.notifyDataSetChanged();
                  lv_Ordre.setAdapter(m_adapter);

                Toast.makeText(getApplicationContext(),
                        "Rec", Toast.LENGTH_SHORT).show();
            }
            break;

as you can see i comented the async task.
EDITED
Here is my async code:
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
                 return POST(urls[0],ordreItem);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        if (result.isEmpty())result ="Oke";
        //else result = "Doublons";
        Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
        Log.d("ERR_WCF", result);
   }
}

public static String POST(String url, Pers_Ordre  TheOrdre){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();

         jsonObject.accumulate("CodeClient", TheOrdre.getLe_CodeClient());
         jsonObject.accumulate("CodeDest", TheOrdre.getLe_CodeDest());
         jsonObject.accumulate("NoOrdre", TheOrdre.getLe_NoOrdre());
         jsonObject.accumulate("LeDate", TheOrdre.getLe_Date());
         jsonObject.accumulate("LeGPS", TheOrdre.getLe_GPS());
         jsonObject.accumulate("LeStatut", TheOrdre.getLe_Statut());
         jsonObject.accumulate("LeCamion", TheOrdre.getLe_Camion());
         jsonObject.accumulate("LeOrdrePos", TheOrdre.getLe_Ordre_1());
         jsonObject.accumulate("LeOrdreTot", TheOrdre.getLe_Ordre_2());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result +TheOrdre.getLe_CodeClient()+"__"+TheOrdre.getLe_CodeDest()+"__"+TheOrdre.getLe_NoOrdre()+ "__"+TheOrdre.getLe_Ordre_1()+"--"+TheOrdre.getLe_Ordre_2();
}

A: I don't know which versions you are targeting but I am guessing it's because you didn't account for the different threadpoolexecutors that android uses.
Try this:
new HttpAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "http://myseite/Service.svc/FA/SaveData");

Newer versions of android uses a linear thread pool executor by default. So asynctask are executed one after the other.
I hope I could help.


text:
Q: position of element is changing after re-showing selenium element I am performing same operation for author and about anchor tags
Code to find element
element = driver.find_element('class_name','author')

Code to hide element
driver.execute_script("arguments[0].style.display = 'None';", element)

code to show element
driver.execute_script("arguments[0].style.display = 'block';", element)

Question
why the author name and about element position changed after re-showing same elements?
Website Link : https://quotes.toscrape.com/

A: https://www.w3schools.com/cssref/pr_class_display.asp
block displays the element in next line. delete that property completely or use inline
driver.execute_script("arguments[0].style.display = undefined;", element)

or
driver.execute_script("arguments[0].style.display = 'inline';", element)

A: The author name and the text link "about" are specified in two different lines. Instead of just hiding the author's line using class name, I would suggest try hiding the whole span
Xpath for the same will be xpath = "/html/body/div/div[2]/div[1]/div[1]/span[2]"
If you want to retain the text "by", then try specifying separate variables to find the element of the two lines and hide/unhide them individually. This should not alter the structure of the html elements.

Try this and let me know if it worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable menu item from the ASyncTask on android? Trying to do the following (code is in the main activity):
private MenuItem mainMenuSync = null;

public void onCreate(Bundle savedInstanceState) {
  ...
  mainMenuSync = (MenuItem) findViewById(R.id.main_menu_sync);
}

private class Synchronize extends AsyncTask<Void, Void, Void> {
  ...

  @Override
  protected void onPreExecute() {
    mainMenuSync.setEnabled(false);
  }

But it fails. What I am doing wrong?
(This menu item really starts this ASyncTask and I would like to avoid starting it again)

A: Since your mainMenuSync is coming from a Main Menu, I guess you are creating it in onCreateOptionsMenu, isn't it?
If that's the case, filling its value using onCreate would have no effect, since by that moment, your main menu isn't inflated from the xml yet, and I wonder you should already FC before seeing anything on the screen.
Main Menu is not the same as other UI item in Android, which in most use cases they are inflated on demand in onCreateOptionsMenu and reused next in onPrepareOptionsMenu. What you can do is to declare a flag to enable/disable that item:
boolean showMainMenuSync = true;

onPrepareOptionsMenu(Menu menu){
    super.onPrepareOptionsMenu(menu);
    menu.findItem(R.id.main_menu_sync).setEnabled(showMainMenuSync);
}

which of course showMainMenuSync should be changing by your async task.


text:
Q: ActionResult parameters with no default constructor Obviously there are a number of ways to do this, but I thought I'd ask for a little feedback on benefits and drawbacks of the approaches.
First of all, the NerdDinner tutorial's Edit Action is in the form (say Form A):
[HttpPost]
public ActionResult Edit(int id, FormCollection collection) {

It seems to me that if you shape your ViewModels well to match your views, that the approach Form B:
[HttpPost]
public ActionResult Edit(MyViewModel mvm) {

just seems like a better, cleaner approach.  I then just map the VM properties to the Model properties and save.  However, if this ViewModel has other entities embedded in it that are initialized via the constructor (for example in the nerddinner tutorial), then this edit action fails if there is no default constructor and you'd have to use the first approach.
So, the first question is do you agree that generally Form B is usually better?  Are there drawbacks?
Secondly, it seems then if Form B is used, the decorator type validation would need to be in the ViewModel.  Are there advantages of embedding entities in ViewModels and keeping the validation at the entity level only?

A: This is a pretty general SO question.

the first question is do you agree that generally Form B is usually better?

The only time I do not use Form B is when I upload files.  Otherwise, I don't believe anyone should ever need to use Form A.  The reason I think people use Form A is a lack of understanding of the abilities of ASP.Net's version of MVC.

Secondly, it seems then if Form B is used, the decorator type validation would need to be in the ViewModel.

Sort of / it Depends.  I'll give you an example:
public IValidateUserName
{
  [Required]
  string UserName { get; set; }
}

public UserModel
{
  string UserName { get; set; }
}

[MetadataType(typeof(IValidateUserName))]
public UserValiationModel : UserModel
{
}

The validation decorator is in an interface.  I'm using the MetadataType on a derived class to validate the derived type.  I personally like this practice because it allows reusable validation and the MetadataType/Validation is NOT part of the ASP.NET core functionality, so it can be used outside of ASP.Net (MVC) application.

Are there advantages of embedding entities in ViewModels ..

Yes, I do my absolute best to never pass a basic model to the view.  This is an example of what I don't do:
public class person { public Color FavoriteColor { get; set; } }

ActionResult Details()
{
  Person model = new Person();
  return this.View(model);
}

What happens when you want to pass more data to your view (for partials or layout data)?  That information is not Person relevant most of the time so adding it to the Person model makes no sense.  Instead, my models typically look like:
public class DetailsPersonViewModel()
{
  public Person Person { get; set; }
}

public ActionResult Details()
{
  DetailsPersonViewModel model = new DetailsPersonViewModel();
  model.Person = new Person();
  return this.View(model);
}

Now I can add required data the DetailsPersonViewModel that view needs beyond what a Person knows.  For example, lets say this is going to display a for with all the colors for the Person to pick a favorite.  All the possible colors aren't part of a person and shouldn't be part of the person Model, so I'd add them to the DetailPersonViewModel.
public class DetailsPersonViewModel()
{
  public Person Person { get; set; }
  public IEnumerable<Color> Colors { get; set; }
}

.. and keeping the validation at the entity level only?

System.ComponentModel.DataAnnotations weren't designed to validate properties' properties, so doing something like:
public class DetailsPersonViewModel()
{
  [Required(property="FavoriteColor")]
  public Person Person { get; set; }
}

Doesn't exist and doesn't make sense.  Why ViewModel shouldn't contain the validation for the entity that needs validation.

this edit action fails if there is no default constructor and you'd have to use the first approach.

Correct, but why would a ViewModel or a Entity in a ViewModel not have a parameterless constructor?  Sounds like a bad design and even if there is some requirement for this, it's easily solved by ModelBinding.  Here's an example:
// Lets say that this person class requires
// a Guid for a constructor for some reason
public class Person
{
  public Person(Guid id){ }
  public FirstName { get; set; }
}

public class PersonEditViewModel
{
  public Person Person { get; set; }
}

public ActionResult Edit()
{
  PersonEditViewModel model = new PersonEditViewModel();
  model.Person = new Person(guidFromSomeWhere);

  return this.View(PersonEditViewModel);
}

//View
@Html.EditFor(m => m.Person.FirstName)

//Generated Html
<input type="Text" name="Person.FirstName" />

Now we have a form that a user can enter a new first name.  How do we get back the values in this constructor?  Simple, the ModelBinder does NOT care what model it is binding to, it just binds HTTP values to matching class properties.
[MetadataType(typeof(IPersonValidation))]
public class UpdatePerson
{
  public FirstName { get; set; }
}

public class PersonUpdateViewModel
{
  public UpdatePerson Person { get; set; }
}

[HttpPost]
public ActionResult Edit(PersonUpdateViewModel model)
{
  // the model contains a .Person with a .FirstName of the input Text box
  // the ModelBinder is simply populating the parameter with the values
  // pass via Query, Forms, etc

  // Validate Model

  // AutoMap it or or whatever

  // return a view
}

A: I have not yet taken a look at the NerDinner project, however, I generally try to avoid having a ViewModel in the POST of an action and instead, only have the elements of the "form" submitted.
For instance, if the ViewModel has a Dictionary that is used in some kind of dropdown, the entire dropdown will not be submitted, only the selected value.
My general approach is:
[HttpGet]
public ActionResult Edit(int id)
{
     var form = _service.GetForm(id);

     var pageViewModel = BuildViewModel(form);

     return View(pageViewModel);
}

[HttpPost]
public ActionResult Edit(int id, MyCustomForm form)
{
     var isSuccess = _service.ProcessForm(id);

      if(isSuccess){
         //redirect
      }

      //There was an error. Show the form again, but preserve the input values
      var pageViewModel = BuildViewModel(form);

      return View(pageViewModel);
}

private MyViewModel BuildViewModel(MyCustomForm form)
{
     var viewModel = new MyViewModel();

     viewModel.Form = form;
     viewModel.StateList = _service.GetStateList();

    return viewModel;
}


text:
Q: Entity framework - Avoid circular Relationship in serialization I have two tables : Users & Profiles. A user has one profile (1:1), a profile can be affected to many users, each profile has many modules, each module has many actions.
I'm sending this object from an asmx to a aspx page using a direct service call.
I got an error because of lazy loading ... so I disabled the lazy loading.
this.Configuration.LazyLoadingEnabled = false;

this works fine, I got my user, with the profile null.
To build the menu tree I have to retrieve the profile. I included It :
        User user = new User();
        using (cduContext db = new cduContext())
        {
            // get the user
            string encryptedPassword = Encryption.Encrypt(password);
            user = (from u in db.Users
                    where u.UserName.Equals(login) &&
                          u.Password.Equals(encryptedPassword)
                    select u).FirstOrDefault();
            // Include the users profile
            user = db.Users.Include("Profile").FirstOrDefault();
        }
        return user;

I got this error in the javascript call function :

A circular reference was detected while serializing an object of type 'CDU.Entities.Models.User'.

When I made a quick watch on the user object, in asmx ( before sending it ) , I found, that the profile has included the list of the users who had this pofile, each user has his profile loaded ... etc
Any idea please ?

A: Note, your code should look like this:
using (cduContext db = new cduContext())
{
    // get the user
    string encryptedPassword = Encryption.Encrypt(password);
    var user = from u in db.Users
               where u.UserName.Equals(login) &&
                     u.Password.Equals(encryptedPassword)
               select u;
    // Include the users profile
    return user.Include("Profile").FirstOrDefault();
}

In your code, you were throwing away the first query by overwriting it with the second.  And there was no valid reason to create a blank user.
To address your problem, you're going to have make a decision on what you don't want to serialize.  In your case, you probably don't want to serialize Profile.Users
You don't mention what serializer you're using.  I'm assuming you're using the DataContract serializer?
EDIT:
You would mark your Profile.Users object with the [IgnoreDataMember] Attribute.


text:
Q: Assertion error expectation failure EasyMock I have the next JUnit test, and it works fine, but finally in the verify it throws expectation failure. I think it is because the mocked PsPort is different of the PsPort that I send to the DataReader.
Is there any other way to test it?
    @Test
    public void testguardarMensaje() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException{

        String datoTest = "1=123456";

        Constructor<PsPort> constructor = PsPort.class.getDeclaredConstructor(new Class[] {String.class});
        constructor.setAccessible(true);
        PsPort port = constructor.newInstance("middleware.conf");

        PsPort drMock;

        int hash1 = datoTest.hashCode();
        String hashString1 = String.valueOf(hash1);
        String combinedIdDataHashString1 = datoTest +"="+ hashString1;

        drMock = strictMock(PsPort.class);
        byte[] datoByte = port.encriptarDesencriptarMensaje(combinedIdDataHashString1.getBytes(), Cipher.ENCRYPT_MODE);
        drMock.guardarDato(datoByte);
        replayAll();

        int hash = datoTest.hashCode();
        String hashString = String.valueOf(hash);
        String combinedIdDataHashString = datoTest +"="+ hashString;

        byte[] datoByte2 = port.encriptarDesencriptarMensaje(combinedIdDataHashString.getBytes(), Cipher.ENCRYPT_MODE);

        DatagramPacket paquete = new DatagramPacket(datoByte2,datoByte2.length);
        paquete.getData();

        DataReader dr = new DataReader(port, null, 100, "=", "C:/Users/Asier/Desktop/logs/");

        dr.guardarMensaje(paquete, port);
        verifyAll();
    }

A: It is really confusing that you have two port objects. What is the sense of creating a mocked drPort; when you are then giving a "real" port object to your class under test?
You see: you either create a mock and pass that down to your code under test (and then you have to setup the mock for the expected behavior; which you can afterwards verify); or you only provide "real" objects to your code under test, but then you would normally do some kind of asserts on the results of calls to "code under test".
So, in that sense, it doesn't really matter that there is at least one problem in your code:
drMock.guardarDato(datoByte);
replayAll();

There should be a call to EasyMock.expectLastCall() after the method invocation on drMock; but as said: as the mocked object isn't really used, that doesn't matter, on the one hand. Because, if you added that statement, your test would always fail; since your un-used mock would never see the calls that you specified it to see.
In order to give you some guidance; this is how you do such kind of testing in general:
SomeClassYouNeed mockedThingy = createStrict/Nice(SomeClassYouNeed.class);
expect(mockedThingy.foo()).andReturn("whatever");
mockedThingy.bar();
expectLastCall();
replay (mockedThingy);

ClassUnderTest underTest = new ClassUnderTest(mockedThingy);
underTest.doSomething();

verify(mockedThingy)

Meaning: any "object" that
a) your "class under test" needs to do its work
b) you want/have to "control" in a certain way
needs to be mocked; including a "specification" of all expected method calls.
Then you provide the mocked things to your code under test; execute the method you want to test ... to finally verify that the mock saw the behavior that you specified for it.


text:
Q: Collapsible ChoiceField in Django I have a django form with what is currently a TextField input that I'd like to turn into a ChoiceField so that I can do away with having to compare similar answers to determine if they refer to the same thing.  However, the number of possible choice is prohibitive (several hundred).  What I really would like is a collapsible ChoiceField where users could select a category, then a sub-category, and so on so that at each step they would only be presented with a reasonable number of options (especially since many users are on mobile devices with limited screen sizes).  The options are quite amenable to unambiguous categorization and so this seems like a good way to display the information.  However, while I see information about collapsing all sorts of other sorts of aspects of forms I haven't seen how to do this.  I'm not even sure what avenue to pursue to make this work best.  CSS or javascript seem to be the ways most people make collapsible lists but I don't know whether either of these will play well with a django Select widget.  What's my best option to do this sort of thing?
Here are the options I'm aware of:
1) Write some sort of new widget.  This sounds horrible (based on my experience writing new widgets) but if it's the best option I'll do it.
2) Use a normal select widget and use javascript to hide options.  I'm not exactly sure how to select options in clean groups though.
3) Use a CSS collapsible list and and hidden form field with a bit of javascript to grab the value from the list and insert it into the hidden field.
4) Use a chain of views to navigate through to the smallest category.  This sounds easy to do, nice and clean (because all the logic is in Python where I feel comfortable), but requires multiple reloads which may be problematic for mobile users.

A: If the number of subcategories is infinite, this is probably your only solution. If it's not infinite, you might be able to get away with loading up all of the choices on the page immediately along with their parent categories so that you can decide which choices to show via javascript.


text:
Q: Can Firebase Data Messages be disabled by iPhone users? Do Firebase Cloud Messaging Data Messages need to be allowed by an iPhone user and can he disable them in the iPhone's Settings app?

I know that this is required for "Notification Messages". But Firebase "Data Messages" seem different. I do not want to show any visible notification to the user. I just want to ping the iPhone app if and when data in the backend were updated to let the app know that it needs to refresh its data from the server. This is meant to happen in the background without the user noticing.
The aim is to avoid having the app frequently "pull" and ask the backend whether a data refresh is needed. But if "Data Messages" can be disabled by the user, I will not use them as a vehicle to keep critical app data in sync.
Thanks!


text:
Q: Spring 4.07 Junit Test and Autowired Hi I'm using Spring and CDI.
In my unit test I want to test a Class that uses the @Autowired annotation.
Problem is if I create a instance of this class and call a method all annotated objects are null.
In basic the annotation works. Just whithin my unit test it doesn't
This is my Unit Test. In here Autowired works. In my test I create an instance of the DemoConsumerBean.class and call the method requestJobsFromPublishedJobsApi in here I have also some Autowired declaration. Problem is all instances are null!
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("development")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, FirstbirdTestExecutionListener.class, FlywayTestExecutionListener.class })
@ContextConfiguration(locations = { "classpath:hibernate-spring.xml" })
@FlywayTest
public class DemoConsumerBeanTest extends AbstractJUnit4SpringContextTests {

@Autowired
private CustomerManager customerManager;

@Autowired
private DemoDetailsManager demoDetailsManager;

@Before
public void setup() {
    CamelContext context = new DefaultCamelContext();
    exchange = new DefaultExchange(context);
}

@Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
    DemoConsumerBean demoConsumerBean = new DemoConsumerBean();

    customer = new Customer();
    customer.setCustomerId(15);

    customer = customerManager.getCustomerById(customer);

    // This one works
    DemoDetails demoDetails = demoDetailsManager.getDemoDetailsByCustomerId(customer);

    demoConsumerBean.requestJobsFromPublishedJobsApi(exchange, customer);

    PublishedJobs apiJobs = exchange.getIn().getBody(PublishedJobs.class);

    assertNotNull(apiJobs);

}

}
public class DemoConsumerBean {

@Autowired
protected CustomerManager customerManager;
@Autowired
protected DemoDetailsManager demoDetailsManager;
@Autowired
protected MessageLogManager messageLogManager;

public void requestJobsFromPublishedJobsApi(Exchange exchange, Customer customer) throws NoSuchDataException {
    //this one is null!
    DemoDetails demoDetails = demoDetailsManager.getDemoDetailsByCustomerId(customer);
    PublishedJobs jobs = null;

    if (demoDetails == null || StringUtils.isBlank(demoDetails.getDemoApiUrl())) {
        throw new NoSuchDataException("No demo data found for customer " + customer.getCustomerFirstbirdId());
    }
....
}

}

A: Using new in new DemoConsumerBean(); bypasses spring, that's your issue.
Either use a DemoConsumerBean instance from spring (i.e. autowired in the test) or add setters and use them to "manually autowire" in DemoConsumerBean in your test:
@Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
    DemoConsumerBean demoConsumerBean = new DemoConsumerBean();
    demoConsumerBean.setCustomerManager(this.customerManager)
    // etc

Some reading: Spring framework reference - The IoC container


text:
Q: Phonegap : losing data on first page after navigating back to first page Phonegap, writing app for Android.  Here is what my app supposed to do :
1) onDeviceReady, read xml ( item names and corresponding hyperlink for each item  - so kind of Table of contents) and show them on index.html
onDeviceReady: function () {
    app.receivedEvent('deviceready');
    var readStatus = sessionStorage["readComplete"];
    alert("readComplete = " + readStatus);
    if (readStatus != "true") {
        app.readxml();
        sessionStorage["readComplete"] = "true";
    }
},

In app.readxml() I read all items + links in my datafile(XML) and add them to a ordered list in a div of Index.html page.

onDeviceReady seems to be getting called each time page loads ( like navigating back). Reading same page for each page load and rebuilding seems redundant since once we read, the page should remember how it was built and controls have their old data in them.So, I store the reading xml status in sessionStorage so that i dont readxml and rebuild page each time.
2) when user clicks on a link in the list, navigate them to a page1.xml
3) when clicks back button, bring them back to Index.html
Problem at #3 --> when user comes back to first page ( index.html), at that time readStatus == true,  the Index.html is showing blank.
Question --> how can I maintain state of index.html ( with data populated from reading xml) so that I dont have to rebuild page on each navigation back.
Any help is appreciated.

A: Whenever you open a new link (page.html) in Cordova, the previous page (index.html) will be destroyed, this behaviour depends on the system, iOS will sometimes cache previous pages and Android seems to always clear data right away.
If you want to avoid reloading the XML data, you can save it into the sessionStorage or localStorage (JSON is a good format). But the DOM has to be re-built whenever you go back to index.html, there will be a minor delay still.
A quick workaround to your problem could be creating an iframe within index.html to load page.html. Or a floating DIV layer on top of index.html using Ajax to load page.html. Both approach will work fine, assuming your index.html and page.html isn't too resource consuming.

A: data-dom-cache="true"

use this in your html tag. for more infromation follow this...http://demos.jquerymobile.com/1.2.0/docs/pages/page-cache.html


text:
Q: Do "good for you" and "I am happy for you" have a negative or positive connotation? I am not sure if this is the right place, but I was wondering if "good for you" and "I am happy for you" have a negative or positive connotation.

A: At face value, and taken literally, these are both positive.
Both can also be said sarcastically or with self-pity, and in that sense they could be negative.

A: I think they are both pretty positive. I never heard people use them in a negative way.


text:
Q: NullPointerException when setting text of TextView I am trying to make a simple game. When I am trying to set the text of 3 TextViews I get a NullPointerException.
public class MainActivity extends Activity implements View.OnClickListener {

private void initRound() {
    countdown = 10;

    ViewGroup container = (ViewGroup) findViewById(R.id.container);
    container.removeAllViews();
    WimmelView wv = new WimmelView(this);
    container.addView(wv, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    wv.setImageCount(8*(10 + round));

    fillTextView(R.id.points, Integer.toString(points));
    fillTextView(R.id.round, Integer.toString(round));
    fillTextView(R.id.countdown, Integer.toString(countdown*1000));
}

private void fillTextView(int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text);  //HERE DO I GET THE EXCEPTION
}

}

Here is the error from logcat:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.developer.nico.kissthefrognow, PID: 1940
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.developer.nico.kissthefrognow.MainActivity.fillTextView(MainActivity.java:80)
        at com.developer.nico.kissthefrognow.MainActivity.initRound(MainActivity.java:34)
        at com.developer.nico.kissthefrognow.MainActivity.newGame(MainActivity.java:21)
        at com.developer.nico.kissthefrognow.MainActivity.startGame(MainActivity.java:67)
        at com.developer.nico.kissthefrognow.MainActivity.onClick(MainActivity.java:58)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19749)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

And my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="@+id/rl">

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/container">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="000000"
        android:id="@+id/points"
        android:layout_gravity="left|top"
        android:textColor="@color/Red" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:id="@+id/round"
        android:layout_gravity="right|top"
        android:textColor="@color/Red" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00000"
        android:id="@+id/countdown"
        android:layout_gravity="center_horizontal|bottom"
        android:textColor="@color/Red" />
</FrameLayout>

Any ideas how to solve it? Thanks!

A: How about this. In onCreate get references for your TextViews:
public class MainActivity extends Activity implements View.OnClickListener {

    TextView tvPoints;
    TextView tvRound;
    TextView tvCountdown;

    protected void onCreate(Bundle savedInstanceState) {
        ....
        ....
        tvPoints = (TextView) findViewById(R.id.points);
        tvRound = (TextView) findViewById(R.id.round);
        tvCountdown = (TextView) findViewById(R.id.countdown);
        ....
        ....
    }

then in your initRound() do this:
fillTextView(tvPoints, Integer.toString(points));
fillTextView(tvRound, Integer.toString(round));
fillTextView(tvCountdown, Integer.toString(countdown*1000));

and in your fillTextView:
private void fillTextView(TextView tv, String text)  {
    tv.setText(text);
}

If this doesn't work, then the error is in some of these lines of code (try removing them and see if the code works):
    container.removeAllViews();
    WimmelView wv = new WimmelView(this);
    container.addView(wv, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    wv.setImageCount(8*(10 + round));

EDIT: As for "TextViews are empty" problem, you need to test stuff, for example:
Instead of tv.setText(text); try using something like tv.setText("10"); (just some random text). If setting the number "10" is working, then the issue is with the Integer.toString(...) part (for some unknown reason). If setting the number "10" is not working, then you should try setting the text in the initRound() method without using the fillTextView method (just to test if setting the text works at all), something like this:
private void initRound() {
    countdown = 10;

    tvPoints.setText("10");
    tvRound.setText("7");
    tvCountdown.setText("19");

    ViewGroup container = (ViewGroup) findViewById(R.id.container);
    container.removeAllViews();
    WimmelView wv = new WimmelView(this);
    container.addView(wv, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    wv.setImageCount(8*(10 + round));
}

If this works, then there is some issue with the WimmelView part of the code. And if setting the text still doesn't work, then the issue is probably where you call the initRound method, some code there is doing something that is affecting the TextViews...

A: Initialise your textviews in onCreate() first
public class MainActivity extends Activity implements View.OnClickListener {

private TextView tv1, tv2, tv3;
private void initRound() {
    countdown = 10;
ViewGroup container = (ViewGroup) findViewById(R.id.container);
container.removeAllViews();
WimmelView wv = new WimmelView(this);
container.addView(wv, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
wv.setImageCount(8*(10 + round));

this is required - this way Android finds view before using them

tv1 = (TextView) findViewById(R.id.points);
tv2 = (TextView) findViewById(R.id.round);
tv3 = (TextView) findViewById(R.id.countdown);

fillTextView(R.id.points, Integer.toString(points));
fillTextView(R.id.round, Integer.toString(round));
fillTextView(R.id.countdown, Integer.toString(countdown*1000));
}

private void fillTextView(int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text);  //HERE DO I GET THE EXCEPTION
}

}

this will solve your problem


text:
Q: Cannot invoke "this.firePropertyChange()" on JPanel reference Why can I not invoke firePropertyChange() on this reference?
    [javac] /home/thufir/NetBeansProjects/Legacy/src/legacy/gui/table/SelectTableFollowup.java:41: error: cannot find symbol
    [javac]                     this.firePropertyChange("client", null, i);
    [javac]                         ^
    [javac]   symbol: method firePropertyChange(String,<null>,int)
    [javac] Note: Some input files use unchecked or unsafe operations.
    [javac] Note: Recompile with -Xlint:unchecked for details.
    [javac] 1 error
    [javac] 1 warning

BUILD FAILED
/home/thufir/NetBeansProjects/Legacy/nbproject/build-impl.xml:923: The following error occurred while executing this line:
/home/thufir/NetBeansProjects/Legacy/nbproject/build-impl.xml:263: Compile failed; see the compiler error output for details.

Total time: 4 seconds
thufir@dur:~/NetBeansProjects/Legacy$

This is my code:
package legacy.gui.table;

import java.awt.BorderLayout;
import java.util.logging.Logger;
import javax.swing.JPanel;
import legacy.database.Queries;

public class SelectTableFollowup extends JPanel {

    private static final Logger log = Logger.getLogger(SelectTableFollowup.class.getName());
    private ClientsTable table;
    private Followup followup;
    private Select Select;
    private final Queries queries = new Queries();

    public SelectTableFollowup() {
        initComponents();
    }

    private void initComponents() {
        table = new ClientsTable();
        followup = new Followup();
        Select = new Select();
        setLayout(new BorderLayout());
        add(Select, BorderLayout.NORTH);
        add(table, BorderLayout.CENTER);
        add(followup, BorderLayout.SOUTH);
        followupButton();
        query();
        cannotFirePropertyChangeOnThisObj();
    }

    private void cannotFirePropertyChangeOnThisObj() {
        table.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                if ("client".equals(evt.getPropertyName())) {
                    String s = evt.getNewValue().toString();
                    int i = Integer.parseInt(s);
                    log.info("i is " + i);
                    this.firePropertyChange("client", null, i);
                }
            }

        });
    }

    private void followupButton() {
        followup.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                if ("followup".equals(evt.getPropertyName())) {
                    try {
                        int id = table.getId();
                        queries.send(id);
                        table.updateModel();
                    } catch (ArrayIndexOutOfBoundsException obe) {
                        log.info(obe.toString());  //no big deal
                    }
                }
            }
        });
    }

    private void query() {
        Select.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                if ("select".equals(evt.getPropertyName())) {
                    log.info(evt.getNewValue().toString());
                    table.select(evt.getNewValue().toString());
                }
            }
        });
    }
}

From Netbeans, I know that it's quite possible to invoke this.firePropertyChange(), for JPanel's which NetBeans creates.
How is the above class any different from a Netbeans generated class? Both extend the same base class.
If I've misused any terminology, please do let me know.

A: In this context:
table.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
    @Override
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
        ...
        this.firePropertyChange("client", null, i);
    }
}

The keyword this refers to the anonymous inner class generated when you create a new PropertyChangeListener instance. This fact is explained here: Using the this Keyword
Take a look to this topic: Keyword for the outer class from an anonymous inner class? You should replace this line for this one to refer to your panel class:
table.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
    @Override
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
        ...
        SelectTableFollowup.this.firePropertyChange("client", null, i);
    }
}

Or you can remove this and compiler will resolve the same for you:
table.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
    @Override
    public void propertyChange(java.beans.PropertyChangeEvent evt) {
        ...
        firePropertyChange("client", null, i);
    }
}

Given the anonymous inner class doesn't have any firePropertyChange() method, compiler will look up for the outer class (or eventually the hierarchy tree) and chek if it has such method, which is indeed the case.

A: I think the error happens in this method:
private void cannotFirePropertyChangeOnThisObj() {
    table.addPropertyChangeListener(new java.beans.PropertyChangeListener()

        @Override
        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            if ("client".equals(evt.getPropertyName())) {
                String s = evt.getNewValue().toString();
                int i = Integer.parseInt(s);
                log.info("i is " + i);
                this.firePropertyChange("client", null, i);
            }
        }

    });
}

You are invoking firePropertyChange() on the anonymous PropertyChangeListener object. The docs state that it does not declare the method firePropertyChange().
I think you want to invoke it on your SelectTableFollowup object. Then you would have to call it like this:
private void cannotFirePropertyChangeOnThisObj() {
    table.addPropertyChangeListener(new java.beans.PropertyChangeListener()

        @Override
        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            if ("client".equals(evt.getPropertyName())) {
                String s = evt.getNewValue().toString();
                int i = Integer.parseInt(s);
                log.info("i is " + i);
                SelectTableFollowup.this.firePropertyChange("client", null, i); // Reference this of the outer class
            }
        }

    });
}

Since PropertyChangeListener does not declare the method you could also just write firePropertyChange("client", null, i);.


text:
Q: Hibernate - Entity class having an attribute that is an interface I've researched this topic a bit and i'm either finding really old posts or questions that are not exactly what i'm trying to achieve.  I have used Hibernate for years now and I'd consider myself well versed in it.  I have used inheritance in my persistence layer before to represent orders with different types of orders as child classes (for a hospital system) to great results.
I am working on a new project which is for a store and i'm faced with an issue that I'm not sure if Hibernate can solve.  Basically I allow the user to construct Bill objects that contain info you'd expect in a bill : customer name, bill number, total amount, taxes, that kind of stuff.  Each Bill object contains a set of OrderedProduct objects which, in turn, contain a Product object and a quantity.  With only this requirement, my project is actually finished and everything works great.
My customer is now asking for an addition which I'm not sure how to tackle.  I am asked to allow the construction of Kit objects which are nothing but a set of Product objects with a price for both to offer discounts on certain things that are often bought together.  Piece of cake, i built a GUI to build and persist these objects but i now have an issue : How do i wire these Kit objects into a Bill?  My OrderedProduct objects are tied to a Product object currently and this model is obviously not compatible with this new requirement.
I can't use inheritance (to my knowledge) because a Kit is basically nothing but a list of Products with ONE reduced price.  If both these classes were to inherit from a common abstract class, how can one contain a set of the other one?
The way I STARTED to build this is with a Billable interface.  The dropdown that allows for product/kit selection uses the below code to populate itself :
items = FXCollections.observableArrayList(productService.findAllInInventory());

@Override
public List<Billable> findAllInInventory()
{
    List<Product> products = findProductsInInventory();
    List<Kit> kits = findKitsInInventory();

    List<Billable> billables = new ArrayList<>();

    billables.addAll(products);
    billables.addAll(kits);

    return billables;
}

This allows one dropdown to contain both types of entities while being completely seamless to the user.  I was getting pretty far into adapting the rest of the bill creation GUI with this concept until I realized : You can't have an attribute of an entity class be an interface type (again, to my knowledge).
Sorry for the long explanation and I hope what I'm trying to do is clear.  I can think of some (less than ideal) workarounds for this but if someone has an idea how to design this model I will gladly hear it!
Thanks

A: The conclusion is that you cannot have a persisted property of an entity class be an interface type.  If your design ends up requiring such structure, you will (for now) have to re-structure things.


text:
Q: Using files as an input in java I need my program to run by using "java RunProgram list" command, RunProgram is the name of the main class of my program and "list" is the text file I'm using. Question is, what do I need to do in my program in order for that to work?

A: java RunProgram list

So RunProgram will be the class and list will be the filename so you can get this file name in the main method as argument parameter and you can access it using args[0].
public static void main(String[] args) {
     String file_name = args[0];  //list pass in cmd will be set in file_name
}

A: Consider this java class:
import java.io.*;
Public Class RunProgram
{
    public static void main(String[] args)
    {
        String fileName = args[0];
        System.out.println(fileName);
        //Perform File Operation, whatever you want to perform.
    }
}

Now compile this java file by javac RunProgram.java
and run it by java RunProgram list.

A: You need to use the command line arguments. In your RunProgram class, you have a main method:
public static void main(String[] args)

This method takes in arguments (via String[] args), which you can use just like any other method.
There are many ways to handle the input, (BufferedReader, Scanner, etc.) but the general idea is to check if the argument is passed in by checking on
args[0] // The first String element in the argument

If it is not null or empty, then you would try to use that argument as a fileName input.


text:
Q: Bootstrap carousel - loop in javascript I am trying to use the bootstrap carousel, but cannot really get it to work. I have a list with pictures I want to loop through and show in the carousel. I cannot show all the pictures since the "activate" (line 3 in the text below) only should be applied for the first picture (and not for the other ones in the list). This mean that I need some kind of restriction regarding the "activate". Probably something like "only use activate for the first loop-through". I'm not quite sure how to write that. I'm writing in javascript (newbie) and having a really hard time incorporating it in the html file.

        {% for image in images %}

        {% endfor %}

A: You are using some template language here, I think Django.
You need to put class active in if block.
 {% if image in images is first %} active {% endif %}
 {% with %} {% endwith %}

I think you can use with syntax. This example is just logic you need to follow.
Just find the correct syntax. Other you do not need to change.


text:
Q: расстановка блоков внутри row Имеется ряд с 2 блоками:

1

2

Как сделать, что бы именно второй блок (с цифрой '2' внутри) при уменьшенном экране, то бишь в md размере был всегда сверху первого блока.

A: Блоки надо будет поменять местами и добавить col-<>-push-<> и col-<>-pull-<>.Примерно вот так:

2

1


text:
Q: How to Invoke a parameter in a batch file with comma-delimiter I want to invoke a batch file with a comma-delimited paramater.  How can I achieved this?
I want it like this example.
I have a text.bat with the script:
@echo off
set test=%1
echo Sample %test% batch.

I want to run the batch like this:
c:\text.bat this,is,sample

and I am expecting a result like this:
Sample this,is,sample batch.

Any idea how I could achieve this?
Thanks.

A: Wow!  I didn't know commas behaved that way.
You have two options.
You can use this script:
@echo off
set test=%~1
echo Sample %test% batch.

And run it with:
C:\text.bat "this,is,test"

The %~1 represents the first argument without quotes.  The quotes group the comma-delimited list as a single argument.
Or
You can use this script:
@echo off
set test=%*
echo Sample %test% batch.

And run it with:
C:\text.bat this,is,test

The %* represents the command line arguments as they were typed.

A: In Batch files the parameter delimiters are, besides spaces, comma, semicolon and equal sign, so there is no direct way to do that. The only option is to enclose the parameter between quotes: c:\text.bat "this,is,sample" and take the parameter with %~1 to eliminate the quotes: set test=%~1.


text:
Q: How to make an iOS VoIP app obey Do Not Disturb when ringing? One would think it would be essential for a VoIP app to obey the same rules as the stock phone app but it turns out to be almost impossible to implement ringing correctly. Several things I tried:

*

*Local push notifications with ring sound.
Good: obeys both Silent and DND modes.
Bad: the sound can be no longer than 30 seconds, and it only vibrates once when the notification appears. So to achieve the ringing effect the notification has to be re-pushed e.g. every 6 seconds, effectively spamming the notification center. Also push notifications do not sound/vibrate if the app is active so the app has to detect that and ring differently.

*AudioServicesPlayAlertSound().
Good: proper API seemingly designed specifically for this task. Obeys silent mode.
Bad: completely ignores Do Not Disturb mode, the sound and vibration come right through.

*Use AVFoundation to play the ring sound.
Good the sound plays.
Bad: does not support vibration, does not support silent/DND modes. Essentially not usable as a ringer.
Is there a better way? Or did Apple completely miss this use case?

A: As you say in your 3 options, only a UILocalNotification actually obeys silent/DND mode.
The problems with it can be solved.
Spamming the notification center: I think that works quite well. You can cancel your previous notification immediately before you fire off a new one, so there will always be only 1 outstanding notification.
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Vibration problem: You should be able to call this: AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); in the same place where you call your local notification over and over again with a timer until the call ends or the users acknowledges the call. With the VOIP background setting on it should work in the background.
As you stated in option 2 the vibrate will not follow DND mode, but it's just vibration. If you spam the notification center that will vibrate once every time the notification comes in so you may not need to explicitly start vibrating if that's enough for you.
Good luck.


text:
Q: css margin unexpected behaviour on block element Suppose I have the following html code

and the following css applies to it
.f1 {
    width: 200px;
    height: 200px;
    background: #fff;
    margin: 5em auto;
}

.f2 {
    background: #000;
    width: 100px;
    height: 100px;
    margin: 20px;  // this doesn't work
}

Then I saw a strange behaviour that margin-top property doesn't apply on class .f2. I don't why but when I add some padding or border on class f1 then it work. Can you please explain this?

A: Your problem is collapsing margins, check http://www.w3.org/TR/CSS2/box.html#collapsing-margins
You could add a padding to .f1 instead of the margin from .f2.


text:
Q: Add JavaScript to NewForm for SPList in SharePoint I have a SPList in SharePoint that I want to edit the NewForm.aspx for. I want to add a few JavaScripts as WebParts to the form programmatically.
How do I do that?
Thanks for helping.

A: Open the list in SharePoint designer in the "lists and libraries" section. In the list designer view you will see a list of forms associated with the list, there will generally be a  "NewForm.aspx" form listed. Right click this and then select "Edit File in Advanced Mode" to expose the ASP .Net / HTML markup used for the form.
Now, add your custom  block within the page markup. I'd generally recommend that you find the asp:content element with id 'PlaceHolderMain'. Add your script as the first element immediately after the content placeholder element opens like:
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<script type='text/javascript' language='javascript'>
$(document).ready(function(e) { alert('my custom script has loaded'); });
</script>
..
.. Existing markup
..
</asp:Content>

My example above assumes you have jQuery present in your masterpage to display the message after the form has fully loaded.

A: If you don't want to (or can't) use SharePoint Designer you can put
?ToolpaneView=2
on the end of the URL to open the View/Edit/new form in design mode in the browser.
http://blog.pentalogic.net/2010/07/how-to-edit-list-forms-sharepoint-2010/


text:
Q: What is meant by gluing two metric spaces together? "Gluing" constructions are common in topology: by gluing two disks along their boundaries we get a sphere; by gluing a cylindical "handle" to a sphere we get a torus, and so forth.
If the original spaces have a metric in addition to topology, when and how do these metrics carry over to the result of gluing? What are the compatibility conditions required for the glued space to have a metric of its own?

A: To perform the gluing, we need:

*

*two metric spaces $X$ and $Y$

*a set $A\subset X$, this is the part of $X$ covered in glue

*an isometric embedding $f:A\to Y$, which is a way to put the glue-covered part of $X$ over $Y$.

After we firmly press the spaces together and let them sit for a while, a point $x\in A$ becomes identical with the point $f(x)\in Y$. The resulting space can be described as the quotient $(X\sqcup Y)/(x\sim f(x))$. It is usually denoted $X\cup_A Y$. Its metric is the standard quotient metric; however, in this case the formula for quotient metric can be simplified to
$$
\tilde d(p,q) = \begin{cases}
d_X(p, q) & \mbox{if } p, q \in X \\
d_Y(p, q) & \mbox{if } p, q \in Y \\
\inf_{a\in A} [d_X(p, a)+d_Y(q, f(a))] & \mbox{if } p \in X \mbox{ and } q \in Y \\
\inf_{a\in A} [d_Y(p, f(a)) + d_X(q, a)] & \mbox{if } p \in Y \mbox{ and } q \in X
\end{cases}
$$
A simple example to start with: $X=(-\infty,0]$, $A=\{0\}$, Y=$[0,\infty)$, $f(0)=0$. This means we glue two half-lines together at point $0$. The result is  $\mathbb R$ with the standard metric.
Another example:  glue two closed disks of the same radius along their boundaries. This means $A$ is the boundary of one disk, and $f(A)$ is the boundary of the other. The resulting space is homeomorphic to a sphere, though the metric on each disk is still flat. It's like a sphere that someone sat on.


text:
Q: geocoder connection reset by peer I tried to execute this code:
from geopy.geocoders import GoogleV3
point = '51.523910, -0.158578'
geolocator = GoogleV3()
address = geolocator.reverse(point)

I get this error:
error: [Errno 104] Connection reset by peer

I am executing this inside a vagrant machine but when I execute this on my local machine it works !!!

A: This is a recent issue of VirtualBox(which is the most probable provider of your vagrant) setting incorrect checksums when networking is set to work as NAT.
Possible decisions are:

*

*use bridge networking instead of NAT

*update your VirtualBox to a recent test build (5.1.9 helped in my case)

You can read more at VirtalBox issues on their tracker here and here


text:
Q: Identifying semidirect products-groups of order 28 So, I'm very new to working with semi-direct products.  I'm working on my algebra qual prep, and one of the questions was to identify all the groups of order 28.  I'm pretty sure I have the answer...the only problem is I'm not sure just what two of the groups look like!
So,  starting with the sylow subgroups, I have that $n_2|7$ and $2|(n_2-1)$,  so we have $n_2=1$ or $n_2=7$.  Similarly, $n_7|4$ and $7|(n_7-1)$, so $n_7=1$, thus the Sylow 7 subgroup is unique, and therefore normal,  hence our group G is a semidirect product of its Sylow 2 subgroup and its sylow 7 subgroup.
The two possibilities for the Sylow 2 subgroup are $\mathbb Z _2 \times \mathbb Z _2$ or $\mathbb Z_4$.  Neither are eliminated by a counting argument.  So, I'm looking for homomorphisms from the sylow 2 subgroup to the automorphism group of the sylow 7 subgroup, which is isomorphic to $\mathbb Z_6$
Case 1:  The sylow 2 subgroup is $\mathbb Z_2 \times \mathbb Z_2$.  The generators are $(0,1)$ and $(1,0)$.  These each have order 2, so the images must have order $1$ or $2$. So the images are either $0$ or $3$.  If the images of both are $0$, we have the trivial homomorphism, so this is actually a direct product and we have the abelian group $\mathbb Z_2 \times \mathbb Z_2 \times \mathbb Z_7$
Now, say $(1,0)$ goes to $3$ and $(0,1)$ goes to $0$.  Then $(1,1)$ goes to 3.  Similarly, we have as a case $(0,1)\to 3,(1,0)\to 0,(1,1)\to 3$ and $(1,0)\to 3,(0,1)\to 3,(1,1)\to 0$.  All of these are identical up to isomorphism as they send 2 indistinguishable elements to the same thing and the other to the identity, so up to isomorphism there is only one such semidirect product...
Here's where I'm stuck, I don't know what this group is, what it looks like!  How do I figure that out?
Case 2: The sylow 2 subgroup is $\mathbb Z_4$. Here we just have one generator, $1$, and it can go to either $0$ or $3$ as above.  If $0$ we have the abelian case.  What does the nonabelian case look like?

A: This previous answer discusses how to find a presentation for a semidirect product. In this case, your first semidirect product has presentation
$$
\langle a,b,c \mid a^2=b^2 = (ab)^2 = c^7=1,aca^{-1}=c^{-1},bcb^{-1}=c\rangle
$$
Here we have used the fact that $c\mapsto c^{-1}$ is the automorphism of $\mathbb{Z}_7$ of order two.
From this presentation, we can see that $b$ commutes with $a$ and $c$, so the group is a direct product of $\langle b\rangle$ and $\langle a,c\rangle$:
$$
\langle b \mid b^2 =1 \rangle \times \langle a,c\mid a^2=c^7=1,a^{-1}ca = c^{-1}\rangle \;\cong\; \mathbb{Z}_2\times D_7.
$$
This is actually the same as $D_{14}$, since $bc$ has order $14$ and $a^{-1}(bc)a = (bc)^{-1}$.  (In general $\mathbb{Z}_2 \times D_n \cong D_{2n}$ when $n$ is odd.)
The other group is given by a similar presentation:
$$
\langle x,y \mid x^4 = y^7 = 1,xyx^{-1}=y^{-1}\rangle
$$
Note that this is not $D_{14}$, since $D_{14}$ has no elements of order $4$.  It is the dicyclic group of order 28.


text:
Q: Mapping Data Flows Dynamic Column Updates I have a text input source. This has over 100 columns so I won't show all of them here - a cut-down view of the data would be:

CustomerNo
DOB
DOD
Status

01418495
01/02/1940
NULL
1

01418496
01/01/1930
NULL
1

The users want to be able to update/override any of these columns during processing by providing another input text file containing the PK (CustomerNo) and the key/value pairs of the columns to be updated e.g.

CustomerNo
Variable
New Value

01418495
DOB
01/12/1941

01418496
DOD
01/01/2021

01418496
Status
0

Can this data be used to create dynamic columns somehow that update the customer records regardless of the columns they want to update - in the example above this would result in:

CustomerNo
DOB
DOD
Status

01418495
01/02/1941
NULL
1

01418496
01/01/1930
01/01/2021
0

I have looked at the documentation but don't see any examples of how something like this could be achieved? Thanks in advance for any advice.

A: You would use a technique similar to what I describe in this video: https://www.youtube.com/watch?v=q7W6J-DUuJY. What I've done is created a file with rules that have expressions and then apply those rules dynamically inside of my data flow.
The key to make this work is using the expr() function to dynamically evaluate the expression from the external file.


text:
Q: Copying data from one column to another table in a separate database on the same server I am trying to figure out how to copy the data in one column back over to another table on the same server but in a separate database.
This will be done after performing an Entity Framework migration. I have tested it pretty thoroughly and know it will update the database schema correctly, but because of various reasons there is a column that will lose all of its data.
I have the original database (pre-EF migration) backed up and have created a duplicate database on the same server that I have restored that .bak file to.
What I am now trying to do is copy all of the data from the column in the backed up table (that gets cleared in the migration) back over to the post-migration table.
Here is the query I have so far:
UPDATE [PostMigDB].dbo.Issues
SET Branch = [PreMigDB].dbo.IssueBranches.Branch
WHERE [PostMigDB].dbo.Issues.Id = [PreMigDB].dbo.IssueBranches.IssueId

But in the Query Editor, both expressions starting with [PreMigDB] are underlined in red and when I hover my mouse over them it reads:

The multi-part identifier [PreMigDB].dbo...  could not be bound

Almost everything I have read online says this should be possible, but I cannot figure out why it won't work for me. Thank you all.

A: Try changing your join logic.
UPDATE i
SET Branch = b.Branch
FROM [PostMigDB].dbo.Issues i
INNER JOIN [PreMigDB].dbo.IssueBranches b ON b.IssueId = i.Id


text:
Q: Can I assign a variable to a variable which is assigned to a Class instances? - Python Question I'm creating a text-based game and I've been having this problem that I don't know how to solve...
class Enemy:
    def __init__(self, hp, maxHp, attack, defense):
        self.maxHp = 100
        self.hp = self.maxHp
        self.attack = 5
        self.defense = 1
# --- Now we just create the two different enemies from this class --- #
tutoEnemy1 = Enemy(100, 100, 5, 1)
tutoEnemy2 = Enemy(100, 100, 5, 1)

Here is the code involved with the problem. I assigned two variables to the Class instances to obtain two separate enemies. One called tutoEnemy1 and other called tutoEnemy2
In the code of the game, the section which contains the fight functions of course has one which involves attacking the enemy. I originally thought that by creating two separate 'if' statements, the moment in which you select the enemy you'd like to attack everything would go ok but then I realised that in the moment that more than 2 enemies appeared I had lots of garbage, repeated code involving the process of calculating the damage and all that stuff.
I came with an idea that consisted on defining a function which realized the damage calculation process everytime, that way I didn't had to repeat any code
def damage():
    option = input("> ")
    if option == 1:
        selectedEnemy = tutoEnemy1()
    elif option == 2:
        selectedEnemy = tutoEnemy2()
    else:
        input("Incorrect input, type a correct one.")
        damage()
    rawDamage = Player.attack * multiplierDamage
    finalDamage = rawDamage - selectedEnemy.defense
    selectedEnemy -= finalDamage

The problem comes that originally I assigned the Enemy class instances to the "tutoEnemy1&2" variables and everything worked fine. But now, it gives me the problem that the variable of "selectedEnemy" doesn't seem to work the way I intended (taking the info of one enemy or the other).It just gives me this error:
Traceback (most recent call last):
  File "c:\Users\acmem\Desktop\Text-Based Game\RPG.py", line 75, in <module>
    selectedEnemy = tutoEnemy1()
TypeError: 'Enemy' object is not callable

Is there a way to do so? If so, what is the correct sintax? (I work with Python 3.0)

A: To assign a reference of either tutoEnemy1 or tutoEnemy2 to 'selectedEnemy' you should drop the brackets, as they are the standard syntax of calling a function.
As tutoEnemy1 and tutoEnemy2 are not callable (=not functions), this error is thrown.
So the code should look like this:

def damage():
    option = input("> ")
    if option == 1:
        selectedEnemy = tutoEnemy1
    elif option == 2:
        selectedEnemy = tutoEnemy2

You may get a problem with your last statement though, as you try to subtract the damage from the selectedEnemy instance and not from their HP, so you probably want something like this:
    selectedEnemy.hp -= finalDamage


text:
Q: How to check if a value exists already in a Firebase and get key in android In my android application, when the user logs in, I need to check my realtime database to determine if the users ID exists within this database. Once the users ID has been located, i then need to retrieve the parent node of this ID in order to determine if the user logging in is a customer or employee. I'm having some difficulties coding this, as i'm relatively new to using firebase.
Here is my code so far:
final String user_id = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener eventListener = new ValueEventListener()
{
    @Override
    public void onDataChange(DataSnapshot dataSnapshot)
    {
        for(DataSnapshot ds : dataSnapshot.getChildren())
        {
            if(ds.child(user_id).exists())
            {
                //check if employee or customer?
                String cust_or_emp =  ds.child(user_id).getKey();
                Log.d("test1",String.valueOf(ds.child(user_id).getKey()));
                if (cust_or_emp.equals("Customers"))
                {
                            name= Objects.requireNonNull(ds.child(user_id).child("User_Information").child("firstName").getValue()).toString();
                            Log.e("first name is ", "firstname :" + name);
                            toNextActivity = new Intent(getActivity(), MainActivity.class);
                            toNextActivity.putExtra("name",name);
                            Log.e("2first name is ", "firstname :" + name);
                            progressBarLayout2.setVisibility(View.GONE);
                            Objects.requireNonNull(getActivity()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                            Objects.requireNonNull(getActivity()).startActivity(toNextActivity);
                            getActivity().finish();
                } else if (cust_or_emp.equals("Employee")) {
                    //code for if the key is employee
                }
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError)
    {
        Log.d("error", databaseError.getMessage()); //Don't ignore errors!
    }
};
rootRef.addListenerForSingleValueEvent(eventListener);

Currently when I run my application, nothing appears to happen.

A: You're attaching a value listener to the root of your database. Then in your onDataChange you loop over the child node, which means that your ds snapshot is for the Users node, while you seem to think it's for the Employee and Customers node.
The fix should be to listen to the Users node instead:
rootRef.child("Users").addListenerForSingleValueEvent(eventListener);

Your current approach is highly inefficient, as (even when you fix the above) you're loading the entire Users node to check if a specific user exists in there. As you add more users to the app, this means you're loading more and more data, without using it.
A better approach is to check whether the specific user exists under each specific node:
rootRef.child("Users/Employee").child(user_id).addListenerForSingleValueEvent(new new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            ... handle the Employee
        }
        else {
            rootRef.child("Users/Customer").child(user_id).addListenerForSingleValueEvent(new new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists()) {
                        ... handle the Customer
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}


text:
Q: SPF Hard Fail still getting to mailbox We had some problems with spoofing, so we had to add all the security checks on the DNS, one of them was the SPF records, first we just added it as a softFail
"~all"  and the emails were going to the Spam folder, thats good, on the email headers you can see the SPF did not pass and it gets classified as a softfail.
Received-SPF: softfail
We changed it to a Hard Fail using "-all"
I'm not sure if I'm just getting it wrong, but this is suppose to make it reject the email right? so the user shouldn't even get it correct?, we are still getting it, but now it says
Received-SPF: fail (google.com: domain of info@xxxxx.xxx does not designate xx.xx.xxx.xxx as permitted sender) client-ip=xx.xx.xxx.xxx;
Authentication-Results: mx.google.com;
       spf=hardfail (google.com: domain of info@xxxx.xxx does not designate xx.xx.xxx.zzz as permitted sender)
Meaning it is a hard fail but I'm still getting it, is that correct?, shouldn't it be completely rejected?

A: The SPF is telling the receiving MTA that the check is a fail.  However, it is up to the receiving MTA what it does next.  Quite possibly, the receiving MTA in this case is not configured to reject emails with a hard fail on the SPF check.  I have seen several mail systems deliberately configured to treat both soft and hard SPF fails as a warning, and to tag them and deliver to the spam folder.
If you have DMARC as well, then that may be configured to recommend a behaviour, but again it is up to the receiving MTA if it acts on it.


text:
Q: Python, Tkinter: how can I prevent tkinter gui mainloop crash using threading Hi I have a small python gui interface with two buttons, start(That starts a counter) and stop (that is suppose to stop the counter), the counter is an infinite loop since I do not want it to end unless the second button is clicked. The problem is the second button cannot be clicked while the function from the first one is still running.
I read that I need to use threading and I have tried but I do not fully understand how I can do this. Please help.
from Tkinter import *
import threading

class Threader(threading.Thread):
    def run(self):
        for _ in range(10):
            print threading.current_thread().getName()

    def main(self):
        import itertools
        for i in itertools.count(1, 1):
            print i

    def other(self):
        print "Other"

m = Threader(name="main")
o = Threader(name="other")

try:
    '''From here on we are building the Gui'''
    root = Tk()

    '''Lets build the GUI'''
    '''We need two frames to help sort shit, a left and a right vertical frame'''
    leftFrame = Frame(root)
    leftFrame.pack(side=LEFT)
    rightFrame = Frame(root)
    rightFrame.pack(side=RIGHT)
    '''Widgets'''
    '''Buttons'''
    playButton = Button(leftFrame, text="Play", fg="blue", command=m.main)
    stopButton = Button(rightFrame, text="Stop", fg="red", command=o.other)
    playButton.pack(side=TOP)
    stopButton.pack(side=BOTTOM)

    root.mainloop()
except Exception, e:
    print e

A: Here's a short example of using threading. I took out your other function and I don't know why your using itertools here. I took that out as well and simply setup using a simple threading example.
A few things:
You setup using threading.Thread as the base class for Threader, but you never actually initialized the base class.
Whenever you use threading you generally want to define a run method and then use start() to start the thread. Calling start() will call run.
You need to use threading to prevent your GUI blocking, because tkinter is just one thread on a giant loop. So, whenever you have some long running process it blocks this thread until the current process is complete. That's why it's put in another thread. Python has something called the GIL, which prevent's true parallelization (I made up that word) since it only one thread can ever be used at a time. Instead, it uses time slicing, the GIL sort of "polls" between them to give the appearance of multiple tasks running concurrently. For true parallel processing you should use multiprocessing.
In the below code I have used self.daemon = True. Setting the thread to be a daemon will kill it when you exit the main program (In this case the Tk GUI)
from tkinter import *
import threading, time

class Threader(threading.Thread):

    def __init__(self, *args, **kwargs):

        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True
        self.start()

    def run(self):

         while True:
            print("Look a while true loop that doesn't block the GUI!")
            print("Current Thread: %s" % self.name)
            time.sleep(1)

if __name__ == '__main__':

    root = Tk()
    leftFrame = Frame(root)
    leftFrame.pack(side=LEFT)
    rightFrame = Frame(root)
    rightFrame.pack(side=RIGHT)
    playButton = Button(leftFrame, text="Play", fg="blue",
        command= lambda: Threader(name='Play-Thread'))
    stopButton = Button(rightFrame, text="Stop", fg="red",
        command= lambda: Threader(name='Stop-Thread'))
    playButton.pack(side=TOP)
    stopButton.pack(side=BOTTOM)
    root.mainloop()

A: For something as simple as a counter, Tkinter's after() method is usually a better choice.  You can use an instance variable to set it to on and off.
class TimerTest():
    def __init__(self, root):
        self.root=root

        Button(root, text="Play", fg="blue",
                            command=self.startit).grid(row=1, column=0)
        Button(root, text="Stop", fg="red",
                            command=self.stopit).grid(row=1, column=1)

        self.is_running=True
        self.count=IntVar()
        Label(root, textvariable=self.count,
              bg="lightblue").grid(row=0, column=0, columnspan=2, sticky="ew")

    def startit(self):
        self.is_running=True
        self.increment_counter()

    def increment_counter(self):
        if self.is_running:
             c=self.count.get()
             c += 1
             self.count.set(c)
             root.after(1000, self.increment_counter)  ## every second

    def stopit(self):
        self.is_running = False

root = Tk()
TT=TimerTest(root)
root.mainloop()


text:
Q: I get this Quota error for 'logging.googleapis.com/read_requests' What is the exact limit to increase in GCP to get rid of this error ?
{
  "error": {
    "code": 429,
    "errors": [
      {
        "message": "Insufficient tokens for quota 'logging.googleapis.com/read_requests' and limit 'ReadRequestsPerMinutePerUser' of service 'logging.googleapis.com' for consumer 'project_number:225258829199'.",
        "domain": "global",
        "reason": "rateLimitExceeded"
      }
    ]

A: Probably you are hitting the 20 QPS max requests quota. Try checking how many read/write requests you've been doing. It's unlikely this will get increased.
https://console.cloud.google.com/apis/api/compute.googleapis.com/quotas?project=<INSERT MY PROJECT NUMBER>&duration=P30D


text:
Q: Random Partitions Show Up-I Didn't Create Any The Partitions
Essentially what happened is that I purged python3 and reinstalled it. That's literally all that happened.
Along with the weird partitions, terminal, Firefox, and Gnome Software uninstalled themselves. (I've manually reinstalled them, so that's ok now)
What's going on with this?


text:
Q: How to add two pages in xamarin.forms shell in code behind I want to add dynamically two pages (ShellContents) into my LoginShell, but LoginShell.Current is always null?
    {
        public LoginShell(string page = null)
        {
            InitializeComponent();

            ShellItem si = new ShellItem();

            LoginShell.Current.Items.FirstOrDefault().Items.Add(new ShellContent {ContentTemplate = new DataTemplate(typeof(SignUpPage))});

        }
    }

LoginShell.Current is a read-only property.
Update
I implemented following code for my StartUpShell class:
    public partial class StartUpShell : Shell
    {
        public StartUpShell(string page)
        {
            InitializeComponent();

            ShellContent content;

            if(page == nameof(SignUpPage))
            {
               content = new SignUpPage();
            }
            else if(page == nameof(LoginPinPage))
            {
                content = new LoginPinPage();
            }
            else
            {
                content = new SignUpPage();
            }

            ShellSection shellSection = new ShellSection();
            shellSection.Items.Add(new ShellContent() { Content = content });

            CurrentItem = shellSection;
        }

but on when I set content variable it crashes with a message:
ShellContent Content should be of type Page. Title , Route D_FAULT_ShellContent4

A: If you want to do this in C#, you could try the code below.
public partial class AppShell : Xamarin.Forms.Shell
{
    public AppShell()
    {
        InitializeComponent();
        ShellSection shell_section = new ShellSection
        {
            Title = "home",
        };

        shell_section.Items.Add(new ShellContent() { Content = new ItemsPage() });

        ShellSection shell_section1 = new ShellSection
        {
            Title = "about",

        };

        shell_section1.Items.Add(new ShellContent() { Content = new AboutPage() });

        myshell.Items.Add(shell_section);
        myshell.Items.Add(shell_section1);
    }
}

x:Name="myshell" is the name of Shell.
Here is running GIF.

update
If you type of LoginShell is Xamarin.Forms.Shell, You want to replace current page with your needs, you can use following code.
    public partial class AppShell : Xamarin.Forms.Shell
    {
        public AppShell()
        {
            InitializeComponent();

            ShellSection shell_section1 = new ShellSection
            {
                Title = "Page1",

            };

            shell_section1.Items.Add(new ShellContent() { Content = new Page1() });

            CurrentItem = shell_section1;

        }
    }

Here is running screenshot.

If you want to hide the navigation bar. you can add Shell.NavBarIsVisible="false" in your ContentPage. Here is code about adding it in page1.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
            Shell.NavBarIsVisible="false"
             x:Class="App18.Views.Page1">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>


text:
Q: Element type is invalid: expected a string with FlatList Iam new to react-native, and are playing around with UI Kitten (https://akveo.github.io/react-native-ui-kitten/)
It has a default ChatListScreenBase that renders a list. It looks like this:
import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  ListView
} from 'react-native';

import ThemeService from '../util/ThemeService';
import api from '../util/ApiMock';

export default class ChatListScreenBase extends Component {

  constructor(props) {
    super(props);
    let ds = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    let data = api.getUserMsgList(api.userId);

    this.state = {
      dataSource: ds.cloneWithRows(data)
    };
  }

  render() {
     let Header = ThemeService.getChatListHeaderComponent();
    return (
      <View style={styles.container}>
        <Header/>
        <ListView
          style={styles.list}
          automaticallyAdjustContentInsets={false}
          dataSource={this.state.dataSource}
          renderRow={(row) => this._renderMsgItem(row)}
        />
      </View>
    )
  }

  _renderMsgItem(msg) {
    let user = api.getUserInfo(msg.from);
    let ChatItem = ThemeService.getChatItemComponent();
    msg.text = msg.text.length > 25 ? msg.text.substring(0,23)+'...' : msg.text;
    return (
      <ChatItem
        user={user}
        message={msg}
        onClick={(user) => this._openChat(user)}
      />
    );
  }

  _openChat(user) {
    this.props.navigator.push({
      screen: ThemeService.getChatScreen(true),
      passProps: {
        userId: user.id
      }
    });
  }
}

const styles = StyleSheet.create({
  container:{
    flex: 1,
  },
  list: {
    paddingTop: 10
  },
});

I would like to substitute the data this screen renders, with my own code, like this:
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList
} from 'react-native';

import ajax from '../util/ApiMock';

export class ChatListScreenBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      themeIndex: ThemeService.getCurrentThemeIndex()
    }
  }

  state = {
    data: []
  }

  async componentDidMount() {
    const data = await ajax.getDataTest();
    this.setState({data});
  }

  render() {
    return (
      <View style={styles.container} >
        <Text style={styles.h2text}>
          Black Order
        </Text>
          <FlatList
          data={this.state.data}
          showsVerticalScrollIndicator={false}
          renderItem={({item}) =>
          <View style={styles.flatview}>
            <Text style={styles.name}>{item.title}</Text>
          </View>
          }
          keyExtractor={item => item.title}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  h2text: {
    marginTop: 10,
    fontFamily: 'Helvetica',
    fontSize: 36,
    fontWeight: 'bold',
  },
  flatview: {
    justifyContent: 'center',
    paddingTop: 30,
    borderRadius: 2,
  },
  name: {
    fontFamily: 'Verdana',
    fontSize: 18
  },
  email: {
    color: 'red'
  }
});

When I do this, I keep getting this error:
"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of ChatListScreenBase."
I think that the problem is with the <FlatList>, but I'am not sure what type its expecting?
When I call the webservice it returns:

{"users":[{"_id":"5d0fcd8fe1dbfd7c23424e09","title":"180710","type":1,"published":"5"},{"_id":"5d0fcd8fe1dbfd7c23424e0a","title":"180705","type":3,"publiched":"5"},{"_id":"5d0fcd8fe1dbfd7c23424e0b","title":"Mr.
  Nick","type":2,"publiched":"5"}]}

Kind regards.

A: For the looks of your API response you are setting data as object with key users and then trying to loop over it.
Instead update componentDidmount:
 async componentDidMount() {
    const resp = await ajax.getDataTest();
    this.setState({ data: resp.users });
  }


text:
Q: Why implication can only be in one way for a sentence in Propositional Logic? Consider the English sentence:

If a person is cool or funny, then he is popular.

We have c for cool, f for funny and p for popular.
I don't see why the above sentence can only be written as c v f => p in propositional logic. If a person is cool or if a person is funny then it must be the case that the person is popular, I understand that.
But can't I also write it as p => c v f?
Just as I writing this I realized there could be other ways he can become popular. Is this the reason why we can't write p => c v f for this sentence?

A:
Just as I writing this I realized there could be other ways he can become popular. Is this the reason why we can't write $p \to c \lor f$ for this sentence?

That's exactly it. The statement $p\to c\lor f$ means "If the person is popular, then he is either cool or funny". This excludes, for example, the possibility that the person is popular for being attractive.

A: When we write
$$P \implies Q $$
We mean that, whenever $P $ happens, $Q $ must happen. For example, whenever I watch a horror movie ($P $), I get scared like hell ($Q $).
So we have
$$P \implies Q $$
But can I also automatically write
$Q \implies P $?
It depends! Is it the case that, whenever I get scared, I am watching a horror movie? Hell no! Sometimes friends hide behind doors and whatnot to scare me, and in those cases $Q $ happens, but $P $ doesn't happen. It is the same in your case.
If you could write $Q\implies P $ whenever you have $P\implies Q $ then you would always have $P \iff Q $, meaning that $P $ and $Q $ always happen together. Which is not the case.

A: $c \lor f \implies p$ says that if a person is cool or funny, then he is popular.
$p \implies c \lor f$ says that if a person is popular, then he is cool or funny.
This is not the same as the original statement (as the original statement does not restrict popularity to only being funny or cool).
However, if we have: a person is popular if and only if he is cool or funny, then we can write $c \lor f \iff p$.


text:
Q: MySQL nested case procedure using concat I'm doing a nested case. However, I am getting an error near this line:
else
        select concat('The month parameter ', p_month, ' is invalid; cannot proceed.');

This is actually the else case for the most inner case. p_month is an IN parameter and also an integer. Could this be the error?
Any thoughts will be helpful. Thank you.

I played around with it a little bit more right now. So I decided to SELECT on the outside block. However, I know now I have an error for the Select statement in the inner block. How can I fix that? Thanks.
entire code:
Create procedure ExamFeesMonth(in p_cl_id int, in p_month int)
begin
    declare count_cl_id int;
    declare num_exam int;
    declare count_exam int;
    declare v_msg varchar(200);

    -- check if p_cl_id is in vt_clients
    select count(*) into count_cl_id from vt_clients where cl_id = p_cl_id;

    -- count the number of exams that has happened in p_month of previous year
    select count(*) into num_exam
    from vt_clients cl
        join vt_headers h on cl.cl_id = h.cl_id
        join vt_details d on h.ex_id = d.ex_id
    where cl.cl_id = p_cl_id
        and month(ex_date) = p_month
        and year(ex_date) = (year(current_date())-1)
    ;

    select
    -- first case block starts
    case
    -- client valid
    when count_cl_id = 1 then

        -- second case block starts
        case
        -- p_month valid
        when p_month in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) then

            -- third case block starts
            case
            -- existing exams
            when count_exam >= 1 then
                select concat( 'Client ', p_cl_id, ' has ', count(h.ex_id),
                                ' exam(s) with total fees of ', sum(ex_fee),
                                ' in ', year(current_date())-1, '-', p_month)
                from vt_clients cl
                    join vt_exam_headers h on cl.an_id = h.an_id
                    join vt_exam_details d on h.ex_id = d.ex_id
                where cl_id = p_cl_id
                    and year(ex_date) = (year(current_date())-1)
                    and month(ex_date) = p_month
                ;
            -- no exams
            when count_exam = 0 then
             concat( 'No exams for client ',  p_cl_id, ' in 2011-' , p_month, '.');

            -- third case block ends
            end

        -- p_month invalid
        else
             concat('The month parameter ', p_month, ' is invalid; cannot proceed.');

        -- second case block ends
        end

    -- client invalid
    when count_cl_id = 0 then
    concat('We have no client with id ', p_cl_id, '; cannot proceed.') ;

    -- first case block ends
    end case;

end;
#

A: I think the issue in END statements in the nested CASEs. You should use END CASE. CASE...END CASE
       -- third case block ends
        end case;  --  <-------------here

    -- p_month invalid
    else
         concat('The month parameter ', p_month, ' is invalid; cannot proceed.');

    -- second case block ends
    end case; --  <-------------and here


text:
Q: characterization of costant functions in $\mathbb{C}$ Are costant functions, say $f$, in $\mathbb{C}$ characterized by $f'(z)=0$  $\forall z \in \mathbb{C}$?
$f'(z)$ denotes the complex number such that $$ f(z+h)-f(z)=f'(z)h +o(\mid h \mid)$$ is valid.
Or equivalently $$f'(z) = \lim_{h \to 0} \frac{f(z+h)-f(z)}{h}$$
I asked this mainly because I don't think there is an equivalent result of Rolle Theorem (or Mean Value's) in $\mathbb{C}$ and $f'(z)=0$ is a local property. Am I right?

A: A function $f\colon\mathbb C\to\mathbb C$ such that $f'(z)$ exists and equals zero  for all $z\in\mathbb C$ is constant. (If $f$ is defined on a non-connected domain, we only get that $f$ is locally constant, but that observation holds in the reals as well)
Assume $f(z_1)\ne f(z_2)$. Consider $g\colon [0,1]\to \mathbb C$, $t\mapsto f(z_1+t(z_2-z_1))$. Then you have $g(t+h)=g(t)+o(|h|)$ and are reduced to the real case.


text:
Q: How to run code everyday with Parse for iOS? Is there a way to run code everyday at a specific time with Parse for an iOS app? I would like to be able to send a push notification to specific users based on their settings and preferences found in various Parse data classes.
Thanks in advance.

A: Found the answer: https://parse.com/docs/ios/guide#cloud-code-advanced-background-jobs
All you need is a background job. Then, you schedule it on the Parse dashboard and set a frequency.


text:
Q: Can anyone tell me why Database options in my netbeans 6.8 seems empty? Can anyone tell me why Database options under services in my netbeans 6.8 seems empty with no options.
Before installing netbeans 6.8 i've also installed netbeans 7.1 also in my operating system. In netbeans 7.1 i've all database option, but why i'm not getting that under netbeans 6.8?
http://i.stack.imgur.com/PCHiL.png

A: I don't know the exact answer, but the following link is talking about this issue
Netbeans 6.9.1 Database Empty Nodes
Read it carefully, and apply the solution only if it is related to you.


text:
Q: How can I backup file using pom.xml? I've got three questions here. First, does pom.xml of maven have any difference from other xml file?
Second, if I would like to rename a file in the same directory as the pom.xml by scripts, can I do it in pom.xml? If possible, then how should I do it?
Last, how can I get the current time in pom.xml?
In fact, what I want to achieve is that I would like to backup the current package(.war) by appending it with the timestamps before I mvn package it. I want the whole process automated by the pom.xml instead of manually processing it.
Hi there,
I find a way to get the timestamp, will it work?
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactID>buildnumber-maven-plugin</artifactId>
  <execution>
  <phrase>package</phrase>
  <configuration>
    <format>{0, date, yyyy-MM-dd HH:mm:ss}</format>
    <items>timestamp</items>
  </configuration>
  <execution>
</plugin>

will it work? if it works, how can I obtain the timestamp variable? $items or $timestamp?
Thanks

A: *

*The Maven pom.xml is just another XML file and there is no difference from others. It follows the same XML standards.

Now for Question 2 and 3, First of all, when you will run mvn clean, it will flush off all the files, including the war from the target folder.
You can run ANT tasks to rename and backup the current war, but it cannot be executed before clean.
I would suggest you the following approach:

*

*Run maven-antrun-plugin as a part of package goal.

*In the ANT target, rename and backup the current packaged war.

Alternatively:
What I would suggest is: In the WAR pom.xml, specify the <version> element with the current timestamp and the desired version. This way, each war would be copied into different directories in the maven local repository.
PS: You cannot generate timestamp in maven as per my knowledge. Pass it through some external variable

A: Perhaps you should set the context for your questions to get better answers. Anyway, here goes.

*

*pom.xml is an xml file, with its own schema.  Thus it is different from other xml files.

*There are a couple of ways to rename a file using maven.  This SO discussion gives the options.  One of them is as follows:
Essentially, you would have a pom with entries similar to the one in this example (external build.xml).  Your ant build.xml would have entries similar to this:
<?xml version="1.0"?>
<project name="dummy">
    ...
    <target name="rename">
        <move file="file.orig" tofile="file.moved"/>
    </target>
    ...
</project>

*

*You can use a special maven variable for timestamp as documented here.  Refer to this SO discussion on how to use it.
maven.build.timestamp   The timestamp that denotes the start of the build. Since Maven 2.1.0-M1


text:
Q: bootstrap carousel image dimensions I have probs in the dimensions of the image to be placed inside carousel. Any image I load (with different dimensions px) I get an image elongated all over the carouse width and not proportional to the original..
How should I fix the CSS ? Can I place the image at the center of the carousel without having it prolonged to the left/right borders? Here is my CSS:
.carousel {
  height: 500px;
  margin-bottom: 10px;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
  z-index: 100;
}

/* Declare heights because of positioning of img element */
.carousel .item {
  height: 500px;
  background-color: #FFF;
}
.carousel-inner > .item > img {
  position: center;
  top: 0;
  left: 10;
  min-width: 100%;
  height: 500px;
}

A: The solution is to put that css code into your  css file
.carousel-inner > .item > img {
    margin: 0 auto;
}


text:
Q: enumerate bibliography items I'm using bibtex, the package apacite and
\bibliographystyle{apacite}
\bibliography{tesis}

I'm sorting the bibliography aphabetically (author-year) and everyting's ok except that I want to enumerate the bibliography items (just in the bibliography). I found this, but it's for biblatex and I can't make it work in my case. Any help will be apreciated!

A: In the following solution I use a new counter for numeric labels. The internal command \@biblabel is redefined to increment and print the counter. It gets called at the beginning of each item. The space after the numeric labels can be adjusted with \biblabelsep. See the manual of apacite for some documentation on the customization facilities.

\documentclass{article}
\usepackage{apacite}

\setlength{\biblabelsep}{0.3em}
\newcounter{MyBibCount}
\makeatletter
\renewcommand{\@biblabel}[1]{\stepcounter{MyBibCount}\theMyBibCount.}
\makeatother

\begin{document}
\bibliographystyle{apacite}
\nocite{article-minimal}\nocite{inbook-minimal}
\nocite{book-minimal}\nocite{incollection-minimal}
\nocite{mastersthesis-minimal}\nocite{inproceedings-minimal}
\nocite{whole-proceedings}\nocite{phdthesis-minimal}
\nocite{techreport-full}\nocite{unpublished-minimal}
\bibliography{xampl}
\end{document}


text:
Q: Post Build event is executing before the msi is built in visual studio with wix sharp I have several projects which generates several references.
and in the installer project which ultimately generates a MSI file; using WIX sharp.
There are pre build events written to copy the reference from different folder to the packaging folder of the MSI. It is working fine the MSI is generating successfully.
Now I want to sign the MSI with a code signing certificate, the Issue is post build event is executing before the MSI build is started and since there is no MSI present the build is getting errors.
I am using Visual studio 2017.
The post build code I am executing
$(ProjectDir)signtool\signtool.exe sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /sm /sha1 [hash] $(ProjectDir)\test.msi

A: Unfortunately you can't  sign your MSI in Post-Build event if you really use WixSharp, because MSI package creates by call ManagedProject.BuildMsi() method in runtime.
So i see only one workaround here, you need to call Process.Start("signtool\signtool.exe ...")" after BuildMsi() method execution


text:
Q: Count number of records with sum of multiple columns equal to 0 in mysql table I have a table with  stocks of different warehouse columns are there.
I need to find out the records matching the below criteria.Its a mysql database.
Count number of records with sum of multiple columns equal to 0.
Structure of table
Stock A | Stock B | Stock C | Stock D
0       | 1       | 0       | 0
0       | 0       | 0       | 0
1       | 1       | 1        | 1

Here the output will be 1.

A: This should be fairly simple:
create table test (stock_a int, stock_b int, stock_c int, stock_d int);
insert into test values (0,1,0,0), (0,0,0,0), (1,1,1,1);

select count(*) from test where stock_a + stock_b + stock_c + stock_d = 0

Result:
count(*)
--------
1

A: Sum of multiple columns are in the where clause so the Count(1) only counts where summ of all fields is zero.
Select Count(1) From warehouse
Where (`Stock A` + `Stock B` + `Stock C` + `Stock D`) = 0

A: I think you won't have negative values in yourtable, then you can just do this:
SELECT COUNT(*) As cnt
FROM yourtable
WHERE (Stock_A, Stock_B, Stock_C, Stock_D) = (0, 0, 0, 0)