text:
Q: Android:Espresso: How get item on specific position of RecyclerView? Android Studio 3.2.
I have activity TradesActivity that show list of items (Trader). This list is show by RecyclerView.
I need to write the next Espresso test.
if trader.getRunning() == true then background color of item is red. Else background color is green. I find trader by position.
So my Espresso test must to the next steps:

*

*Get Trader of specific position (e.g. 6)

*Check trader.running

*if it true then check background of textView

How I can do this by Espresso?
Here my solution. Is this a good solution?
    @Rule
    @JvmField
    var activityActivityTestRule = ActivityTestRule(TradersActivity::class.java)

@Test
fun itemList_itemContainerBackgrounColor() {
    // scroll to position
    onView(withId(R.id.tradersRecyclerView))
            .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(CHECK_ITEM_LIST_POS, swipeLeft()))
    // check
    onView(withId(R.id.tradersRecyclerView)).check(hasCorrectBackgroundColorAtPosition(CHECK_ITEM_LIST_POS, R.id.itemContainer))
}

snippet of my custom ViewAssertion:
class TraderViewAssertion {

    companion object {
        fun hasCorrectBackgroundColorAtPosition(position: Int, @IdRes resId: Int): ViewAssertion {
            return object : ViewAssertion {

                override fun check(view: View, exception: NoMatchingViewException) {
                    if (view !is RecyclerView) {
                        throw exception
                    }
                    val trader = (view.adapter as TraderListItemAdapter).getItem(position) as Trader
                    val itemView = view.findViewHolderForAdapterPosition(position)!!.itemView.findViewById<View>(resId) as TextView
                    val itemViewColorDrawable = itemView.getBackground() as ColorDrawable
                    val colorCode = itemViewColorDrawable.color
                    if (trader.isRunning) {
                        if (DateUtil.getDiffMinutes(Date(trader.last_iteration_time), Date()) > 1) {
                            Assert.assertTrue("Wrong color at position $position", (colorCode == R.color.trade_error_color))
                        } else {
                            Assert.assertTrue("Wrong color at position $position", (colorCode == R.color.trade_running_color))
                        }
                    } else {
                        Assert.assertTrue("Wrong color at position $position", (colorCode == R.color.trade_not_running_color))
                    }
                }
            }
        }
    }
}

But I get error:
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter exception
at com.myproject.custom.assertion.TraderViewAssertion$Companion$hasCorrectBackgroundColorAtPosition$1.check(TraderViewAssertion.kt)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAssertion.check(ViewInteraction.java:419)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:282)
at androidx.test.espresso.ViewInteraction$2.call(ViewInteraction.java:268)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: You can do that creating a custom matcher like this:
public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) {
    return new TypeSafeMatcher<View>() {
        int currentIndex = 0;

        @Override
        public void describeTo(Description description) {
            description.appendText("with index: ");
            description.appendValue(index);
            matcher.describeTo(description);
        }

        @Override
        public boolean matchesSafely(View view) {
            return matcher.matches(view) && currentIndex++ == index;
        }
    }
}

A: There is the Kotlin version of Daniel Beleza answer:
private fun withIndex(matcher: Matcher<View>, index: Int): Matcher<View> {
    return object : TypeSafeMatcher<View>() {
        private var currentIndex = 0

        override fun describeTo(description: Description?) {
            description?.appendText("with index: ");
            description?.appendValue(index);
            matcher.describeTo(description);
        }

        override fun matchesSafely(view: View?): Boolean {
            return matcher.matches(view) && currentIndex++ == index;
        }
    }
}

A: You did not provide enough information to answer your question in full, but this should lead you in right direction. I have to mention I'd rather create specific condition during test and check given list item at given position, then dive into checking both data and view.
Matcher (pseudocode) :
    public static ViewAssertion hasCorrectBackgroundColorAtPosition(int position, @IdRes int id) {
        return new ViewAssertion() {
            @Override
            public void check(View view, NoMatchingViewException exception) {
                if (!(view instanceof RecyclerView)) {
                    throw exception;
                }

                RecyclerView rv = (RecyclerView) view;
                Trader item = ((YourAdapter) rv.getAdapter()).getItem(position);

                View itemView = rv.findViewHolderForAdapterPosition(position).itemView.findViewById(id);

        if(item.running) {
                Assert.assertTrue(
                        "Wrong color at position " + position,
                        itemView.getBackground().getColor() == R.color.colorA
                );
                } else {
                Assert.assertTrue(
                        "Wrong color at position " + position,
                        itemView.getBackground().getColor() == R.color.colorB
                );
                }

            }
        };
    }

How to use:
onView(yourRecyclerView).check(hasCorrectBackgroundColorAtPosition(123, R.id.yourTextViewId));

A: I found solution:
 @Test
    fun itemList_itemContainerBackgrounColor() {
        // scroll to position
        onView(withId(R.id.tradersRecyclerView))
                .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(CHECK_ITEM_LIST_POS, swipeLeft()))
        // check
        val recyclerView = activityActivityTestRule.activity.findViewById<View>(R.id.tradersRecyclerView) as RecyclerView
        val trader = (recyclerView.adapter as TraderListItemAdapter).getItem(CHECK_ITEM_LIST_POS) as Trader
        val itemContainer = recyclerView.findViewHolderForAdapterPosition(CHECK_ITEM_LIST_POS)!!.itemView.findViewById<View>(R.id.itemContainer) as ConstraintLayout
        val colorCode = (itemContainer.background.current as ColorDrawable).color
        if (trader.isRunning) {
            if (DateUtil.getDiffMinutes(Date(trader.last_iteration_time), Date()) > 1) {
                Assert.assertTrue("Wrong color at position $CHECK_ITEM_LIST_POS", (colorCode == ContextCompat.getColor(itemContainer.context, R.color.trade_error_color)))
            } else {
                Assert.assertTrue("Wrong color at position $CHECK_ITEM_LIST_POS", (colorCode == ContextCompat.getColor(itemContainer.context, R.color.trade_running_color)))
            }
        } else {
            Assert.assertTrue("Wrong color at position $CHECK_ITEM_LIST_POS", (colorCode == ContextCompat.getColor(itemContainer.context, R.color.trade_not_running_color)))
        }
    }

A: In my case, I needed to check for the background tint. I modified the solution @ror(https://stackoverflow.com/a/55658980/1713366) provided into this:
fun itemHasBackgroundTintAtPosition(position: Int, @IdRes id: Int, backgroundTintHex : String): ViewAssertion
    {
        return ViewAssertion { view, _ ->

            val itemView: View = (view as RecyclerView).findViewHolderForAdapterPosition(position)!!.itemView.findViewById(id)

            Assert.assertTrue(
                "Wrong background tint at position $position",
                itemView.backgroundTintList?.defaultColor == Color.parseColor(backgroundTintHex)
            )
        }
    }

FYI, this is part of a RecylerView matcher class I created, so there's no need to validate if it's the correct instance.
To use:
onView(withId(R.id.recyclerViewId)).check(itemHasBackgroundTintAtPosition(0, R.id.recyclerViewItemViewId, "some hex value. For example, #000000."))


text:
Q: Is the CloudBees Jenkins SaaS PCI Compliant? I am looking for a hosted Jenkins solution that is PCI Compliant, Does CloudBees offer this?

A: Yes, for payment for the Jenkins SaaS - CloudBees is PCI compliant (ie how we handle your CC) - assuming that is what you mean.

A: CloudBees will know the answer; ask them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the most succinct Scala way to invoke a Java 8 functional interface? Take a Runnable, for example.  What is the most succinct way to call this from Scala?
I'm currently doing this:
r { () => runnable-body; null; }

after having declared the following trait:
trait Implicits {
    def r(fun: () => Unit) = new Runnable { def run() = fun() }
}

But this has two flaws:

*

*It's only for Runnable, not for all functional interfaces.

*There must be a more succinct way to express this.  Compare with Java 8's simpler () -> runnable-body.

A: You could make the adapter take () => Any to avoid the need for the null.
Scala is working on support for Java 8 SAM synthesis but it won't be marked stable until 2.12; you can build with -Xexperimental to enable it in current versions. Other than that as far as I can see you'll need adapters for every case (maybe a macro could help generate them).


text:
Q: Как сделать ветвление в aiogram FSM в зависимости от ответа? Есть код бота aoigram, FSM работает отлично, но вот появилась задача, сделать логику в зависимости от ответа пользователя.
class FSMHelp(StatesGroup):
    state1 = State()
    state2 = State()
    state3 = State()
    state4 = State()

async def cm_start(message: types.Message):
    await FSMHelp.state1.set()
    await message.reply('Выберите тип', reply_markup=but.buttons2)

async def load_state1(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['state1'] = message.text
    await FSMHelp.next()
    await message.reply('Укажите документ', reply_markup=but.cancel_btn)

async def load_state2(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data ['state2'] = message.text
    await FSMHelp.next()
    await message.reply('Название организации', reply_markup=but.cancel_btn)

async def load_state3(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['state3'] = message.text
    await FSMHelp.next()
    await message.reply('Контактное лицо', reply_markup=but.cancel_btn)

async def load_state4(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data ['state4'] = message.text
    await message.reply(answer, reply_markup=but.buttons)
    await state.finish()

def register_message_order(dp : Dispatcher):
    dp.register_message_handler(cm_start, regexp='.*заявка', state=None)
    dp.register_message_handler(load_state1, state=FSMHelp.state1)
    dp.register_message_handler(load_state2, state=FSMHelp.state2)
    dp.register_message_handler(load_state3, state=FSMHelp.state3)
    dp.register_message_handler(load_state4, state=FSMHelp.state4)

Как сделать, чтобы  при вводе в state1 "нет", пропускать ввод state2? А если было да, то выполнять всё...

A: Не знаю, лучше это или нет, но я вообще перестал использовать StatesGroup-ы.
Для меня намного удобнее выбирать state через строку - await state.set_state('name-of-state'), после чего отлавливать по этой строке в хендлере - dp.register_message_handler(handler, state='name-of-state'.
Думаю, в вашем случае так будет сделать проще и удобнее.
Пример кода:
async def action_one(message: types.Message, state: FSMContext):

    await state.set_state('next_state')
    ...

async def action_two(message: types.Message, state: FSMContext):

    await state.finish()
    ...

dp.register_message_handler(action_one)
dp.register_message_handler(action_two, state='next_state')

При смене state через set_state данные стейта не пропадают.

A: Вроде разобрался, а может и нет, но всё равно работает как я хотел:
class FSMHelp(StatesGroup):
    state1 = State()
    state2 = State()
    state3 = State()
    state4 = State()

async def cm_start(message: types.Message):
    await FSMHelp.state1.set()
    await message.reply('Выберите тип', reply_markup=but.buttons2)

async def load_state1_yes(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['state1'] = message.text
    await FSMHelp.next()
    await message.reply('Укажите документ', reply_markup=but.cancel_btn)

async def load_state1_no(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['state1'] = message.text
    async with state.proxy() as data:
        data ['state2'] = 'нет'
    await message.reply('Название организации', reply_markup=but.cancel_btn)
    await state.set_state(FSMHelp.state3)

async def load_state2(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data ['state2'] = message.text
    await FSMHelp.next()
    await message.reply('Название организации', reply_markup=but.cancel_btn)

async def load_state3(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['state3'] = message.text
    await FSMHelp.next()
    await message.reply('Контактное лицо', reply_markup=but.cancel_btn)

async def load_state4(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data ['state4'] = message.text
    await message.reply(answer, reply_markup=but.buttons)
    await state.finish()

def register_message_order(dp : Dispatcher):
    dp.register_message_handler(cm_start, regexp='.*заявка', state=None)
    dp.register_message_handler(load_state1_yes, (lambda message: message.text == 'Yes'), state=FSMHelp.state1)
    dp.register_message_handler(load_state1_no, (lambda message: message.text == 'No'), state=FSMHelp.state1)
    dp.register_message_handler(load_state2, state=FSMHelp.state2)
    dp.register_message_handler(load_state3, state=FSMHelp.state3)
    dp.register_message_handler(load_state4, state=FSMHelp.state4)

Может кто-то проверить насколько правильно я сделал?


text:
Q: Can I use  or similar in  to avoid RowSpan? I am using PHP to generate a report, which is basically a one line table.
However, if any of the fields reflect a memo then I would like to see multiple lines of memo text - with line breaks of some kid - and not just the whole memo text as one long string.
I am using PHP to generate the HHTML. I did try replacing all '\r\n' with
, but that didn't work.
To do it 'properly' is going to get messy. I need to examine all fields in the table and find the memo field with the most line breaks, then use the number of lines to add a rowspan to each in the table.
Is there any easy way to avoid that?
Bad ascii art clarification follows. I currently have
-----------------------------------------------------------------------------------
| edit box text | radio group selection | memo line 1 memo line 2 ... memo line x |
-----------------------------------------------------------------------------------

and what I want is:
------------------------------------------------------
| edit box text | radio group selection | memo line 1 |
|               |                       | memo line 2 |
|               |                       |    ...      |
|               |                       | memo line x |
-------------------------------------------------------

A: what about do it like this:

    edit box text
    radio group selectio

        memo line 1

        memo line 2

        memo line 3

combining tables with div like this , you kept your table and forced the "memo"s to take a new line, and using this formation, you can give the memos a different styles.

A: Maybe this is over simplifying it, but why don't you just assign a fixed width to the table cell with the memo? I forget if s can act funny with width set, but if so just wrap it in a div with fixed width.
OR with php...
wordwrap() — Wraps a string to a given number of characters
OR with CSS  or a
 tag if it's already formatted:
td.has_memo {
    white-space:pre;
}

OR again, with php if it's preformatted:
nl2br() — Inserts HTML line breaks before all newlines in a string

A: maybe this might work

A: Simply clear the formatting (if any) on the cell that needs to show the memo field.
Then print out the contents like this:
echo nl2br($Fields["MemoField"]);

The above function auto-converts all \n lines to br tags.
Hope this helps.


text:
Q: Asp.net 3.5 localization, can't get it working This is really simple, can't understand why I can't get it working. In asp.net 3.5 I'm trying to use localization and French using Global Resources. But it never uses the French resource file.
I have three files: Default.aspx, Resource.resx, Resource.fr.resx.
In Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" Culture="fr-FR" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Label ID="lblWelcomeMsg" runat="server" Text="<%$ Resources:Resource, welcomeMessage %>"></asp:Label>

In App_GlobalResources/Resource.resx:
Name: welcomeMessage
Value: Welcome

In App_GlobalResources/Resource.fr.resx (have also tried using Resource.fr-FR.resx):
Name: welcomeMessage
Value: Bonjour

The problem is that it always says "Welcome" even if I set the culture to "fr-FR". I have also tried to set the language in the browser but nothing happens. What am I doing wrong?

A: I needed to set the culture in web.config for example (for auto):
<globalization culture="auto" uiCulture="auto"/>


text:
Q: class of data frame column data changed unintentionally- leading to downstream NA values I have read a set of data from an excel file into a variable "proportions". I tested the results of read.xls (package-gdata), read.xlsx (package-xlsx) and XLConnect (but this made no difference).
I need to analyse the column number 27 of the proportions variable.
 > class(proportions$X.27)
 [1] "character"

You can see that the class of that column is initially a character.
My problem is that when I go to subset the data in a particular way into a variable called "proportions1", the column classes are perturbed...
 proportions1<-data.frame(proportions$X.5, proportions$Lab.data, proportions$X.26, proportions$X.27, proportions$X.28, proportions$X.29, proportions$X.30)
 > class(proportions1$X.27)
 [1] "NULL"

When I reset the colnames to things that make sense it changes the columns' class to "factor"
 > colnames(proportions) <- c("barcode1", "WBC", "Neutrophils", "Lymphocytes", "Eosinophils", "Monocytes", "Basophils")
 > class(proportions1$Neutrophils)
 [1] "factor"

Later down the line I have to convert these column values to numerics such that I can plot them. I do this using:
     as.numeric(as.character(proportions1$Neutrophils)) etc.

However this leads to a loss of as much as 90% of my data (varyingly across the different analysed columns i.e. in some of my columns I lose 10% while in others 90% of the values).
When I contrast the data of proportions to the final data of :
 head(proportions$X.27)
 [1]  "10.8"            "5.3"             "3.9"            "2.8" ......

So according to the following error (note the values have been rearranged):
 > head(as.numeric(as.character(proportions1$Neutrophils)))
 [1]   NA   NA  2.3 14.9   NA   NA
 Warning message:
 In head(as.numeric(as.character(proportions1$Neutrophils))) :
   NAs introduced by coercion

Is there something that I can do to mitigate the NA values?


text:
Q: Renaming Realm DB file I have an old project with realm db, i am updating that to the newer realm version. i checked there was a funny name given to realm file.
I want to change that name but haven't found any documentation about that.
Has any done this before ?
RealmConfiguration config = new RealmConfiguration.Builder()
                .name("funnyName.realm")
                .schemaVersion(5)
                .migration(new RealmMigrationScript())
                .build();

A: *

*You can copy your old realm into a new realm (with your updated name) file

*Perform Data migration for all old names

*Once the new realm is created, set is as default instance.


text:
Q: how to create multiselection in listview? I am using listview in my android app. I use a checkbox in the listview and I want to know: How can I create multiselection and how can I show all selected items in another activity with a button click event. Following is the code snippet:
public class Home extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://api-11hr.anovatesoft.com/v1/list";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_CONTACT_NUMBER = "contactnumber";
    private static final String TAG_POSTAL_CODE = "postalcode";
    private static final String TAG_IMAGE = "image";
    SessionManager session;
    private double latitude;
    private double longitude;
    private String apikey;
    private String status;
    private  ImageView back;
    private  CheckBox check;

    GPSTracker gps;

    ListView listView;
    private Toolbar toolbar;                              // Declaring the Toolbar Object

    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        findViewsById();
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        check=(CheckBox)findViewById(R.id.ck);

        AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
                Home.this);

// Setting Dialog Title
        alertDialog2.setTitle("Too quiet?");

// Setting Dialog Message
        alertDialog2.setMessage("Follow your favourite merchants and see what deals they're launching at the 11th Hour!");

// Setting Positive "Yes" Btn
        alertDialog2.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to execute after dialog

                        dialog.cancel();

                    }
                });

        alertDialog2  .show();

        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View arg0) {
                                        Intent intent = new Intent(Home.this, ResultActivity.class);
                                        startActivity(intent);

                                    }
                                });

                Gps_func();
                // Session class instance
                session = new SessionManager(getApplicationContext());

                // get user data from session
                HashMap<String, String> user = session.getUserDetails();

                // apikey
                // Calling Application class (see application tag in AndroidManifest.xml)
                final GlobalClass globalVariable = (GlobalClass) getApplicationContext();

                //Set name and email in global/application context
                apikey = globalVariable.getApikey();

                latitude = globalVariable.getLatitude();
                longitude = globalVariable.getLongitude();
                status = globalVariable.getStatus();

                contactList = new ArrayList<HashMap<String, String>>();

                ListView lv = getListView();

                // Listview on item click listener
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        // getting values from selected ListItem

                        String cost = ((TextView) view.findViewById(R.id.email))
                                .getText().toString();

                        // Starting single contact activity
                        Intent in = new Intent(getApplicationContext(),
                                Adds.class);

                        in.putExtra(TAG_EMAIL, cost);

                        startActivity(in);

                    }
                });

                // Calling async task to get json
                new GetContacts().execute();
            }

            private void Gps_func() {

                gps = new GPSTracker(Home.this);

                // check if GPS enabled
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    //  Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);

                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();

                    if (gps.canGetLocation()) {
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();

                        // \n is for new line
                        // Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                        Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);

                    }
                }

            }

            @Override
            protected void onRestart() {
                super.onRestart();
                Gps_func();
            }

            /**
             * Async task class to get json by making HTTP call
             */
            private class GetContacts extends AsyncTask<Void, Void, Void> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    // Showing progress dialog
                    pDialog = new ProgressDialog(Home.this);
                    pDialog.setMessage("Please wait....");
                    pDialog.setCancelable(false);
                    pDialog.show();

                }

                @Override
                protected Void doInBackground(Void... arg0) {
                    // Creating service handler class instance
                    ServiceHandler1 sh = new ServiceHandler1(apikey, latitude, longitude);

                    // Making a request to url and getting response
                    String jsonStr = sh.makeServiceCall(url, ServiceHandler1.POST);

                    Log.d("Response: ", "> " + jsonStr);

                    if (jsonStr != null) {
                        try {
                            JSONObject jsonObj = new JSONObject(jsonStr);

                            // Getting JSON Array node
                            contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                            // looping through All Contacts
                            for (int i = 0; i < contacts.length(); i++) {
                                JSONObject c = contacts.getJSONObject(i);

                                String username = c.getString(TAG_USERNAME);
                                String name = c.getString(TAG_NAME);
                                String email = c.getString(TAG_EMAIL);
                                String address = c.getString(TAG_ADDRESS);
                                String gender = c.getString(TAG_CONTACT_NUMBER);
                                String postalcode = c.getString(TAG_POSTAL_CODE);

                                // tmp hashmap for single contact
                                HashMap<String, String> contact = new HashMap<String, String>();

                                // adding each child node to HashMap key => value

                                contact.put(TAG_EMAIL, email);

                                // adding contact to contact list
                                contactList.add(contact);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    // Dismiss the progress dialog
                    if (pDialog.isShowing())
                        pDialog.dismiss();
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            Home.this, contactList,
                            R.layout.list_item1, new String[]{TAG_EMAIL,
                    }, new int[]{
                            R.id.email,});

                    setListAdapter(adapter);
                }

            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.menu_main, menu);
                return true;
            }
    private void findViewsById() {
        check = (CheckBox) findViewById(R.id.ck);
        back = (ImageView) findViewById(R.id.back);
    }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                // Handle action bar item clicks here. The action bar will
                // automatically handle clicks on the Home/Up button, so long
                // as you specify a parent activity in AndroidManifest.xml.
                int id = item.getItemId();

                //noinspection SimplifiableIfStatement
                if (id == R.id.action_settings) {
                    return true;
                }

                return super.onOptionsItemSelected(item);
    }

A: here i will give you simple project which can be used to for multiple selection in listview.
public class MainActivity extends Activity {

private ListView llChb;

private String[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
        "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
        "x", "y", "z" };
private ArrayList<String> arrData=null;

private ArrayList<InfoRowdata> infodata;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    arrData=new ArrayList<String>();
    arrData.add("a");
    arrData.add("b");
    arrData.add("c");
    arrData.add("d");
    arrData.add("e");
    arrData.add("f");
    arrData.add("g");
    arrData.add("h");
    arrData.add("i");
    arrData.add("j");
    arrData.add("k");
    arrData.add("l");
    arrData.add("m");
    arrData.add("n");
    arrData.add("o");
    arrData.add("p");
    llChb = (ListView) findViewById(R.id.llChb);

    infodata = new ArrayList<InfoRowdata>();
    for (int i = 0; i < data.length; i++) {
        infodata.add(new InfoRowdata(false, i));
        // System.out.println(i);
        //System.out.println("Data is == "+data[i]);
    }
    llChb.invalidate();
    llChb.setAdapter(new MyAdapter());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public class MyAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View row = null;
        row = View.inflate(getApplicationContext(), R.layout.row, null);
        TextView tvContent=(TextView) row.findViewById(R.id.tvContent);
        //tvContent.setText(data[position]);
        tvContent.setText(data[position]);
        //System.out.println("The Text is here like.. == "+tvContent.getText().toString());

        final CheckBox cb = (CheckBox) row
                .findViewById(R.id.chbContent);
        cb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (infodata.get(position).isclicked) {
                        infodata.get(position).isclicked = false;
                    } else {
                        infodata.get(position).isclicked = true;
                    }

                for(int i=0;i<infodata.size();i++)
                {
                    if (infodata.get(i).isclicked)
                    {
                        System.out.println("Selectes Are == "+ data[i]);
                    }
                }
            }
        });

        if (infodata.get(position).isclicked) {

            cb.setChecked(true);
        }
        else {
            cb.setChecked(false);
        }
        return row;
    }

} }

InfoRowdata class here:
public class InfoRowdata {

public boolean isclicked=false;
public int index;
/*public String fanId;
public String strAmount;*/

public InfoRowdata(boolean isclicked,int index/*,String fanId,String strAmount*/)
{
    this.index=index;
    this.isclicked=isclicked;
    /*this.fanId=fanId;
    this.strAmount=strAmount;*/
} }

activity_main.xml here:
 <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"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/llChb"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

row.xml here:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:id="@+id/rlInner"
        android:layout_width="fill_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/tvContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:text="Medium Text"
            android:textColor="#000000" />

        <CheckBox
            android:id="@+id/chbContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp" />

    </RelativeLayout>

</RelativeLayout>

hope this will work for you :)

A: The best way is to use the ChoiceMode option with list as provided in API Demo sample -
You can have a look on
https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List11.java
and
https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List15.java
First Refernce code is
public class List11 extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_multiple_choice, GENRES));

        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }
    private static final String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };
}

You can go to the link and have a look on the codes.

A: You can try MultiChoiceAdapter.

MultiChoiceAdapter is an implementation of ListAdapter which adds support for modal multiple choice selection as in the native Gmail App.
It provides a functionality similar to that of the CHOICE_MODE_MULTIPLE_MODAL ListView mode, with two additional benefits:

*

*It's easier to use, as it keeps count of the selected items, updates their background accordingly and handles checkboxes transparently.

*It is compatible with every version of Android from 2.x. Of course, this implies that your project must use either ActionBarSherlock or the support library's ActionBarCompat.


text:
Q: Show by mathematical induction that the $\gcd(n,n+1) = 1$ for every integer $n$. By mathematical induction, how would you show $\gcd(n,n+1)= 1$ for every integer $n$?
I'm thinking you would start by knowing that some integer, $d$, would divide both $n$ and $n+1$. That's all I have so far.

A: $Proof \ by \ Induction$:
$Base \ case$: $n=0, \ n+1=1$. $\;$ $x\mid$$n$ for all $x$$\in$$\mathbb{Z}$, and $1\mid$$1$  trivially holds. Since the only common divisor is 1, $\gcd(0,1)=1$ holds.
$Inductive \ Hypothesis$: Assume $\gcd(k,k+1)=1$ for some $k\in$$\mathbb{Z}, \ k>0.$
Let $d=\gcd(k+1,k+2)$, where $d\in$$\mathbb{Z}, \ d>0.$ Hence, $d\mid$$(k+1)$ and $d\mid$$(k+2)$. Furthermore, $(k+1)=dm$, for $m$$\in$$\mathbb{Z}$, $0<m\leqslant(k+1)$. Also, $k+2=(k+1)+1=dm+1.$ Since $dm=(k+1)$, we get $(dm-1)=k$. Hence, $\gcd(dm-1,dm)=$$\gcd(k,k+1)=1$, by inductive hypothesis.
Edit: Also, since $d=\gcd(k+1,k+2)$$=\gcd(dm,dm+1)$$=\gcd(dm,d(m+\frac1d))$, we get that $\frac1d$ is an integer.
Thus, $\gcd(dm-1,dm)=$$\gcd(d(m-\frac1d),dm)=1$, and it follows that $0<d\leqslant1$. Hence, $d=1$.
Therefore, $\gcd(k+1,k+2)=1$.


text:
Q: strange methods showing in First Responder received actions I am curious about something that I am seeing in interface builder when I right click on the "First Responder" placemark. My question is when I right click the "First Responder" lists its received actions, amongst theses are 5 methods that are defined in one of my early classes, does anyone know why they are showing up, does it matter, is this normal?
EDIT:
If I right click on [First Responder] on any of the nib/xib files in my project (there are 4) I see the following.

I am just curious why the buttonPressed_XXX methods display in that list (for all the xibs in the project).

A: http://i.stack.imgur.com/WBMsk.png
First reponder is action of Keyboard to go off after you finish typing.. in above image all these actions uses keyboard so it shows that page when you remove the action(IBAction) thats it...

A: Did you delete the references from IB? XCode doesn't automatically delete the IBOutlets or IBActions if you hook up objects and get rid of the objects or IBActions. Press x beside the name of the object and the object type to get rid of the IBAction or Outlet. A picture could be helpful.


text:
Q: Why won't these combo boxes update correctly when changing datasource in Windows Forms (VB)? In a windows forms project, I have several combo boxes. The first combo box contains a list of objects. Those objects then have several lists which are used as the datasource's for the successive combo boxes, depending on which item is chosen in the first.
When the first item is selected, the other combo boxes update correctly. When this item is changed a second time (or any successive time), the other combo boxes do not correctly update. When debugging, it shows that the other combo boxes are having their datasource assigned correctly, with the right 'count' of items. But the items aren't actually displaying. What could be the cause?
Private Sub cmbPackage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPackage.SelectedIndexChanged
    // The Package controls what other options are available.
    If (TypeOf (cmbPackage.SelectedItem) Is Package) Then
        // Set current package as a member object to see if it was a scoping issue
        _currentPackage = CType(cmbPackage.SelectedItem, Package)
        ClearOptionDropdowns()
        cmbReward.DataSource = _currentPackage.Rewards
        cmbPayment.DataSource = _currentPackage.PaymentTypes
        cmbCommMethod.DataSource = _currentPackage.CommunicationMethods
        cmbBillMethod.DataSource = _currentPackage.BillMethods
        cmbNotification.DataSource = _currentPackage.BillNotifications

        cmbReward.Refresh()
        cmbPayment.Refresh()
        cmbCommMethod.Refresh()
        cmbBillMethod.Refresh()
        cmbNotification.Refresh()
        ...
        ...
End Sub

Private Sub ClearOptionDropdowns()
    cmbReward.DataSource = Nothing
    cmbPayment.DataSource = Nothing
    cmbCommMethod.DataSource = Nothing
    cmbBillMethod.DataSource = Nothing
    cmbNotification.DataSource = Nothing
    ' Also had x.items.clear(), but removed to see if that was affecting it
End Sub

A: Using Reflector to see what happens when the datasource is set, the following method is called:
base.DataSource = value;

Which then does this:
if (this.dataSource != value)
    {
        try
        {
            this.SetDataConnection(value, this.displayMember, false);
        }

SetDataConnection:
private void SetDataConnection(object newDataSource, BindingMemberInfo newDisplayMember, bool force)
{
    bool flag = this.dataSource != newDataSource;
    bool flag2 = !this.displayMember.Equals(newDisplayMember);
    if (!this.inSetDataConnection)
    {
        try
        {
            if ((force || flag) || flag2)
            {
               // Update Accordingly

If I manually set the DisplayMember with a Guid.NewGuid.ToString, the datasource updates correctly. It appears that the datasource comparison is determining that they are the same when they most definately are not. Even when I call .DataSource = new List(Of ...)(list) it will not update correctly.
The Object.Equals method does this:
 InternalEquals(object objA, object objB);

Which I'm assuming does a pointer comparison? Are there any optimizations that the compiler might be doing that would cache one List object, and then fill that list with the required values at run-time? I'm certain that each List is a new List(Of type) when the objects are created.


text:
Q: CreateText method produces error "The process cannot access the file because it is being used by another process" I am working on a button that will delete text in gross.txt. I keep getting this error:

The process cannot access the file 'C:\Users\isaiah\Visual BASIC Programs\VB2012\Chap10\Gross Pay Solution\Gross Pay Project\bin\Debug\gross.txt' because it is being used by another process.

Or more specifically:

A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll.

It appears the error comes from btnDelete_Click at the bottom.
Option Explicit On
Option Strict On
Option Infer Off

Public Class frmMain

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub txtGrossPay_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtGrossPay.KeyPress

        ' Allows the text box to accept only numbers, the period, and the Backspace key
        If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> ControlChars.Back Then
            e.Handled = True
        End If
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

        Dim outFile As IO.StreamWriter
        outFile = IO.File.AppendText("gross.txt")
        outFile.WriteLine(txtGrossPay.Text)
        outFile.Close()

        txtGrossPay.Text = ""
    End Sub

    Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click

        ' Declare new inFile Varable as a streamreader object
        Dim inFile As IO.StreamReader
        Dim dblLine As Double

        ' Opens gross.txt for input
        inFile = IO.File.OpenText("gross.txt")

        ' .Exists() searches /bin folder for gross.txt, returns a boolean value
        If IO.File.Exists("gross.txt") Then
            inFile = IO.File.OpenText("gross.txt")

            'Fill the list with the values
            Do Until inFile.Peek = -1

                Double.TryParse(inFile.ReadLine, dblLine)

                lstContents.Items.Add(dblLine.ToString("C2").PadLeft(6, " "c))
            Loop
        Else
            MessageBox.Show("The file you have requested does not exist", "Gross Pay Project",
                            MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
        End If

        inFile.Close()
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        Dim outDelete As IO.StreamWriter
        outDelete = IO.File.CreateText("gross.txt")
        outDelete.Close()
    End Sub
End Class

A: I believe you need to call dispose ...
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim outDelete As IO.StreamWriter
outDelete = IO.File.CreateText("gross.txt")
outDelete.Close()

outDelete.Dispose()
End Sub

Also in your Do Loop are you meaning to add a line when the
Double.TryParse(inFile.ReadLine, dblLine)

fails to parse?  It seems like you would want to skip it if the parse fails
  Do Until inFile.Peek = -1

       if Double.TryParse(inFile.ReadLine, dblLine)  then
          lstContents.Items.Add(dblLine.ToString("C2").PadLeft(6, " "c))
        end if

  Loop

but up to you.

A: Ok, I found the issue.
You were opening the file twice in your code with the line
inFile = IO.File.OpenText("gross.txt")

I commented out the first time you did it before your .Exists call.  I also added a dispose to your Delete call.  CreateText doesn't need to assign to anything so I commented out that code and added the line you needed.  I tested and these changes fixed the issue.  In fact the first change was the fix, the second one was just to clean things up.
 Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
    'declare new inFile Varable as a streamreader object
    Dim inFile As IO.StreamReader
    Dim dblLine As Double
    'opens gross.txt for input
    ' inFile = IO.File.OpenText("gross.txt")
    '.Exists() searches /bin folder for gross.txt, returns a boolean value
    If IO.File.Exists("gross.txt") Then
        inFile = IO.File.OpenText("gross.txt")
        'fill the list with the values
        Do Until inFile.Peek = -1
            Double.TryParse(inFile.ReadLine, dblLine)
            lstContents.Items.Add(dblLine.ToString("C2").PadLeft(6, " "c))
        Loop
         inFile.Close()
    Else
        MessageBox.Show("The file you have requested does not exist", "Gross Pay Project",
                        MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
    End If
End Sub

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    'Dim outDelete As IO.StreamWriter
    'outDelete = IO.File.CreateText("gross.txt")
    'outDelete.Close()
    IO.File.CreateText("gross.txt").Dispose
End Sub

A: The error means what it says. Somewhere you have the file open. Perhaps in Notepad? Are you looking at the contents of the file perhaps?


text:
Q: Positive scalar curvature in dimension 4 Let $M^n$ be a compact simply connected spin manifold.
Gromov, Lawson, and Stolz proved that if $n\geq 5$, then $M$ admits a metric of positive scalar curvature iff $\alpha(M)=0$.
Question: What happens in dimension 4?

*

*Are there compact simply connected spin manifolds of dimension 4 which have a metric of positive scalar curvature and $\alpha(M)\neq 0$?

*Are there compact simply connected spin manifolds of dimension 4 which have $\alpha(M)=0$ but no metric of positive scalar curvature?

*What are necessary and/or sufficient conditions for a compact simply connected spin 4-manifold to have a metric with positive scalar curvature?

A: $1.$ Lichnerowicz proved that if $M$ is a closed spin manifold which admits a positive scalar curvature metric, then $\hat{A}(M) = 0$. In dimensions $4k$, $\alpha(M) = 2\hat{A}(M)$, so it follows that $\alpha(M) = 0$. In fact, Hitchin proved that $\alpha(M) = 0$, regardless of dimension.
$2.$ In dimension four, $\hat{A}(M) = -\frac{1}{24}p_1(M) = -\frac{1}{8}\tau(M)$, so $\alpha(M) = 0$ if and only if $\tau(M) = 0$. If $M$ is a simply connected, closed, spin four-manifold with signature zero, then by Freedman's classification, there is an integer $k \geq 0$ such that $M$ is homeomorphic to $k(S^2\times S^2)$, the connected sum of $k$ copies of $S^2\times S^2$; note, the connected sum of zero copies of $S^2\times S^2$ is defined to be $S^4$. If $M$ is diffeomorphic to $k(S^2\times S^2)$, then $M$ admits positive scalar curvature metrics. Said another way, the topological manifolds $k(S^2\times S^2)$ all admit positive scalar curvature for their standard smooth structure.
A closed four-manifold can potentially admit a countably infinite number of smooth structures, and the existence of a positive scalar curvature metric depends on which smooth structure you choose. So it is possible that for some choice of $k$ and some choice of smooth structure on $k(S^2\times S^2)$, there does not admit a positive scalar curvature metric. Such examples exist. In Hirzebruch Surfaces: Degenerations, Related Braid Monodromy, Galois Covers (MR 1720873), Teicher constructs examples of simply connected general-type complex surfaces which are spin and have signature zero; see Theorem $5.8$. These are homeomorphic to $k(S^2\times S^2)$ for some $k$, but general type surfaces do not admit positive scalar curvature metrics.
$3.$ In dimension four, unlike in other dimensions, there are gauge theoretic obstructions to the existence of positive scalar curvature metrics. In particular, on a closed smooth four-manifold with $b^+ \geq 2$, the existence of a positive scalar curvature metric implies that all of its Seiberg-Witten invariants vanish. This is a necessary condition, but it is not sufficient. Note that these invariants are usually too complicated to calculate, except in ideal situations such as when the four-manifold in question is the underlying four-manifold of a Kähler surface.


text:
Q: Wrong(?) return type of overloaded method Task.Run I found in the book about programming asynchronous applications the following code:

public static double ReadDataFromIO() {
    // We are simulating an I/O by putting the current thread to sleep.
    Thread.Sleep(2000);
    return 10d;
}

public static Task<double> ReadDataFromIOAsync() {
    return Task.Run(new Func<double>(ReadDataFromIO));
}

This code compiles without errors and works great. However I wanted to check which overloaded method of Task.Run (MSDN - Task.Run) is used here and didn't find any.
Moreover Visual Studio indicates that:
Task.Run<double>(Func<double> function)

is used.
How is it possible?

A: If you mean the silent <double> - that is generic parameter inference, and it happens routinely in C#. Basically, if you don't specify any generic type parameters, and if there isn't an exact non-generic match, then the compiler will attempt to deduce the parameters on your behalf, considering all of the available overloads. In this case, the fact that it knows (from static analysis) that Func<double> returns double allows it to deduce that the most applicable option would be <double>, using the Task<TResult> Task.Run<TResult>(Func<TResult>) overload.
If it cannot deduce all of the generic parameters, or if it cannot find a suitable set of unambiguous options for a suitable overload, it will simply give up and tell you to specify them yourself.


text:
Q: Get simple data in xml attribute I want to get and echo the data in this simple XML format :
<top>
<file>
<my data="first"/>
</file>
<file>
<my data="second"/>
</file>
</top>

And i want to echo out with php this :
first,second

i need to give the path of XML file and get that results.
How to do that ?

A: First off, you need to extract the values using simplexml_load_string() function, then you need to loop the values. Since, first and second are attributes, you also need to use also attributes(). Consider this example:
$raw_xml = '<top>
<file>
<my data="first"/>
</file>
<file>
<my data="second"/>
</file>
</top>';
$data = array();
$xml = simplexml_load_string($raw_xml);
foreach($xml->file as $key => $value) {
    $value = reset($value);
    $data[] = (string) $value->attributes()['data'];
}

echo "<pre>";
print_r($data);
echo "</pre>";

Sample Output:
Array
(
    [0] => first
    [1] => second
)

Edit: if you want to just echo try this.
echo implode(',', $data); // should output first,second


text:
Q: DB Query on returning one value Laravel Im using a simple query to pull the users in a table called users.
 $users = DB::table('users')->get();

Then using a foreach loop to get the values , for example :
 foreach ($users as $user)
    {
        return $user->email;
    }

There is definitely 2 records in the DB Table, but it only returns one line. If i try to query a different table it does the same thing.
If i use the Query Log between the query
DB::enableQueryLog();
$users = DB::table('users')->get();
$result = DB::getQueryLog();

It returns the query and it looks fine
[{"query":"select * from `users`","bindings":[],"time":0.85}]

This table was created within PhpMyAdmin and not using the Artisan Migrate

A: Of course it so, cause you return from loop, use echo
foreach ($users as $user)
{
    echo $user->email;
}

return statement inside the loop will behave like break for your case, this means breaking the loop.

A: You can use either:
DB::table('users')->select(['email'])->get();
or
DB::table('users')->get(['email']);
But its basics, you can easily find this stuff in docs https://laravel.com/docs/master/


text:
Q: MySQL mariaDB union select execution ignorance there are two tables in one structured query as below
SELECT "field"

UNION SELECT "<category_id>"
UNION SELECT category_id FROM categories
UNION SELECT "</category_id>"

UNION SELECT "<inventory_id>"
UNION SELECT inventory_id FROM inventories
UNION SELECT "</inventory_id>"

UNION SELECT "<inventory_name>"
UNION SELECT inventory_name FROM inventories
UNION SELECT "</inventory_name>"

UNION SELECT "<category_name>"
UNION SELECT category_name FROM categories
UNION SELECT "</category_name>"

query result:

field

field

category_id

1

2

3

category_id

inventory_id

inventory_id

inventory_name

inv1

inv2

inv3

inventory_name

category_name

cate1

cate2

cate3

category_name

<inventory_id></inventory_id> should contain 1 which is the inventories.inventory_id record
notice
when i moved  <inventory_id></inventory_id> to <category_id></category_id> in query
i have got the expected result in <inventory_id></inventory_id> but <category_id></category_id> is empty
tables structure for simulation
create table inventories(inventory_id int AUTO_INCREMENT, inventory_name varchar(255), PRIMARY key (inventory_id));
create table categories(category_id int AUTO_INCREMENT, category_name varchar(255), PRIMARY key (category_id));
INSERT INTO categories(category_name) VALUES("cate1"),("cate2"),("cate3");
INSERT INTO inventories(inventory_name) VALUES("inv1"),("inv2"),("inv3");

use top select query to get the result
i have using https://sqliteonline.com/ to simulate it with phpmyadmin and got the same result

A: You need to use UNION ALL. By default, UNION removes duplicates, and some of the category_id and inventory_id values are the same.


text:
Q: How much faster is the native implementation of the native cryptographic hashes on Windows than the .Net Managed version? I'm providing hashes for sets of data in order to fingerprint the data and identify it by hash - this is the core use case for fast hashes like SHA1 and MD5.
In .Net, there is an option to go with the native or managed implementations of some of these hashes (the SHA variants, anyway). I'm looking for an MD5 managed implementation, and there doesn't appear to be one in the .Net Framework, but wondered if the wrapped native CSP is faster anyway, and if I should just use it content that there will be no perf problems using it. The top answer to Why is there no managed MD5 implementation in the .NET framework? indicates that faster performance could be the reason that a managed variant doesn't exist.
Is this true, and if so, how much faster is the native CSP?

A: Unfortunately, the wrapped native CSP for MD5 - MD5CryptoServiceProvider - is significantly slower than a pure managed implementation. It is an obstinate viewpoint that holds that native code is unequivocally faster than managed code: in many cases the opposite is true. This is such a case, at least in head-to-head measurements.
Using the translated reference MD5 implementation by David Anson, I constructed a quick performance test (source) which aims to measure any large differences in performance between the two implementations. While for small data arrays the difference are negligible, as expected, at around 16kB the native implementation starts to show potentially significant delay - on the order of milliseconds. This might not seem like much, but it is orders of magnitude slower than the pure managed implementation. This difference is maintained as the size of the data being hashed increases, and at the largest tested data array - ~250MB - the difference in CPU time was about 8.5 seconds. Considering that a hash like this is often used to fingerprint very large files, this extra delay would become noticeable, even against the often much larger delays from I/O.
It's not abundantly clear where the delay comes from, since a pure native test was not performed (one which would dispense with the wrapping of a CSP and consumption in managed code), but given the nearly identical shape of the graphs on the log scale, it would appear that the managed and native implementations have the same intrinsic performance, but that the native code performance is "shifted" down in performance likely due to the cost of the interop between native and managed code at runtime. This performance difference between wrapped native CSPs and pure managed implementations has also been reproduced and documented by other investigators.
In addition to answering the question "how much faster is the native implementation" in this particular case, I hope this evidence serves to prompt more reflection and investigation when the question of native vs. managed arises, breaking the long-standing and pernicious reaction to similar questions that native code is always faster, and thus, somehow, better. Managed code is clearly very fast, even in this performance-sensitive domain of bulk data hashing.


text:
Q: Java doesn't detect new version of applet when deploying from the same URL If have a webapp that loads an applet from an URL. Whenever I deploy a new version of the applet (accesible through the same URL), the clients don't detect the change and work with the cached version.
Why doesn't Java / browser plugin detect new verions of applets?
What alternatives do I have? (e.g. adding headers like entity tags, change jnlp, etc.)
This is my jnlp:
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" href="LITE_afirma.jnlp">
 <information>
   <title>My package</title>
   <vendor>My vendor</vendor>
   <homepage href="http://www.my.url" />
   <description>My description</description>
 </information>
 <offline-allowed/>
 <security>
   <all-permissions/>
 </security>
 <resources>
   <property name="jnlp.packEnabled" value="true"/>
   <property name="jnlp.versionEnabled" value="true"/>
   <j2se version="1.6+" href="http://java.sun.com/products/autodl/j2se" />
   <jar href="my.jar" main="true" version="3.2.1"/>
 </resources>
 <applet-desc
   name="My applet"
   main-class="com.my.company.package.MyApplet"
   width="1"
   height="1" />
 <update check="background"/>
</jnlp>


text:
Q: "declaration has no storage class or type specifier" in C++ I'm learning C++ through the book (5th Edition),today I encounter a problem when doing the exercise 12.6.
The code is shown below, the error is this declaration has no storage class or type specifier. But the program can run normally. The error locates at the last line on '}'.
#include<iostream>
#include<vector>
#include<new>

using namespace std;

vector<int>* func(){
    return new vector<int>();
}

void read_vec(istream &in, vector<int>* vp){
    int i;
    while(in>>i)
        vp->push_back(i);
}

void print_vec(vector<int>* vp){
    for(int i:*vp)
        cout<<i<<" ";
    cout<<endl;
}

int main(){
    auto vec = func();
    cout<<"Enter a sequence of integers"<<endl;
    read_vec(cin,vec);
    print_vec(vec);
    delete vec;
    vec = nullptr;

    system("pause");
}

I have searched the message, but still cannot figure out where my code is wrong.
I would be appreciative for all hints.

A: You need the standard library header <cstdlib> to use system.
Add
#include <cstdlib>

at the top of the file. Then, use std::system instead of just system.
std::system("pause");


text:
Q: Infimum & Supremum in $\epsilon-\delta$ Proofs When we are introduced to $\epsilon-\delta$ proofs in a usual first-year introductory course to Calculus, we usually always tend to do one of two things when we attempt to prove limits using the $\epsilon-\delta$ definition of a limit.

When we attempt to prove a limit of the form :
$$\lim_{x \ \to \ a} f(x) = L$$

*

*We show a relation between $\epsilon$ and $\delta$ by choosing a value of $\delta > 0$ equal to $\epsilon$, (how we choose this value depends on how we work our way towards that point in out proof). Afterwards we then have to show that the chosen value of $\delta$ satisfies the inequality $0<|x-a|<\delta \implies |f(x)-L|<\epsilon$ , $\forall \epsilon > 0$

*We write delta as a function of epsilon $\delta(\epsilon)$ since, delta is dependent on epsilon, and by that we can (arguably more intuitively) show that $\forall \epsilon >0 \ (\exists \ \delta>0 \ni (0<|x-a|<\delta \implies |f(x)-L| < \epsilon))$

But in either of these cases, we prove the existence of a single $\delta$ for a given $\epsilon$, however multiple $\delta$'s can exist for a single given $\epsilon$, but we tend to disregard that fact in our proofs as the existence of a single \delta satisfies the formal definition of a limit. Therefore the set of $\delta$'s that we prove exists (by proving every $\epsilon > 0$ has a single corresponding $\delta >0\ $) is only a small subset of the set of all possible $\delta$'s satisfying the inequality ($0<|x-a|<\delta \implies |f(x)-L|<\epsilon$ , $\forall \epsilon > 0$)
If we let $S$ be the set of all possible $\delta$'s satisfying the inequality :
$$S = \{\delta \in \mathbb{R} \ : \ 0<|x-a|<\delta \implies |f(x)-L|<\epsilon\}$$
All we do in our $\epsilon-\delta$ proofs (in first-year) is show that the value of $\delta$ we choose or write as a function of epsilon $\delta(\epsilon)$ is an element of that set $S$, and by showing that the inequality holds with the $\delta$ we've chosen for a given $\epsilon$. we are essentially showing that our chosen $\delta$ lies between the Infinum of $S$ and the Supremum of $S$.

So in a nutshell in our first-year $\epsilon - \delta$ proofs all we show in our proofs is this about our chosen value of $\delta$ :

*

*$\delta \in S$

*$inf(S) \leq \delta \leq sup(S)$

Which are both logically the same thing. But what about the other values of $\delta$ for a given $\epsilon > 0$? How can we find the set $S$ of all possible $\delta$'s for a given $\epsilon > 0$? How do we find, $inf(S)$ and $sup(S)$?
Lastly am I correct in everything that I have said above about $\epsilon-\delta$ proofs?


text:
Q: Spring annotation based configuration not found with SpringJUnit4ClassRunner I have some JUnit (4.10) tests configure using Spring (3.1.3) like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TestConfig.class)
public class MyTest {...}

These run fine from within Eclipse, but with Maven (surefire) from the command-line it fails to find the TestConfig class. I used to have the same configuration using xml based configuration and that worked fine in both cases. I have verified that TestConfig.class is in the expected location in test-classes. I also tried to move it to classes in case the context loader didn't look in test-classes, but no luck. Any ideas?
java.lang.IllegalStateException: Failed to load ApplicationContext
        at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
...
Caused by: java.io.FileNotFoundException: class path resource [com/test/TestConfig.class] cannot be opened because it does not exist
        at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
        at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:49)
        at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
        at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
        at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
        at org.springframework.context.annotation.ConfigurationClassParser.findAllAnnotationAttributes(ConfigurationClassParser.java:282)
        at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:225)
        at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:148)
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:134)

Update
I had <forkMode>never</forkMode> for the maven-surefire-plugin.
Setting <forkMode>once</forkMode> (default) made the problem go away.


text:
Q: Change the color with the user option I'm working in my project with assembly emu8086 and I've done a lot of things:

Now I'm struggling to put the option selected by the user. I want to change the leds color from (0-7) using the user option, I've already done a lot of things I only dont understand how I'll do this to change the color, if the user select 1 both squares(leds) need to change to blue and this for all the colors, I need to verify the user option.
Here is my code:
title    ac-cores-mov-cursor.asm - desenha poligno colorido em modo texto
         org  100h           ; directiva para definição do enderço da 1ª instrução
; definição de constantes

inicio:  jmp  princ          ; etiqueta e instrução de 'salto' para procedimento

;____________________Menu_cores___________________________
menucores    db   '1 black',0ah,0Dh
         db   '2 blue',0ah,0Dh
         db   '3 green',0ah,0Dh
         db   '4 cyan ',0ah,0Dh
         db   '5 red',0ah,0Dh
         db   '6 magenta',0ah,0Dh
         db   '7 brown',0ah,0Dh
         db   '8 light gray',0ah,0Dh
         db "Please select a choice(1-8):",13,10,   '$'

menu    db  '1 Todos os leds ligados',0ah,0Dh        ;leva ao menu cores para escolher a cor
        db  '2 Combinaçao(0,2,4,6)',0ah,0Dh          ;leva ao menu cores para escolher a cor dos leds 0 2 4 6
        db  '3 Combinaçao(1,3,5,7)',0ah,0Dh          ;leva ao menu cores para escolher a cor dos leds 1 3 5 7
        db "Please select a choice(1-8):",13,10,   '$'

;____________________Menu_principal___________________________
menuprincipal db   '1 Todos os leds desligados',0ah,0Dh   ; retorna os leds todos com a cor preta
              db   '2 Cor dos leds ',0ah,0Dh               ; leva para o menu cores
              db "Please select a choice(1-2):",13,10,   '$'      ;opçao escolhida

; definição de variáveis

esqlin   db   15            ; linha do vértice superior esquerdo
esqcol   db   10              ; coluna do vértice superior esquerdo

largura  db   2             ; largura do fundo
altura   db   2              ; altura do fundo

texlin   db   17             ; linha do texto
texcol   db   12              ; coluna do texto
colincio db   2

enter    db   0Ah,0Dh,'$'
fundo    db   'Cor fundo (0-9,A-F) ', '$'
texto    db   'Cor texto (0-9,A-F) ', '$'
corfund  db   0              ; 0-15 (decimal), 0-F (hexadecimal)
cortext  db   4             ; 0-15 (decimal), 0-F (hexadecimal)
frase1    db   'LED1', '$'
corft    db   0Fh

;___________________________START___________________________
verificacao:

princ    proc near           ; início do procedimento principal
         lea  dx, menucores      ; escrever string
         mov  ah, 09h
         int  21h

; define cor do texto e cor do fundo do ecrã
         mov  corft, 24h
         mov  bh, corft

         mov  ch, esqlin     ; vértice superior esquerdo - linha
         mov  cl, esqcol     ; vértice superior esquerdo - coluna
         mov  dh, esqlin
         add  dh, altura     ; vértice inferior direito - linha
         dec  dh
         mov  dl, esqcol
         add  dl, largura    ; vértice inferior direito - coluna
         dec  dl
         mov  ah, 06h
         int  10h

; instruções para terminar o programa
         mov  ax, 4c00h
         int  21h

princ    endp           ; fim do procedimento principal

; define cor do texto e cor do fundo do ecrã
         mov  bh, 218        ; 218(16*13+10) = DAh: D - cor fundo, A - cor texto
         mov  al, 01h        ; nº linhas scroll
         mov  ch, 0          ; vértice superior esquerdo - linha
         mov  cl, 0          ; vértice superior esquerdo - coluna
         mov  dh, 0          ; vértice inferior direito - linha
         mov  dl, 46         ; vértice inferior direito - coluna
         mov  ah, 06h        ; scroll uma linha (al)=1
         int  10h

         mov  al, corfund
         mov  bh, 16         ; 16 = 2^4
         mov  ah, 0
         mul  bh             ; 16*corfund
         add  al, cortext    ; = corfund*16 + cortext

A:
I need to verify the user option.

Ask the user to press a key and verify if it was valid.
Again:
    mov ah, 00h    ; BIOS.GetKeyboardKey
    int 16h        ; -> AX
    cmp al, "0"
    jb  Again
    cmp al, "7"
    ja  Again

Here the user has made a valid selection from 0 to 7. Now turn this choice into a background color. Remember the input is still a character! Once converted, you put it into the high nibble of the attribute byte to be used for outputting to the screen.
    sub al, "0"    ; Convert from character to value (*)
    mov cl, 4
    shl al, cl     ; Shift into high nibble (background color)
    add al, 15     ; Add in low nibble (foreground color)
    mov bh, al

Your screenshot uses the red text color, but that would make the text disappear if the user selected the red backgroundcolor. That's why I suggest you use BrightWhite (15) as your foreground color.
(*) can be omitted in this particular case (because of the shift left that follows)

I want to change the leds color from (0-7) using the user option,

The usual way would be to simply redraw the whole colored tile using the attribute set up in the BH register.
First you clear the tile using BIOS.ScrollWindowUp with AL=0 !
    FirstButtonCol    db 10
    FirstButtonRow    db 15
    FirstButtonWidth  db 10
    FirstButtonHeight db 3
    frase1            db 'LED1', '$'

    ...

    mov  ch, FirstButtonRow
    mov  cl, FirstButtonCol
    mov  dh, ch
    add  dh, FirstButtonHeight
    dec  dh
    mov  dl, cl
    add  dl, FirstButtonWidth
    dec  dl
    mov  ax, 0600h     ; BIOS.ScrollWindowUp AL=0
    int  10h

Then you position the cursor over the button and write the label "LED1"
    lea  si, [frase1]
    mov  cx, 1         ; ReplicationCount
    mov  bh, 0         ; DisplayPage
    mov  dl, FirstButtonCol
    mov  dh, FirstButtonRow
    add  dx, 0102h
NextChar:
    mov  ah, 02h       ; BIOS.SetCursor
    int  10h
    mov  al, [si]
    mov  ah, 0Ah       ; BIOS.WriteCharacter
    int  10h
    inc  dl            ; Next column
    inc  si            ; Next char
    cmp  byte [si], "$"
    jne  NextChar


text:
Q: Detecting one point's location compared to two other points EDIT I'm looking for the actual one or two liner that does what the answer with a lot of upvote suggest.
I've got a little problem to solve in a very real software and I'm looking for an easy way to solve it.
I've got two fixed points on screen (they're fixed, but I don't know beforehand their position) that are not at the same location.  These two fixed points form an imaginary line.  Now I've got a third point that is "on one side" of that line (it cannot be on the line).  The user can grab the point (the user actually grabs an object that I track by its center, which is the point I'm interested in) and drag it.  But it cannot "cross" the imaginary line.  What is the easiest way to detect if the user is crossing the imaginary line?
Points could be:
a[] = new int { 30, 50};
b[] = new int { 0, 100 };
c[] = new int { 20, 22 };

Examples (not corresponding to the points above):

      /
     a
c   /
   /
  /   (c cannot be dragged here)
 b
/

Or:

         c
---b--------------c--- -- -- -- - -
(c cannot be dragged here)

So what is an easy to detect if c is staying on the correct "side" of the line (I draw segments here, but it really can be thought of as a line)?
One way to detect this is to take the destination point d and see if segment (c,d) intersects with line (a,b), but isn't there an easier way?  Can't I just do some 2D dot-product magic here and have basically a one or two liner solving my issue?

A: You can use the sign of the Z-component of the cross product AB x AC (taking A & B's Z-components implicitly as 0) as an indicator of which side of segment AB point C is currently on.  When that sign changes, the drag has crossed or is crossing the segment AB.


text:
Q: Take value of a field in a block and place it in another field I have a problem taking values from a system.xml field to show them in another field.
This is the system.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="tryagain_system" translate="label" sortOrder="0">
            Tryagain module
        </tab>

            <class>separator-top</class>
            Settings
            <tab>tryagain_system</tab>
            <resource>Tryagain_System::config</resource>
            <group id="tryagain_system_group1" translate="label" type="text" sortOrder="1000" showInDefault="1" showInWebsite="1" showInStore="1">
                Views
                <field id="active_views" translate="label" type="multiselect" sortOrder="91" showInDefault="1" showInWebsite="1" showInStore="1">
                    Select store views
                    <source_model>Tryagain\System\Model\Config\Source\ListView\Values</source_model>
                </field>
            </group>
            <group id="fixiamo_dictionary" translate="label" type="text" sortOrder="7000" showInDefault="1" showInWebsite="1" showInStore="1">
                Dictionary
                <field id="terms" translate="label" sortOrder="92" showInDefault="1" showInWebsite="1" showInStore="1">
                    Dictionary

                    <frontend_model>Tryagain\System\Block\Adminhtml\Menu\Field\AdditionalItem</frontend_model>
                    <backend_model>Tryagain\System\Block\Adminhtml\Menu\Config\Backend\AdditionalItem</backend_model>
                </field>
            </group>

    </system>
</config>

I would like to take the data selected in the active_views and show them as header of the field terms.
These are the frontend_model and the backend_model
<?php
 namespace Tryagain\System\Block\Adminhtml\Menu\Field;

  use

Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;

class AdditionalItem extends AbstractFieldArray
{
protected $_typeblockOptions;
protected $_cmsblockOptions;
/**
 * {@inheritdoc}
 */

protected function _prepareToRender()
{

    $this->addColumn(
        'fromprice',
        [
            'label' => __('From Price'),
            'size' => '200px',
            'class' => 'required-entry' //remove this class if the field is not required
        ]
    );

    $this->addColumn(
        'toprice',
        [
            'label' => __('To Price'),
            'size' => '200px',
            'class' => 'required-entry'
        ]
    );

    $this->addColumn(
        'productcost',
        [
            'label' => __('Product Cost'),
            'size' => '200px',
            'class' => 'required-entry'
        ]
    );

    $this->_addAfter = false;
    $this->_addButtonLabel = __('Add');
} }

create block for backend
<?php

namespace Tryagain\System\Block\Adminhtml\Menu\Config\Backend;

use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value as ConfigValue;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;

class AdditionalItem extends ConfigValue
{

protected $serializer;

public function __construct(
    SerializerInterface $serializer,
    Context $context,
    Registry $registry,
    ScopeConfigInterface $config,
    TypeListInterface $cacheTypeList,
    AbstractResource $resource = null,
    AbstractDb $resourceCollection = null,
    array $data = []
) {
    $this->serializer = $serializer;
    parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}

public function beforeSave()
{
    $value = $this->getValue();
    unset($value['__empty']);
    $encodedValue = $this->serializer->serialize($value);

    $this->setValue($encodedValue);
}

protected function _afterLoad()
{
    /** @var string $value */
    $value = $this->getValue();
    if($value) {
        $decodedValue = $this->serializer->unserialize($value);

        $this->setValue($decodedValue);
    }

}    }

So I know that the way to take values from the system is this in a controller
<?php
namespace Vendor\Module\Controller\Index;
use Magento\Store\Model\ScopeInterface;

class Index extends \Magento\Framework\App\Action\Action
{
protected $scopeConfig;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig)
{
    $this->scopeConfig = $scopeConfig;
    parent::__construct($context);
}

public function execute()
{
    $storeScope = ScopeInterface::SCOPE_STORE;
    $value = $this->scopeConfig->getValue('pathinsystem', $storeScope);

    echo $value;
} }

I also tried a helper
How can I do the same thing in the block and pass the values to terms field


text:
Q: Arithmetic in a dihedral extension Let $\;$L = $\Bbb Q$[$\sqrt[4]{2}$, i ]$\;$ which is a dihedral extension of the rationals.  There are three quadratic and five quartic intermediate fields between L and $\Bbb Q$.  The following questions arose while trying to sort out how certain arithmetic information varies over the different subfields.  Although the third appears somewhat labor intensive, hopefully the first two
are easier.
Questions: $\quad$1)$\,$ Is$\,$  $\Bbb Z$[$\sqrt[4]{2}$, i ] the full ring of integers in L ?  $\;$ 2)  It is easy to see explicitly how the prime$\,$ p = 2$\,$ factors in each of the subfields $\,$$\Bbb Q$[ i ] $\,$and $\Bbb Q$[$\sqrt[4]{2}$]$\,$. $\;$ How does it factor in L , their compositum ?$\quad$3)$\,$ According to Dirichlet's unit theorem$\,$ L $\,$possesses 4 - 1 = 3 fundamental units.  Is it possible to compute them ? (This may be reducible to looking at the units in the quartic subfields.)$\quad$4)$\,$ Finally, are there any references which treat dihedral extensions of $\Bbb Q$ as an extended example or
case study?$\;$  Of special interest would be units, rings of integers, and class numbers.
Thanks


text:
Q: Как элемент из символьного массива сделать целым числом и записать в переменную целого типа? Нужно ли для этого пользоваться atoi , просто у меня ничего подобного не получилось , выводится ноль
char num1[80];
printf("Enter: ");
gets(num1);
printf("%d", atoi(num1));
return 0;

A: я хочу ввести ,например, ААА и получить 656565
Тогда делайте что-то вроде
for(char * с = num1; *c; ++c)
    printf("%02d",*c);

См. https://ideone.com/ggtnkV

A: До меня тоже дошло
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
int main(void)
{
    char num1[80];
    int A[80];
    int j = 0;
    printf("Enter: ");
    gets_s(num1);
    int i = 0;
    while (num1[i] != '\0')
    {
        A[i]=int(num1[i++]);

    }
    for (j = 0; j < i; j++)
    {
        printf("%d", A[j]);
    }
    _getch();
    return 0;
}


text:
Q: Correct classpath of your application so that it contains compatible versions of the classes BootstrapApplicationListener and SpringApplicationBuilder I am trying to upgrade my springboot application from. 1.5.22 to 2.7.0.  I am not ale to upgrade because of few dependency mismamtches.  I am using spring consul also and because of this may be the error.  Here is some portion of my pom.xml:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <testutils.version>1.6.1</testutils.version>
        <slf4j.version>1.7.25</slf4j.version>
        <logstash-logback-encoder.version>4.11</logstash-logback-encoder.version>
        <ch-qos-logback.version>1.2.11</ch-qos-logback.version>
        <!-- Sonar Properties -->
        <sonar.dynamicAnalysis>true</sonar.dynamicAnalysis>
        <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
        <sonar.language>java</sonar.language>
        <sonar.coverage.exclusions>**/*Config.*</sonar.coverage.exclusions>
        <log4j2.version>2.17.2</log4j2.version>
        <groovy.version>2.5.16</groovy.version>
        <httpclient.version>4.5.13</httpclient.version>
        <commons-beanutils.version>1.9.4</commons-beanutils.version>
        <gson.version>2.9.0</gson.version>
        <jackson.version>2.13.2</jackson.version>
        <snakeyaml.version>1.30</snakeyaml.version>
        <gemfire.version>8.1.0</gemfire.version>
        <hibernate.version>4.3.11.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-xml</artifactId>
            <version>3.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.cdk.credit</groupId>
            <artifactId>credit-application-model</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.cdk.ds.credit</groupId>
            <artifactId>dealer</artifactId>
            <version>2.0.24</version>
        </dependency>
        <dependency>
            <groupId>com.cdk.ds.credit</groupId>
            <artifactId>transaction-entities</artifactId>
            <version>1.3.8</version>
            <exclusions>
                <exclusion>
                    <artifactId>hibernate-jpa-2.0-api</artifactId>
                    <groupId>org.hibernate.javax.persistence</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.cdk.ds.credit</groupId>
            <artifactId>logging</artifactId>
            <version>1.0.7</version>
            <exclusions>
                <exclusion>
                    <artifactId>hibernate-jpa-2.1-api</artifactId>
                    <groupId>org.hibernate.javax.persistence</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.cdk.credit.memcache</groupId>
            <artifactId>cdk-credit-memcache</artifactId>
            <version>1.0.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.security</groupId>
            <artifactId>xml-security-impl</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>

        <dependency>
            <groupId>com.googlecode.junit-toolbox</groupId>
            <artifactId>junit-toolbox</artifactId>
            <version>1.8</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>2.7.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.6.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path-assert</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <version>3.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-all</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.adp.ds.frontoffice.credit</groupId>
            <artifactId>testutils</artifactId>
            <version>${testutils.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${ch-qos-logback.version}</version>
        </dependency>
        <dependency>
            <groupId>com.cdk.credit.security</groupId>
            <artifactId>cdk-credit-security</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.cdk.credit.error.response</groupId>
            <artifactId>cdk-credit-error-response</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${ch-qos-logback.version}</version>
        </dependency>
        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>${logstash-logback-encoder.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.xmlunit</groupId>
            <artifactId>xmlunit-core</artifactId>
            <version>2.6.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom2</artifactId>
            <version>2.0.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.14.3</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-consul-dependencies</artifactId>
                <version>3.1.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk15on</artifactId>
                <version>1.70</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.13.3</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.13.3</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.13.3</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-buffer</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-transport</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-transport-native-epoll</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-codec</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-codec-http</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-common</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-handler</artifactId>
                <version>4.1.77.Final</version>
            </dependency>
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>31.1-jre</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-crypto</artifactId>
                <version>5.7.1</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

And below is the error:

APPLICATION FAILED TO START

Description:
An attempt was made to call a method that does not exist. The attempt was made from the following location:
org.springframework.cloud.bootstrap.BootstrapApplicationListener.bootstrapServiceContext(BootstrapApplicationListener.java:120)

The following method did not exist:
org.springframework.boot.builder.SpringApplicationBuilder.<init>([Ljava/lang/Object;)V

The calling method's class, org.springframework.cloud.bootstrap.BootstrapApplicationListener, was loaded from the following location:
jar:file:/Users/patangav/.m2/repository/org/springframework/cloud/spring-cloud-context/1.1.0.RELEASE/spring-cloud-context-1.1.0.RELEASE.jar!/org/springframework/cloud/bootstrap/BootstrapApplicationListener.class

The called method's class, org.springframework.boot.builder.SpringApplicationBuilder, is available from the following locations:
jar:file:/Users/patangav/.m2/repository/org/springframework/boot/spring-boot/2.7.0/spring-boot-2.7.0.jar!/org/springframework/boot/builder/SpringApplicationBuilder.class

The called method's class hierarchy was loaded from the following locations:
org.springframework.boot.builder.SpringApplicationBuilder: file:/Users/patangav/.m2/repository/org/springframework/boot/spring-boot/2.7.0/spring-boot-2.7.0.jar

Action:
Correct the classpath of your application so that it contains compatible versions of the classes org.springframework.cloud.bootstrap.BootstrapApplicationListener and org.springframework.boot.builder.SpringApplicationBuilder

A: The error says :
The calling method's class, org.springframework.cloud.bootstrap.BootstrapApplicationListener, was loaded from the following location:
jar:file:/Users/patangav/.m2/repository/org/springframework/cloud/spring-cloud-context/1.1.0.RELEASE/spring-cloud-context-1.1.0.RELEASE.jar!/org/springframework/cloud/bootstrap/BootstrapApplicationListener.class
=> spring-cloud-context/1.1.0.RELEASE
Your pom.xml references :
<artifactId>spring-cloud-consul-dependencies</artifactId>
<version>3.1.1</version>

So you should be using the latest spring-cloud-context version :
https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-context
Your pom.xml looks consistent.
Try to clean / rebuild, delete IDE cache if possible.
If the error still occurs, use the mvn dependency:tree command to find out why you are still using a 1.1.0 version of the spring-cloud-context library.


text:
Q: Can an MPI worker suspend itself? I have built an MPI program in C++.
The program might be run in a distributed computing context, but it may also be run on a single machine. At initialization parameters are distributed to each worker. The workers then proceed in a parallel fashion without intercommunication. A partial result is returned to the master, more parameters are distributed, more fully parallel work is done, and the program terminates.
In the case of a single machine, the program's workers can be and will have to be run sequentially. The total data held by the program will not fit into RAM. A possible solution is to suspend worker processes at strategic points in time so that their memory can be swapped to disk and then reanimate them later to perform more calculations.
Is it possible to suspend a worker, say with pthread_suspend and reactivate it later?


text:
Q: Convertion of json to list in c# i have a json string like below
{"Page Load":{"Entity":[{"NamesList":[{"Id":1,"Name":"Food"},{"Id":2,"Name":"Power"},{"Id":3,"Name":"air"},
{"Id":4,"Name":"water"},{"Id":5,"Name":"nature"},{"Id":6,"Name":"another"}],
"Transaction information":{"success":true,"return val":"","return datatype":"","error":""},
"Metadata":{"Type":"Abstract"}}],"next records":false},"Processing Time":14}

i want to get the values of NamesList(returning from json) to my Root class.
Myclass

A: Try this:
using Newtonsoft.Json;

var result = JsonConvert.DeserializeObject<T>(jsonString);

T is your root class.