text:
Q: My Fragment layout is overlapping Activity layout I have an Activity with two buttons. Button click opens a new Fragment. But the Fragment view is overlapping my Activity view.
I have tried giving background to my fragment but it is not working for me

Here is activity xml code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E6E6E6"
    tools:context=".TourAdmin">

        <TextView
            android:id="@+id/tour_admin_tour_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="60dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="Tournament Name"
            android:textSize="30dp" />

        <Button
            android:id="@+id/tour_admin_schedule"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tour_admin_tour_name"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="50dp"
            android:background="@color/colorPrimary"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="Schedule Match"
            android:textColor="#fff" />

        <Button
            android:id="@+id/tour_admin_show_for_score"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tour_admin_schedule"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="40dp"
            android:background="@color/colorPrimary"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="Score Match"
            android:textColor="#fff" />

    <FrameLayout
        android:id="@+id/admin_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Here is fragment xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="2dp"
    android:background="@android:color/holo_red_dark"
    tools:context=".TourScheduleMatch">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Spinner
                android:id="@+id/tour_team1_select_spinner"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="30dp"
                android:paddingLeft="6dp"
                android:paddingRight="6dp" />

            <Spinner
                android:id="@+id/tour_team2_select_spinner"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/tour_team1_select_spinner"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="40dp"
                android:paddingLeft="6dp"
                android:paddingRight="6dp"
                />

            <Spinner
                android:id="@+id/tour_sched_half_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/tour_team2_select_spinner"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="40dp"
                android:paddingLeft="6dp"
                android:paddingRight="6dp"
                android:entries="@array/match_time"/>

            <Spinner
                android:id="@+id/tour_sched_nop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/tour_sched_half_time"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="40dp"
                android:paddingLeft="6dp"
                android:paddingRight="6dp"
                android:entries="@array/tournament_nop"/>

            <EditText
                android:id="@+id/tour_cityNameEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="24dp"
                android:layout_marginTop="24dp"
                android:layout_marginRight="24dp"
                android:layout_weight="0"
                android:hint="City"
                android:inputType="text"
                android:padding="8dp"
                android:layout_below="@id/tour_sched_nop"/>

            <EditText
                android:id="@+id/tour_groundNameEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="24dp"
                android:layout_marginTop="24dp"
                android:layout_marginRight="24dp"
                android:layout_weight="0"
                android:hint="Ground"
                android:inputType="text"
                android:padding="8dp"
                android:layout_below="@id/tour_cityNameEditText"/>

            <LinearLayout
                android:id="@+id/match_date_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_below="@id/tour_groundNameEditText"
                android:layout_centerHorizontal="true">

                <Button
                    android:id="@+id/tour_match_date_bn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    android:background="@color/colorPrimary"
                    android:paddingLeft="6dp"
                    android:paddingRight="6dp"
                    android:text="Match Date"
                    android:textColor="#fff" />

                <TextView
                    android:id="@+id/tour_match_date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="85dp"
                    android:layout_marginTop="28dp"
                    android:text="Match Date"
                    android:textColor="#000"
                    android:textSize="20dp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/match_time_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/match_date_layout"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp">

                <Button
                    android:id="@+id/tour_match_time_bn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="24dp"
                    android:background="@color/colorPrimary"
                    android:paddingLeft="6dp"
                    android:paddingRight="6dp"
                    android:text="Match Time"
                    android:textColor="#fff" />

                <TextView
                    android:id="@+id/tour_match_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="85dp"
                    android:layout_marginTop="28dp"
                    android:text="Match Time"
                    android:textColor="#000"
                    android:textSize="20dp" />

            </LinearLayout>

            <Button
                android:id="@+id/tour_schedule_schedule_bn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/match_time_layout"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="40dp"
                android:background="@color/colorPrimary"
                android:text="Create"
                android:textColor="#fff" />
        </RelativeLayout>
    </android.support.v4.widget.NestedScrollView>

</RelativeLayout>

A: I hope you are using a ConstraintLayout. To make the elements align one after another, use a LinearLayout or FrameLayout.

A: Using RelativeLayout here is wrong option. You should use LinearLayout instead. Place your FrameLayout as first view in your activity layout and change its visibility from gone to visible when needed.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="#E6E6E6"
          android:orientation="vertical">

<FrameLayout
    android:id="@+id/admin_fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"/>

<TextView
    android:id="@+id/tour_admin_tour_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="60dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:text="Tournament Name"
    android:textSize="30dp" />

<Button
    android:id="@+id/tour_admin_schedule"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:layout_gravity="center_horizontal"
    android:background="@color/colorPrimary"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:text="Schedule Match"
    android:textColor="#fff" />

<Button
    android:id="@+id/tour_admin_show_for_score"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tour_admin_schedule"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="40dp"
    android:background="@color/colorPrimary"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:text="Score Match"
    android:textColor="#fff" />

</LinearLayout>

Another option is using ConstraintLayout but it is harder to use than LinearLayout.


text:
Q: Any drawbacks to "low temp" lead-free solder paste? I am about to try my first "reflow skillet" soldering job, and as I look at the available types of solder paste I see there are lead-free pastes with much lower melting temperatures than others.
For example, this one from ChipQuik.
The advantages seem obvious, but somehow the marketing literature does not mention any drawbacks to this type of solder paste. In the quantities I would order the price seems about the same. Is there a reason this Sn42Bi58 formula hasn't become standard?

A: The only thing that springs to mind is that some components may get hotter than the solder and melt it?
It'd be quite rare for that to happen, but supposing you had a component which used some pins as a heatsink (some use ground pins as this), and it got hotter than the solder could cope with - the solder would melt, the connection would break down, the heat sink would fail, and the component would fry.
- This is just my thoughts, so is probably completely wrong ;)

A: 42/58 Tin / Bismuth is not unknown as a low temperature solder but has issues.
While widely used for some very serious applications (see below) it is not a mainstream industry contender for general use. It is not obvious why not given its substantial use by eg IBM.
Identical to the Bi58Sn42 solder you cite is:

*

*Indalloy 281, Indalloy 138, Cerrothru.
Reasonable shear strength and fatigue properties.
Combination with lead-tin solder may dramatically lower melting point and lead to joint failure.
Low-temperature eutectic solder with high strength.
Particularly strong, very brittle.
Used extensively in through-hole technology assemblies in IBM mainframe computers where low soldering temperature was required.
Can be used as a coating of copper particles to facilitate their bonding under pressure/heat and creating a conductive metallurgical joint.
Sensitive to shear rate.
Good for electronics. Used in thermoelectric applications.
Good thermal fatigue performance.
Established history of use.
Expands slightly on casting, then undergoes very low further shrinkage or expansion, unlike many other low-temperature alloys which continue changing dimensions for some hours after solidification.
Above attributes from the fabulous Wikipedia - link below.
According to other references it has low thermal conductivity, low electrical conductivity, thermal embrittlement issues and potential for mechanical embrittlement.
SO - it MAY work for you, but I'd be very very very cautious about relying on it without very substantial testing in a wide range of applications.
It is well enough known, has obvious low temperature advantages, has been widely used in some niche applications (eg IBM mainframes) and yet has not been welcomed with open arms by industry in general, suggesting that it's disadvantages outweigh advantages except perhaps in areas where the low temperature aspect is overwhelmingly valuable.
Note that the chart below suggests that flux cored versions seem to be specifically unavailable either as wire or as preforms.
Comparison chart:

The above chart is from this superb report which however does not provide detailed comment on the above issues.
Wikipedia notes

*

*Bismuth significantly lowers the melting point and improves wettability. In presence of sufficient lead and tin, bismuth forms crystals of Sn16Pb32Bi52 with melting point of only 95 °C, which diffuses along the grain boundaries and may cause a joint failure at relatively low temperatures. A high-power part pre-tinned with an alloy of lead can therefore desolder under load when soldered with a bismuth-containing solder. Such joints are also prone to cracking. Alloys with more than 47% Bi expand upon cooling, which may be used to offset thermal expansion mismatch stresses. Retards growth of tin whiskers. Relatively expensive, limited availability.

Motorola's patented Indalloy 282 is Bi57Sn42Ag1 . Wikipedia says

*

*Indalloy 282. Addition of silver improves mechanical strength. Established history of use. Good thermal fatigue performance. Patented by Motorola.

Useful lead free solder report - 1995 - nothing to add on above subject.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matlab issues with large image files I am currently facing a new batch of hyperspectral images in Matlab. Usually, I have no problems, but this time images of around 2000x2000x324 (double) have flooded me with "Out of memory" messages for all the image processing and statistical analyses I was a happily doing before.
My pc is relatively good ( Intel Core i7 and a total of available RAM of 15.8 GB but says available 7), so I am surprised.
I was wondering if you have any suggestions, strategy for dealing with such files or I am missing something here.
I have been suggested to switch to python for larger files, but with Matlab I have been having an intimate relationship for a while now.
Thank you very much for your support.
E


text:
Q: Web Socket java client outside server I am looking for an approach to create a java application for web socket. This application should not use any server's jars.
I say this because I have seen that java client for web sockets are available only for server to server communication. If I need to create it outside the server I have no other go to get those server's jars imported inside.

A: nv-websocket-client is a new WebSocket client library written in Java. It requires just Java SE 1.5, so it can run even on Android. The size of nv-websocket-client-1.3.jar (released on 2015-05-06) is 62,854 bytes and it does not require any external dependencies. See "WebSocket client library (Java SE 1.5+, Android)" for details.

A: I'm not sure I understand your question completely but from what I can gather of your question you might want to look into just plain old sockets. It uses a simple tcp protocol to talk between Java applications and is supported natively in Java take a look at this example (http://cs.lmu.edu/~ray/notes/javanetexamples/). Another alternative for server to server communication is to use something like RabbitMQ (http://www.rabbitmq.com/) or Kafka (http://kafka.apache.org/) but those require much more setup and are more complex then sockets.

A: To build a socket application you need only a server part where you instantiate a java.net.ServerSocket and a client part where you instantiate a java.net.Socket.
To do that is not necessary any special library.
Those are standard java applications (with a public static void main(String[] args) method) so you don't need a server environment (servlet container or Java EE container).

A: You are asking for java, however I suggest you cast your net wider and dive into using Node.js (javascript) as your web socket client/server ... nodejs applications run outside the browser and offer super fast asynchronous networking using the V8 c++ javascript engine ... the same engine which lives at the heart of google's chrome browser ... think of it as the JVM for javascript ... you write javascript yet it executes at c++ speeds


text:
Q: erase_water in as_dot_density failed I'm trying to create a dasymetric dot density map using tmap. From the vignette, it was recommended to use erase_water() to remove water areas from the polygons prior to generating dots. However, when i do so, it gives me the following errors:

Error in h(simpleError(msg, call)) :
error in evaluating the argument 'x' in selecting a method for function 'dots': [as,sf] coercion failed. You can try coercing via a Spatial* (sp) class

It runs fine without the erase_water() arguments. Can someone please help me? Here is more detail on the file that I used:

    str(ut_race_T90)

    > sf [1,317 × 5] (S3: sf/tbl_df/tbl/data.frame)
     $ GEOID   : chr [1:1317] "49035101700" "49035101700" "49035101700" "49035101800" ...
     $ NAME    : chr [1:1317] "Census Tract 1017, Salt Lake County, Utah" "Census Tract 1017, Salt Lake County, Utah" "Census Tract 1017, Salt Lake County, Utah" "Census Tract 1018, Salt Lake County, Utah" ...
     $ geometry:sfc_POLYGON of length 1317; first list element: List of 1
      ..$ : num [1:17, 1:2] -112 -112 -112 -112 -112 ...
      ..- attr(*, "class")= chr [1:3] "XY" "POLYGON" "sfg"
     $ variable: chr [1:1317] "per_his_T" "per_nonhis_white_T" "per_nonhis_nonwhite_T" "per_his_T" ...
     $ value   : num [1:1317] 211 2471 420 239 2047 ...
     - attr(*, "sf_column")= chr "geometry"
     - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA
      ..- attr(*, "names")= chr [1:4] "GEOID" "NAME" "variable" "value"

Also, I pull the file from tidycensus.

    # Get tract shape file information using tidycensus ====
    ut_bg_tidycensus_T10 <- get_decennial(
      geography = "tract",
      state = "UT",
      county = c("Davis", "Weber", "Salt Lake", "Utah"),
      variables = "P001001",
      year = 2010,
      geometry = TRUE
    ) %>%
      filter(!(GEOID %in% exclude_tracts_fips)) %>%
      select(-variable, -value)

    # Get race/ethnic information ====
    # Have to set tracts with value = 0 or NA as 1
    ut_race_T90 <- ut_bg_tidycensus_T10 %>%
      left_join(master_tract_tall %>%
                  filter(YEAR == 1990) %>%
                  select(FIPSCODE, per_his_T,
                         per_nonhis_white_T, per_nonhis_nonwhite_T) %>%
                  pivot_longer(cols = c("per_his_T",
                                        "per_nonhis_white_T",
                                        "per_nonhis_nonwhite_T"),
                               names_to = "variable",
                               values_to = "value") %>%
                  mutate(FIPSCODE = as.character(FIPSCODE),
                         value = ifelse(is.na(value) | value == 0, 1, value)),
                by = c("GEOID" = "FIPSCODE"))

Thank you so much for your help!


text:
Q: Encrypt application name in c# and decrypt in SQL Server I've encrypted application name in my c# app using MD5, so when constructing the connection string the application name is passed to SQL as encrypted. I would like to decrypt in SQL server the value to see if there is a match?
How can I get the original text in SQL ?

A: Hashes like MD5 are by definition one-way: you can't decrypt them by design. This is how many applications store secrets like passwords. A better solution would be to store a list of applications and their hashed values in a database table, then compare your submitted hash to the stored hashes to find a match.

A: I don't believe this is possible natively in SQL Server since MD5 is a one-way (apparently loss-full) hash. Here's a good StackOverflow answer that goes over MD5 in general.
SQL Server has a built in function to generate hashes called HASHBYTES() which maybe you could leverage (and one of the other hashing algorithms that are loss-less) to potentially generate a hash string that is reversible. But I have feeling even that might not be possible to do.


text:
Q: PDO connection class So I'm trying to build a simple PDO connection class so I can create a DB object whenever I need to have DB access but I keep getting the same errors no matter what I try.
Here is my code for the DB class
<?php
class DbConnect
{
// Database login vars
private $dbHostname = 'localhost';
private $dbDatabase = 'database';
private $dbUsername = 'username';
private $dbPassword = 'password';
public $db = null;

public function connect()
{
    try
    {
        $db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword); // Establish DB connection
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error handling
        return $db;
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}
}
?>

And here is my code for the class I'm trying to use it in:
<?php
session_start();
require 'DbConnect.php';

class User
{
    public function bindParams()
    {
        $DbConnect = new DbConnect();
        $sql = $DbConnect->connect();

        $sql->prepare("insert into dbobjectex(firstName, lastName) values (:firstName, :lastName)");
        $sql->bindParam(':firstName', $_SESSION['firstName']);
        $sql->bindParam(':lastName', $_SESSION['lastName']);
        $sql->execute();
    }
}
?>

Then bindParams() is called from the spot where I create the User class.  The two errors I keep getting are "NetworkError: 500 Internal Server Error" and "The character encoding of the HTML document was not declared."  Any ideas on what I'm doing wrong here?  Thanks for any advice.

A: What am I doing wrong here? - Many things, but the most obvious one to miss is this: at the end of your class definition of DbConnect, you're closing the php tag ?>, which you must avoid as much as possible with included files with included files. The upshot of having them in your case is that headers are sent prematurely, explaining your second error.
Other then that, each time you're instantiating the user class, you're creating a new PDO instance: you assign it to a variable, local to the connect member function, at least replace $db with $this->db. But most of all, I agree with @sabre: why would PDO require an additional wrapper? especially one that does nothing more than instantiate and return a pdo instance, just create an abstract class that handles the connections if needs must.
Another thing you might want to check is weather or not the include path is correct, and read the docs on autoloading classes. It'll save you a world of trouble once you've got a substantial class library. This might explain your first error, as might the ?> tag, but just to be on the safe side: use require_once, rather than require: including, and thus redefining, a class a second time is not what you want to be doing at all.


text:
Q: Only enumerate files in folders with specific names I have a folder structure and files like this:
 - doe-john
   - inbox
      - 1.
      - 2.
      - 3.
   - sent
      - 1.
      - 2.
      - 3.
   - notes
      - 1.
      - 2.
      - 3.
   - contacts
      - 1.
      - 2.
      - 3.
 - doe-jane
   - inbox
      - 1.
      - 2.
      - 3.
   - sent
      - 1.
      - 2.
      - 3.
   - notes
      - 1.
      - 2.
      - 3.
   - contacts
      - 1.
      - 2.
      - 3.

I only want to enumerate the files from the inbox and sent folders within each main folder. I know how to enumerate all of the files like so:
for root, dirs, files in os.walk(top_level_folder):
    for fn in files:
        with open(os.path.join(root, fn), 'r') as f:
            pass  # do something

I would presume that I would do it something like this, but I'm not quite sure how to do this correctly:
for root, dirs, files in os.walk(top_level_folder):
    for dir in dirs:
        if dir.lower() == "inbox" or dir.lower() == "sent":
            for fn in files:
                with open(os.path.join(root, fn), 'r') as f:
                    pass  # do something

But this still just enumerates all the files. How do I only enumerate the files in the folders with the specified folder names?

A: You're confusing root and dirs. root is the "current directory" at each level; dirs is a list of directories visible at this level.
Your current code processes all files in each directory, once per visible subdirectory. What you want is to see whether your current directory is inbox or sent, and only then do your processing.
for root, dirs, files in os.walk(top_level_folder):
    if root.lower().endswith("inbox") or root.lower().endswith("sent"):
        for fn in files:
            with open(os.path.join(root, fn), 'r') as f:
                pass  # do something

You can also set topdown=True in your walk call, and then modify which subdirectories you want to walk into.
for root, dirs, files in os.walk(top_level_folder, topdown=True):
    if root != top_level_folder:
        # only recurse into level 3+ directories with the desired names
        dirs[:] = [d for d in dirs if d in ['inbox', 'sent']]
    if root.lower().endswith("inbox") or root.lower().endswith("sent"):
        for fn in files:
            with open(os.path.join(root, fn), 'r') as f:
                pass  # do something

However, I find that option to be a little bit ugly (especially since you need a special case at the top level to avoid skipping /doe-john, etc.). In your particular case, since there are only two directories you want to look at and they're only one level down, I wouldn't use walk at all:
for person in os.listdir(top_level_folder):
    inbox = os.path.join(top_level_folder, person, 'inbox')
    sent = os.path.join(top_level_folder, person, 'sent')

    for file in os.listdir(inbox):
        pass # Do something

    for file in os.listdir(sent):
        pass # Do something

A: You can modify the dirs returned from os.walk() if you use the topdown=True option. According to the documentation:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False is ineffective, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.


text:
Q: AWS EBS references Perhaps this isn't so much a code question as a definitional question, but would someone be able to explain to me what the six line items below represent?

A: EBS has 3 types of storage (in order from most expensive to cheapest):

*

*Provisioned I/O. These are SSD volumes with a performance guarantee. With these volumes you not only pay for the size of the volume, but also the number of IOPS you have provisioned. These volumes should only be used when performance is very important.

*General Purpose SSD. These volumes provide improved performance over Magnetic volumes at a somewhat higher cost. Probably the best choice for most general purpose uses.

*Magnetic. This type of storage uses magnetic disks and is the cheapest and slowest. Good for bulk data storage that doesn't have any performance requirement.

The other two items not covered by the above volume types are IO requests, which occur any time data blocks are read or written to any volume. Also snapshots are copies of volumes stored on S3.

A: Amazon Elastic Block Storage is offered in three flavors: Magnetic, PIOPS SSD and General Purpose SSD.
Each flavor will offer different performance and prices, that you can check in the EBS pricing page.
These lines looks like a budget showing how much of each is consumed by your project :)


text:
Q: Can Java batch calls to SQL stored procedures? Java: Insert multiple rows into MySQL with PreparedStatement covers batching multiple INSERTs into one operation. I wondered if it is possible to do the same with calls to stored procedures, more specifically with MySQL? If so, what statement class would be used?

A: If you have your stored procedure like this:
JDBC CallableStatement Stored procedure IN parameter example.
CREATE OR REPLACE PROCEDURE insertEMPLOYEE(
   e_id IN EMPLOYEE.EMPLOYEE_ID%TYPE,
   e_name IN EMPLOYEE.NAME%TYPE,
   e_salary IN EMPLOYEE.SALARY%TYPE)
IS
BEGIN

  INSERT INTO EMPLOYEE ("EMPLOYEE_ID", "NAME", "SALARY")
  VALUES (e_id, e_name, e_salary);

  COMMIT;

END;

You can just use executeBatch() to do as you intend.
Example:
Connection conn = null;
CallableStatement callableStatement = null;
String proc = "{call insertEMPLOYEE(?,?,?)}";
try{
    //get connection
    conn = JDBCUtil.getConnection();

    //create callableStatement
    callableStatement = conn.prepareCall(proc);

    callableStatement.setInt(1, 7);
    callableStatement.setString(2, "Harish Yadav");
    callableStatement.setInt(3, 50000);
    callableStatement.addBatch();

    callableStatement.setInt(1, 8);
    callableStatement.setString(2, "Abhishek Rathor");
    callableStatement.setInt(3, 50000);
    callableStatement.addBatch();

    //execute query
    callableStatement.executeBatch();

    //close connection
    callableStatement.close();
    conn.close();

     System.out.println("Records inserted successfully.");
}catch(Exception e){
    e.printStackTrace();
}

A: You can use executeBatch(). See this example
Note: I haven't validated example by running in my local, but as per documentation it should work.


text:
Q: See what's in a stash without applying it How do I see what is inside a stash without actually applying it?

A: From man git-stash (which can also be obtained via git help stash):

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show, and ...

show [<stash>]
    Show the changes recorded in the stash as a diff between the stashed
    state and its original parent. When no <stash> is given, shows the
    latest one. By default, the command shows the diffstat, but it will
    accept any format known to git diff (e.g., git stash show -p stash@{1}
    to view the second most recent stash in patch form).

Note: the -p option generates a patch, as per git-diff documentation.
List the stashes:
git stash list

Show the files in the most recent stash:
git stash show

Show the changes of the most recent stash:
git stash show -p

Show the changes of the named stash:
git stash show -p stash@{1}

Or in short:
git stash show -p 1


text:
Q: Parsed Json array shows undefined in Dialogflow Following is my json data:
{
    "code": "200",
    "count": 3,
    "data": [
        {
            "_id": "602a2d4427e5ac1f5c8e897b",
            "survey_id": "602a5de91d4f0000ec004b94",
            "parent_question_id": "",
            "is_required": "1",
            "is_active": "1",
            "options": [
                {
                    "_id": "604b22c53b57d53fdc8c43f3",
                    "question_id": "602a2d4427e5ac1f5c8e897b",
                    "option_type_id": "602a2b0127e5ac1f5c8e8976",
                    "option_details": "He/She is good.",
                    "is_active": "1"
                },
                {
                    "_id": "604b22df3b57d53fdc8c43f5",
                    "question_id": "602a2d4427e5ac1f5c8e897b",
                    "option_type_id": "602a2b0127e5ac1f5c8e8976",
                    "option_details": "He/She is Average.",
                    "is_active": "1"
                },
                {
                    "_id": "604b22e63b57d53fdc8c43f6",
                    "question_id": "602a2d4427e5ac1f5c8e897b",
                    "option_type_id": "602a2b0127e5ac1f5c8e8976",
                    "option_details": "He/She is Poor.",
                    "is_active": "1"
                },
                {
                    "_id": "604b22d33b57d53fdc8c43f4",
                    "question_id": "602a2d4427e5ac1f5c8e897b",
                    "option_type_id": "602a2b0127e5ac1f5c8e8976",
                    "option_details": "He/She is Excellent.",
                    "is_active": "1"
                }
            ],
            "qustion_type": {
                "_id": "602a2b2627e5ac1f5c8e8978",
                "question_type": "Multie Radio",
                "is_active": "1"
            }
        },
    ]
}

Here I want to fetch the data of "option_details" which is inside the "option" array. I am able to get the option array.
Following is my code:
return
  axios.get(api call here)
  .then((results) => {
    results.data.data.map(quesobj => {
      ques.push(quesobj.question_text);
    })
    console.log(ques);
    results.data.data.map(questypeobj => {
      questype.push(questypeobj.qustion_type.question_type);
    })
    results.data.data.map(optionobj => {
      option.push(optionobj.options);
    })
    console.log("Hello");
    console.log(option);
    console.log(option[0]);
    console.log(option[0].option_details);
    conv.add('Thank you');
  })

Here in the console when I print the option it display the option array which is coming from the api. but when I print option[0] it comes [] and when I print option[0].option_details it comes undefined. How do I solve this?
Can someone help me with this please?

A: What is going on
In your json data, options is an array. So, this line :
option.push(optionobj.options)
will push some arrays to your option variable. In the end, option is an array of array, option[0] is an array, and option[0].option_details is undefined.
Suggestion
If I understand correctly, you want option to be an array that contains all the items from options attribute. You can use the spread operator to do that, change from :
option.push(optionobj.options)
to :
option.push(...optionobj.options);
the spread operator will push all the items in optionobj.options (not the array itself, that's the difference) to option
You can find more info about spread syntax here


text:
Q: How to add variable and do loop in CSS Is it possible to add variable and do loop in css like php:
for($a=6; $a<9; $a++) { "#divShow"+$a }

So, the result will be:
#divShow6 #divShow7 #divShow8

Any idea? Thanks in advance.

A: No. There are no 'variables' or 'loops' in CSS. It is not a Turing-complete language. This is what CSS classes are for, so you don't have to generate IDs.

A: You don't have loops in CSS, but if you want to match all the tags with an id that starts with divShow you can use (example http://jsfiddle.net/diegof79/mUGsj/):
div[id^="divShow"]

But I'll recommend to use a class instead.
Also your question shows a match of childrens: divShow8 inside a divShow7. You don't need that kind of selector, because probably the problem can be resolved in another way (by using classes or different id).
Take a look to http://www.w3schools.com/cssref/sel_nth-child.asp maybe it gives you other ideas.


text:
Q: Mapping array of props objects reduce(sum) values in objects in React I have multiple props objects and pass them into an array.
each object contains point value. I'm trying to sum all values in the objects and pass the result into Semantic-ui-react Statistics component.
const withoutSpousePointsArray = [
            withoutSpouseAgePoint,
            withoutSpouseLoePoint,
            withoutSpouseOlpPoint,
            withoutSpouseOlp2Point,
            withoutSpouseExpPoint,
            BwithSpouseLoePoint,
            BwithSpouseOlpPoint,
            BwithSpouseExpPoint,
            skillEducation1Point,
            skillEducation2Point,
            skillFwe1Point,
            skillFwe2Point,
            skillCertificatePoint,
            additionalPoint,
];
const mapStateToProps = state => ({
    // core withSpouse states
    withSpouseAgePoint: state.withSpouseAge,
    withSpouseLoePoint: state.withSpouseLoe,
    withSpouseOlpPoint: state.withSpouseOlp,
    withSpouseOlp2Point: state.withSpouseOlp2,
    withSpouseExpPoint: state.withSpouseExp,
    // core withoutSpouse
    withoutSpouseAgePoint: state.withoutSpouseAge,
    withoutSpouseLoePoint: state.withoutSpouseLoe,
    withoutSpouseOlpPoint: state.withoutSpouseOlp,
    withoutSpouseOlp2Point: state.withoutSpouseOlp2,
    withoutSpouseExpPoint: state.withoutSpouseExp,
    // Spouse factor
    BwithSpouseLoePoint: state.BwithSpouseLoe,
    BwithSpouseOlpPoint: state.BwithSpouseOlp,
    BwithSpouseExpPoint: state.BwithSpouseExp,
    // skill transferability factors
    skillEducation1Point: state.skillEducation1,
    skillEducation2Point: state.skillEducation2,
    skillFwe1Point: state.skillFwe1,
    skillFwe2Point: state.skillFwe2,
    skillCertificatePoint: state.skillCertificate,
    // Additional
    additionalPoint: state.additional,
});

Since there are multiple objects I .map() the points value first and .reduce() to sum all the values. the result showed like
so I added parsInt() the default number set to 0 but when I dispatch the action, It showed me many 0s again and the number does not add up correctly.
const withoutSpousePointSum =
        withoutSpousePointsArray.map(points => points.point)
        .reduce((acc, curr) => [parseInt(acc + curr)]);

<Points key={shortid.generate()} color={"orange"} value={withoutSpousePointSum} label={"Points"} />

Is there a solution to work this correctly? Thank you.

A: A few things about your reduce function:

*

*reduce should parse only the current value

*parseInt should pass the base as second param to force decimal parse

*reduce should pass in the initial value as the second param

-
const withoutSpousePointSum =
  withoutSpousePointsArray
    .map(points => points.point)
    .reduce((acc, curr) => acc + parseInt(curr, 10), 0);


text:
Q: illegal start of type,  expected, ';' expected errors My code:
https://github.com/LightningFastRom/android_frameworks_base/blob/next-20200913/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
I am trying to set that only if the build type is eng it will show the build number. But there's a lot of errors when compiling:
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:106: error: illegal start of type
        if (android.os.Build.TYPE.equals("eng")) {
        ^
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:106: error: <identifier> expected
        if (android.os.Build.TYPE.equals("eng")) {
                                        ^
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:106: error: illegal start of type
        if (android.os.Build.TYPE.equals("eng")) {
                                         ^
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:108: error: ';' expected
            public void onChange(boolean selfChange, Uri uri) {
                                ^
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:108: error: ';' expected
            public void onChange(boolean selfChange, Uri uri) {
                                                        ^
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:108: error: not a statement
            public void onChange(boolean selfChange, Uri uri) {
                                                         ^
error: /home/android/lineage-17.1/frameworks/base/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java:108: error: ';' expected
            public void onChange(boolean selfChange, Uri uri) {
                                                            ^

A: Its syntax error braces not closed properly
try this:
    private final ContentObserver mDeveloperSettingsObserver = new ContentObserver(
            new Handler(mContext.getMainLooper()) {
                @Override
                public void onChange(boolean selfChange, Uri uri) {
                    if (android.os.Build.TYPE.equals("eng")) {
                        super.onChange(selfChange, uri);
                        setBuildText();

                    }
                }});

A: You have problem in your code, please check this function
private final ContentObserver mDeveloperSettingsObserver = new ContentObserver(
                new Handler(mContext.getMainLooper())) {
        if (android.os.Build.TYPE.equals("eng")) {
            @Override
            public void onChange(boolean selfChange, Uri uri) {
                super.onChange(selfChange, uri);
                setBuildText();
            }
        }
    };

// new Handler(...) { }, is a functional interface and you can only write inside th `onChange` method , curly braces after constructor is class body, you cannot write statements there, so put your checks inside the function. It will compile.

A: I can see issue at lines L104 to L113. You are trying to override method based on an if condition which is not allowed. You need to put condition in method definition itself.
private final ContentObserver mDeveloperSettingsObserver = new ContentObserver(
            new Handler(mContext.getMainLooper())) {
    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
        // put if condition here
        if (android.os.Build.TYPE.equals("eng")) {
             setBuildText();
        }
    }
};


text:
Q: Java writing/editing a properties file I have a really confusing problem.
I am trying to change a property in my properties file, but it just is not changing...
Here is the code:
package config;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

    /**
     * @author Crunchify.com
     *
     */
    public class CrunchifyGetPropertyValues {
        String result = "";
        InputStream inputStream;

        public String getPropValues() throws IOException {

            try {
                Properties prop = new Properties();
                String propFileName = "config.properties";

                inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

                if (inputStream != null) {
                    prop.load(inputStream);
                } else {
                    throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
                }

                Date time = new Date(System.currentTimeMillis());

                // get the property value and print it out
                String user = prop.getProperty("user");
                String company1 = prop.getProperty("company1");
                String company2 = prop.getProperty("company2");
                String company3 = prop.getProperty("company3");
                prop.setProperty("company1", "Amazon");
                prop.store(new FileOutputStream("config.properties"), null);

                // result = "Company List = " + company1 + ", " + company2 + ", " +
                // company3;
                // System.out.println(result + "\nProgram Ran on " + time + " by
                // user=" + user);
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            } finally {
                inputStream.close();
            }
            return result;
        }
    }## Heading ##

The code am I am specifically looking at is
prop.setProperty("company1", "Amazon");
prop.store(new FileOutputStream("config.properties"), null);

For some reason my properties file won't change...
 #Crunchify Properties
    user=Crunchify
    company1=Google
    company2=eBay
    company3=Yahoo

Any help is appreciated

A: When you use getResourceAsStream( this retrieves the file from the class path. e.g. if you have a /home/user/resources in your class path, this is where it looks for the file.
If you use new FileOutputStream("config.properties") this uses the current working directory, only as you didn't specify a directory.
In short, it is writing to the properties, just not the one you are reading.  You could write to the one in the class path provided it comes from a directory however I suggest you only write to the current work directory or a directory provided in configuration.

A: I think it's because you are reading the file from one place (i.e. resources) and it might be that you are saving the file in another place (i.e. current working directory).


text:
Q: Selecting all text in a UITextView on focus only after UIAlertView I have a tableView that contains a few UITextView controls. When the user taps on one of these the text inside should be selected so that any keyboard input immediately replaces the original content.
I cannot get the text inside a UITextView selected using this code:
txtQuantity.SelectAll (new NSObject(NSObjectFlag.Empty));

as this code only shows the menu "Select | Select All' without the text being actually selected.
Has someone gotten this to work?
EDIT:
The code below select the text inside the txtQuantity control, BUT ONLY IF the UIAlert is show first! Why is this?
public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();

            txtQuantity.TouchDown += txtQuantityHandleTouchDown;

            txtQuantity.EditingDidBegin += delegate {

                txtQuantity.ExclusiveTouch=true;
                UIAlertView uv = new UIAlertView("","OK",null,"OK",null);
                uv.Show ();
            };

        }

        void txtQuantityHandleTouchDown (object sender, EventArgs e)
        {
            txtQuantity.SelectAll (this);
            txtQuantity.Selected = true;

        }

If all code within the txtQuality.EditingBegin delegate is commented out, the HandleTouchDown event does not fire.

A: I am not sure that this is what you are going for but I put together a quick sample.
The problem I was having is with calling SelectAll in EditingDidBegin. I had to make a call to BeginInvokeOnMainThread to get the select to work.  I am not sure if it is a problem with the event not happening on the main thread or you simply need to make an async call on the main thread.
using System;
using System.Collections.Generic;
using System.Linq;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace SelectText
{
    [Register ("AppDelegate")]
    public partial class AppDelegate : UIApplicationDelegate
    {
        // class-level declarations
        UIWindow window;

        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            // create a new window instance based on the screen size
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            window.RootViewController = new MyTableViewController ();

            // make the window visible
            window.MakeKeyAndVisible ();

            return true;
        }
    }

    public class MyTableViewController : UITableViewController
    {
        public override void LoadView ()
        {
            base.LoadView ();
            this.TableView.DataSource = new TableViewDataSource ();
        }
        private class TableViewDataSource : UITableViewDataSource
        {
            private class EditCell : UITableViewCell
            {
                UITextField _field;

                public EditCell () : base (UITableViewCellStyle.Default, "mycell")
                {
                    _field = new UITextField (this.Bounds);
                    _field.AutoresizingMask = UIViewAutoresizing.All;
                    _field.BackgroundColor = UIColor.Clear;
                    _field.ShouldReturn = delegate {
                        _field.ResignFirstResponder ();

                        return true;
                    };

                    _field.EditingDidBegin += delegate {
                        this.BeginInvokeOnMainThread ( delegate {
                            _field.SelectAll (this);
                        });
                    };

                    _field.Text = "Some Text";
                    this.Add (_field);
                }

                public override void LayoutSubviews ()
                {
                    base.LayoutSubviews ();
                    _field.Frame = this.Bounds;
                }

            }

            #region implemented abstract members of UITableViewDataSource
            public override int RowsInSection (UITableView tableView, int section)
            {
                return 2;
            }

            public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
            {
                UITableViewCell cell = tableView.DequeueReusableCell ("mycell");

                if (cell == null)
                {
                    cell = new EditCell ();
                }

                cell.SelectionStyle = UITableViewCellSelectionStyle.None;

                return cell;
            }
            #endregion
        }
    }
}


text:
Q: How can I capture the name of a C# static string resource property without changing the caller? Having string resources in Strings.resx/Strings.Designer.cs, used like this:
myObject.DoSomething(Strings.HelloWorld);

can I capture the resource id (i.e. "Strings.HelloWorld") in DoSomething without changing the source line that calls DoSomething? I want the name of the static property defined in Strings.Designer.cs, along with the string value.
What I've figured out is:
myObject.DoSomething(() => Strings.HelloWorld);

and then:
void DoSomething(Expression<Func<string>> expr)
{
    string id = expr.Body.ToString();
    string value = (expr.Compile())();
    // do something with these...
}

That changes the original line slightly, but it's still readable and the compiler is checking the property name for me.
I was wondering if there is any C# magic to do this without changing that original line.
EDIT: Really, I just want unique ints for each string resource that I use to format a TraceEvent message, to use as the TraceEvent id. I don't want to maintain a list of ints myself when the compiler can do that for me, adding one every time I insert a new source line to trace something else interesting. I get my ints once in initialization by mapping the ResourceSet keys to a sequence of ints, and I don't mind if the numbers shift around from build to build.
EDIT2: Referring to LBushkin's answer, I did initially map strings to int, like this:
var resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

var sorted =
    from i in resourceSet.Cast<DictionaryEntry>()
    orderby i.Key
    select i.Value as string;

var valueToId = new Dictionary<string, int>();

foreach (string value in sorted)
{
    valueToId[value] = valueToId.Count + 100; // whatever range you like
}

...but I don't like relying on a static CurrentCulture. I want a simple low-tech, low-maintenance mapping of the resource strings to unique ints, where all I need to do is add strings in the designer when I feel like it.

A: No, I'm afraid there isn't anything that will do this. The lambda expression is the closest you'll get.
EDIT: Warning - smelly code ahead
At least, that's the case if you don't want to add extra methods in another Strings class in the same namespace as the caller. Here's a really grotty hack:
// You'd want to autogenerate this class based on the designer file.
public class Strings
{
    public static string HelloWorld()
    {
        return global::OriginalNS.Strings.HelloWorld;
    }
}

then...
void DoSomething(Func<string> provider)
{
    string id = provider.Method.Name;
    string value = provider();
}

Now this:
myObject.DoSomething(Strings.HelloWorld);

is compiled into a method group conversion using the method Strings.HelloWorld. DoSomething finds the name of that method to get the ID, and calls the delegate to get the actual value.
This will only work if Strings is in a different namespace to the method calling DoSomething, so that you can hijack the use of the name Strings. I suppose another alternative would be a using directive:
using Strings = EvilStrings;

In general though: urgh! Don't do this! It's fun to think about, of course, but I wouldn't wish it on production code...

A: Unless I'm completely misunderstanding your intent, it seems like you're making things more complicated than they really need to be.
While Jon's solution is certainly creative, I would approach this much more practically.
If all you're trying to do is associate each string resource with a unique number that you can retrieve in various places, then I suggest that you write a singleton catalog to do this. The catalog would essentially be a dictionary mapping strings to unique values. Alternatively, you could use the name of the string resource property as the id, rather than a number. Either way, you could use reflection to build this on startup:
public static class StringCatalog
{
    private static readonly Dictionary<string,int> m_CatalogMap;

    static StringCatalog()
    {
        m_CatalogMap = new Dictionary<string,int>();
        // use reflection to discover and assign unique IDs to string resources
        // ... LEFT AS AN EXCERCISE ...
    }

    public static int GetId( string stringResource )
    {
        return m_CatalogMap[stringResource];
    }
}

Your consumers would then look something like:
void DoSomething(string s)
{
    int id = StringCatalog.GetId(s);

    // use the string as you would normally...
}


text:
Q: why do this defition in textbook return 2 values? In this post I will do 3 things in order:
A introduce the question
B display the answer in the textbook to this question
C show my doubt

A introduce the question
The question goes like this:

(1)
Make a list or tuple containing a series of 10 numbers and five letters.
Randomly select four numbers or letters from the list and print a message saying that any ticket matching these four numbers or letters wins a prize;
(2)
Make a list or tuple containing a series of 10 numbers and five letters.
Randomly select four numbers or letters from the list and print a message saying that any ticket matching these four numbers or letters wins a prize.

B display the answer in the textbook to this question
This answer code is from the textbook:

(1)

from random import choice

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']

winning_ticket = []
print("Let's see what the winning ticket is...")

# We don't want to repeat winning numbers or letters, so we'll use a
#   while loop.
while len(winning_ticket) < 4:
    pulled_item = choice(possibilities)

    # Only add the pulled item to the winning ticket if it hasn't
    #   already been pulled.
    if pulled_item not in winning_ticket:
        print(f"  We pulled a {pulled_item}!")
        winning_ticket.append(pulled_item)

(2)

from random import choice

def get_winning_ticket(possibilities):
    """Return a winning ticket from a set of possibilities."""
    winning_ticket = []

    # We don't want to repeat winning numbers or letters, so we'll use a
    #   while loop.
    while len(winning_ticket) < 4:
        pulled_item = choice(possibilities)

        # Only add the pulled item to the winning ticket if it hasn't
        #   already been pulled.
        if pulled_item not in winning_ticket:
            winning_ticket.append(pulled_item)

    return winning_ticket

def make_random_ticket(possibilities):
    """Return a random ticket from a set of possibilities."""
    ticket = []
    # We don't want to repeat numbers or letters, so we'll use a while loop.
    while len(ticket) < 4:
        pulled_item = choice(possibilities)

        # Only add the pulled item to the ticket if it hasn't already
        #   been pulled.
        if pulled_item not in ticket:
            ticket.append(pulled_item)

    return ticket

def check_ticket(played_ticket, winning_ticket):
    # Check all elements in the played ticket. If any are not in the
    #   winning ticket, return False.
    for element in played_ticket:
        if element not in winning_ticket:
            return False

    # We must have a winning ticket!
    return True

possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = get_winning_ticket(possibilities)

plays = 0
won = False

# Let's set a max number of tries, in case this takes forever!
max_tries = 1_000_000

while not won:
    new_ticket = make_random_ticket(possibilities)
    won = check_ticket(new_ticket, winning_ticket)
    plays += 1
    if plays >= max_tries:
        break

if won:
    print("We have a winning ticket!")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")
    print(f"It only took {plays} tries to win!")
else:
    print(f"Tried {plays} times, without pulling a winner. :(")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")

print(check_ticket(new_ticket, winning_ticket))

C Show my doubt
And my question lies in this para:
plays = 0
won = False

# Let's set a max number of tries, in case this takes forever!
max_tries = 1_000_000

while not won:
    new_ticket = make_random_ticket(possibilities)
    won = check_ticket(new_ticket, winning_ticket)
    plays += 1
    if plays >= max_tries:
        break

if won:
    print("We have a winning ticket!")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")
    print(f"It only took {plays} tries to win!")
else:
    print(f"Tried {plays} times, without pulling a winner. :(")
    print(f"Your ticket: {new_ticket}")
    print(f"Winning ticket: {winning_ticket}")

I wonder why it first define
won=False,then in the   if not won (why doesn't it say if True?)
it defines won = check_ticket(new_ticket,winning_ticket)
which can return False or True,
and at the end says if won??? is this mean if False? why doesn't it say so?
And moreover,I wonder why my code to this question connot work:

from random import choice

possibilities=['1','2','3','4','5','6','7','8','9','10','a','b','c','d','e']

def make_winning_ticket(possibilities):
    winning_ticket=[]
    while len(winning_ticket)<4:
        new_number=choice(possibilities)
        if new_number not in winning_ticket:
          winning_ticket.append(new_number)
    return winning_ticket

def make_new_ticket(possibilities):
     new_ticket=[]
     while len(new_ticket)<4:
        new_number=choice(possibilities)
        if new_number not in new_ticket:
          new_ticket.append(new_number)
     return new_ticket

play=0
max_try=100000

def check_ticket(new_ticket,winning_ticket):
    while play<max_try:
        for element in new_ticket:
            if new_ticket not in winning_ticket:
             play+=1
             make_new_ticket(possibilities)

    print(play)

make_winning_ticket(possibilities)
make_new_ticket(possibilities)
check_ticket(winning_ticket,new_ticket)

Thank you for your patience:)

A:
I wonder why it first define won=False, then in the if not won (why doesn't it say if True?) it defines won = check_ticket(new_ticket,winning_ticket) which can return False or True, and at the end says if won??? is this mean if False? why doesn't it say so?

No. It means what it says:

*

*First we have a while loop which continuously checks whether "we" have won. This decision (won or not won) is saved in a variable won.

*In order to be able to properly enter the while loop, the condition (not won) must be true, so won must be False. So it is set this way.

*After the while loop, we check hether we have won. And it clearly says so: if won: means "if we have won".

And moreover,I wonder why my code to this question connot work:

To be honest, I didn't try to follow each line of it, but what seems to be one of the biggest problems: you discard the return values of your functions.
If we have a function, say
def f(x):
    y = 2 * x
    return y

it is not sufficient to do
f(10)

and then to expect that we have done something useful: the y variable is completely inside the function. In order to get access to its value, we must do
y = f(10) # y will be 20

or even (with a completely different name than inside the function):
y1 = f(10) # y1 will be 20
y2 = f(15) # y2 will be 30

So in your example, you should do at least
winning_ticket = make_winning_ticket(possibilities)
new_ticket = make_new_ticket(possibilities)
check_ticket(winning_ticket, new_ticket)


text:
Q: "at any time" vs "on any time" vs "in any time"? How use? For example:
Should I always mount with the noinit_itable option to mount all ext4 device at(or "on" or "in") any time?
If you can't understand above text then:
"Should I always mount with the noinit_itable option to mount one ext4 device at(or "on" or "in") any time?"this new text can more help you try guess my mean?please.
link to context

A: Looking at the Collins Dictionary, there is "at any time", the other two don't exist. Also, looking at this Dictionary of examples, "at any time" is far more frequent than the other options, and when talking about time the most common preposition used is "at".


text:
Q: How to get resumptiontoken value from given xml I am getting an XML from a OAI-PMH request which contains a resumption token to get next set of records. How to get the resumption token Value and its other attributes such as completeListSize etc.
 <?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="static/style.xsl"?><OAI-PMH xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"><responseDate>2015-06-24T16:45:25Z</responseDate>
<request verb="ListRecords" metadataPrefix="uketd_dc">http://publications.iadb.org/oai/request</request>
<ListRecords>
    <record>
        <header>
            <identifier>oai:publications.iadb.org:11319/195</identifier>
            <datestamp>2015-06-12T23:02:48Z</datestamp>
            <setSpec>com_123456789_1</setSpec>
            <setSpec>col_123456789_3</setSpec>
        </header>
        <metadata></metadata>
    </record>
 <resumptionToken completeListSize="6305" cursor="0">MToxMDB8Mjp8Mzp8NDp8NTp1a2V0ZF9kYw==</resumptionToken>
</ListRecords>

I tried the below code
 XDocument root= XDocument .Load("http://publications.iadb.org/oai/request?verb=ListRecords&metadataPrefix=uketd_dc");
        var tokenValue= root.Element("resumptionToken").Value;

Its returning object reference error.Please help.

A: Element returns an immediate child element. From the context of your document, the only element available to you is OAI-PMH - this is why you're getting the null reference exception.
In addition, your target element has a namespace as defined by the default namespace declaration (xmlns="...") in the root OAI-PMH element.
You can use Descendants to find any element in the document with your required name, so this short code should work:
XNamespace ns = "http://www.openarchives.org/OAI/2.0/";
var tokenValue = (string)root.Descendants(ns + "resumptionToken").Single();


text:
Q: Rewriterule .htaccess in subfolder I need to perform a rewrite in a subfolder using the .htaccess file. The current url has a form like:
domain.com/subfolder/chapter.php?urlkey=name

It needs to be rewritten to:
domain.com/subfolder/chapter/name

In the subfolder I have a .htaccess file with the following code:
<IfModule mod_rewrite.c>
    Options -Indexes
    RewriteEngine On
    RewriteBase /subfolder/

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^chapter/([a-z0-9]+)/?$ chapter.php?urlkey=$1 [L,NC,QSA]
</IfModule>

Modrewrite is enabled, but for some reason when I go to the url
domain.com/subfolder/chapter/name

It returns the following error:
Notice: Undefined index: urlkey

A: Have this code in subfolder/.htaccess:
Options -MultiViews
RewriteEngine On
RewriteBase /subfolder/

RewriteRule ^chapter/([\w-]+)/?$ chapter.php?urlkey=$1 [L,NC,QSA]

Option MultiViews (see http://httpd.apache.org/docs/2.4/content-negotiation.html) is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So if /file is the URL then Apache will serve /file.html.
Also there is no need to rewrite to chapter?... you can rewrite to chapter.php?...

A: Your error is not related to htaccess rules.
Notice: Undefined Index
Happens when you try to access an array by a key that does not exist in the array.
A typical example for an Undefined Index notice would be check sample code below.
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];

Both spinach and 1 do not exist in the array, causing an to be triggered.
The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists or isset:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in array';
}

If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then $_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

The notices above appear often when working with $_POST, $_GET or $_SESSION. For $_POST and $_GET you just have to check if the index exists or not before you use them. For $_SESSION you have to make sure you have the session started with session_start() and that the index also exists.

A: When removing RewriteBase it does working for me
put this in subfolder please check
Options -Indexes
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^chapter/([a-z0-9]+)/?$ chapter.php?url=$1 [L,NC,QSA]

and you have to add chapter.php? instead of chapter?.


text:
Q: Deprecation of TableRegistry::get() I'd like to ask what are your thought on deprecation of the TableRegistry::get() static call in CakePHP 3.6?
In my opinion it was not a good idea.
First of all, using LocatorAwareTrait is wrong on many levels. Most important, using traits in such way can break the Single Responsibility and Separation of Concerns principles. In addition some developers don't want to use traits as all because they thing that it breaks the object oriented design pattern. They prefer delegation.
I prefer to use delegation as well with combination of flyweight/singleton approach. I know that the delegation is encapsulated by the LocatorAwareTrait but the only problem is that it exposes the (get/set)TableLocator methods that can be used incorrectly.
In other words if i have following facade:
class Fruits {
    use \Cake\ORM\Locator\LocatorAwareTrait;

    public function getApples() { ... }
    public function getOranges() { ... }
    ...
}

$fruits = new Fruits();

I don't want to be able to call $fruits->getTableLocator()->get('table') outside of the scope of Fruits.
The other thing you need to consider when you make such changes is the adaptation of the framework. Doing TableRegistry::getTableLocator()->get('table') every time i need to access the model is not the best thing if i have multiple modules in my application that move beyond simple layered architecture.
Having flyweight/singleton class like TableRegistry with property get to access desired model just makes the development more straight forward and life easier.
Ideally, i would just like to call TR::get('table'), although that breaks the Cake's coding standards. (I've created that wrapper for myself anyways to make my app bullet proof from any similar changes)
What are your thoughts?


text:
Q: "No database provider has been configured for this DbContext" I'm getting this error message when trying to reach my ASP .NET Core 3.1 Web API with Postman:

InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

However, I do have configured it using AddDbContext in Startup.cs:
public void ConfigureServices(IServiceCollection services)
        {
            ..

            string connectionString = Configuration.GetConnectionString("ViewQlikDatabase");
            services.AddDbContext<QlikDbContext>(options => options.UseSqlServer(connectionString));
        }

I have checked the connection string and it is correctly retrieved.
The DbContext also has the recommended constructor:
public QlikDbContext(DbContextOptions<QlikDbContext> options)
        : base(options)
    {
    }

The exception is raised when I try to call the context in my business class:
public string SedeGetTotaleElementiVista()
    {
        using (var db = new QlikDbContext())
        {
            // Exception raised here
            int count = db.ViewQlikSede.Count();

            return count.ToString();
        }
    }

Can someone please tell me what's wrong?

A: The context must be injected. If you new it up yourself, the service registration doesn't come into play at all. Here, you're creating it yourself, and not passing anything into it, so this instance definitely doesn't have a provider configured.


text:
Q: Lipschitz continuous and differentiability Hey i'm trying to solve this question:
Let U be an open interval in R and a ∈ U.
Prove that if f : U → R is Lipschitz
continuous, then $g(x) = (f(x) − f(a))^2$
is differentiable at a.
so far I have the following, but im not sure how to piece it all together
$|f(x) - f(y)| \le k|x-y|$
=> $ (f(x) − f(a))^2 \le (k|x-a|)^2$
if $g(x)$ is differentiable at a then $\lim_{x\to a} \frac{g(x) - g(a)}{x - a }$ must exist
$\lim_{x\to a} \frac{g(x) - g(a)}{x - a }  = \lim_{x\to a} \frac{(f(x) − f(a))^2 - (f(a) − f(a))^2}{x - a } = \lim_{x\to a} \frac{(f(x) − f(a))^2}{x - a } \le \frac{(k|x-a|)^2}{x-a} = k^2(x-a)$
and from here im not sure where to go to show the limit exists

A: hint
For $x\ne a$,
$$|\frac{g(x)-g(a)}{x-a}|=$$
$$|\frac{f(x)-f(a)}{x-a}||f(x)-f(a)|$$
$$\le K|f(x)-f(a)|$$$f$ is continuous at $a$ then
$$\lim_{x\to a}(f(x)-f(a))=0$$
then
$$g'(a)=0.$$

A: To prove that, we find the left and write limits.$$\lim_{x\to a^+} \frac{g(x) - g(a)}{x - a }=\lim_{x\to a^+} \frac{g(x)}{|x - a|}$$since $$0\le {g(x)\over|x-a|}\le k|x-a|$$by squeeze theorem we have $$\lim_{x\to a^+} \frac{g(x) - g(a)}{x - a }=0$$For the left limit we obtain$$\lim_{x\to a^-} \frac{g(x) - g(a)}{x - a }=\lim_{x\to a^-} -\frac{g(x)}{|x - a| }$$while we have $$-k|x-a|\le -{g(x)\over x-a}\le 0$$then the Squeeze theorem is still applicable and we finally have $$\lim_{x\to a} \frac{g(x) - g(a)}{x - a }=0$$or $$g'(a)=0$$

A: Note that $\lim_{x\to a} k^2|x-a|=0$. So you get that $|\frac{g(x)-g(a)}{x-a}|$ is non negative on the one hand, and on the other hand it is bounded from above by a function that converges to $0$ when $x\to a$. Hence by the squeeze theorem the limit exists and equals $0$. Of course we also use the known fact that a function converges to $0$ if and only if its absolute value converges to $0$.


text:
Q: Where to enter commands to compile and run C program that resides in gedit? I am running Ubuntu. Please advise where I should enter the command to compile the C++ program that I have entered in gedit.
Please also advise if I need to relocate the C program before trying to compile and run it, and where I should relocate it.

A: Save the file somewhere as program.cpp then open a terminal and cd to the directory you saved the file.
To compile the program with gcc run gcc -o program program.cpp. If there are no errors in the program this will output a binary with your compiled program called program which you can run with ./program in the terminal.


text:
Q: grid-auto-rows .vs min-height. What is the difference? What is the difference between these two codes? What is the advantage of using grid-auto-rows while we can simply achieve the same result using a more simple rule such as min-height? I personaly cannot find a major difference!
In the first one, I used grid-auto-rows to control the height of rows.
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: minmax(100px , auto);
}

.item {
  border: 2px solid blue;
  background-color: bisque;
}

In the following code, I used min-height of the children in order to achieve the same result.
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.item {
  border: 2px solid blue;
  background-color: bisque;
  min-height: 100px;
}

I know that from the developer's point of view, the first one might be better because the user of this theme do not need to apply class "item" to all the children elements. However, I am curious to know if there is any differences in the final output.


text:
Q: Camel Kafka S3 Source Connector with multiple connectors for same bucket I am trying to define Camel S3 Source connectors. I have searched quite a bit without success to find answers to below questions.

*

*How can I set up my connector  such that the file in the S3 bucket doesn't get deleted but can  be moved to another folder specified by me, after it  is processed

*Is it possible  to define separate connectors with different value converters for the same bucket, maybe by folders  under the bucket?  The connectors will use different kafka topics based on the file type.  How can I define the bucket with folder when defining the connector properties

Thank you


text:
Q: Implement password recovery best practice I want to to implement password recovery in my web application.
I'd like to avoid using secret questions.
I could just send the password by e-mail but I think it would be risky.
Maybe I could generate a new temporary random password and send it by e-mail but I think it is as risky as the above point.
Can I send a url by e-mail for example http://example.com/token=xxxx
where xxxx is a random token associated with the user. So when the user navigates to that url he/she can reset the password.

A: When I was in the Air Force the security rule we had was: When setting or resetting passwords, do not send the user id and the password in the same email. That way, if someone is intercepting emails snooping for passwords, he has to successfully intercept BOTH emails, and be able to connect them, to breach security.
I've seen a lot of sites that use the "go to this URL to reset your password". Maybe I'm missing something -- I don't claim to be a security expert -- but I don't see how that is any more secure than just inventing a new, temporary password and sending it. If a hacker intercepts the email, why can't he go to that link and see the new password as well as the legitimate user could? It looks to me like extra hassle for the user with no security gain.
By the way, congratulations on NOT using security questions. The logic of this device escapes me. Since the dawn of computer security we have been telling people, "DON'T make a password that is information about yourself that a hacker could discover or guess, like the name of your high school, or your favorite color. A hacker might be able to look up the name of your high school, or even if they don't know you or know anything about you, if you still live near where you went to school they might get it by tryinging local schools until they hit it. There are a small number of likely favorite colors so a hacker could guess that. Etc. Instead, a password should be a meaningless combination of letters, digits, and punctuation." But now we also tell them, "But! If you have a difficult time remembering that meaningless combination of letters, digits, and punctuation, no problem! Take some information about yourself that you can easily remember -- like the name of your high school, or your favorite color -- and you can use that as the answer to a 'security question', that is, as an alternative password."
Indeed, security questions make it even easier for the hacker than if you just chose a bad password to begin with. At least if you just used a piece of personal information for your password, a hacker wouldn't necessarily know what piece of personal information you used. Did you use the name of your dog? Your birth date? Your favorite ice cream flavor? He'd have to try all of them. But with security questions, we tell the hacker exactly what piece of personal information you used as a password!
Instead of using security questions, why don't we just say, "In case you forget your password, it is displayed on the bottom of the screen. If you're trying to hack in to someone else's account, you are absolutely forbidden from scrolling down." It would be only slightly less secure.
Lest you wonder, when sites ask me for the city where I was born or the manufacturer of my first car, I do not give an actual answer tot he question. I give a meaningless password.
</rant>

A: First off, do not store a plain-text copy of the user's password, or even an encrypted version. You want to only ever keep a hashed copy of the user's password.
As for recover solutions, I find that the recovery link to change the user's password is the best solution in my experience. It will probably be a bit more convenient for the user, while being largely the same from a security point of view as sending a new random password to be changed after next login. I'd still recommend having the recovery url expire after a reasonable short period of time, as well as only being usable a single time.

A: I don't unnderstand the attitude towards the secret question method. It's not like I am going to make my password "BlueHouse" and then make my security question "What are your two favorite things?" and the answer "Blue and Houses". The security question is not the magic key to get the actual password. It's usually a way to get a new password sent to the email address on file. I don't know how else you guys do it, but it sounds like you do one of two things.
1) The user clicks a "I forgot my password" button and the new password is sent to the user.
2) The user clicks a "I forgot my password" button and then has to answer a security question before getting the new password emailed to the address on file.
Seems to me that option number 2 is more secure.
Why is sending a token any more secure than sending the password? If an email account has been hacked, it's been hacked. It doesn't matter if there is a link to reset the password, a token, or a new password. Don't forget, most sites don't say "The new password has been sent to the following email address for you to hack into". A hacker would need to guess the email address that needs to be hacked.

A: I agree with Andy.  Aren't security questions normally independent of the password? (mine are)  Meaning they have a question and an answer and aren't related to the password.  It seems like this is used to prevent spurious password reset requests and actually does have a use.
Imagine - someone could go to a site's "forgot password" utility and enter a zillion email addresses - or just one person they want to annoy.  If the password is reset at that point, the people belonging to those email addresses would have to then notice in their email the password reset and login to the site with the reset password next time they went there.  With the security question, this isn't as easy for someone to do.
I see Amazon sends a link to the given email.  They also require you to enter a captcha to prevent DOS attacks.  Because it's a link, I imagine that means they did not reset the password immediately and it would be reset once the user clicks the link.  With the scenario above, the user would just see the email and note that "no I didn't do that" and go about their business not having to change their password needlessly.  A security question might have prevented the attempt at the beginning and the legit user from getting the email in the first place.
Here's a whitepaper on it:
http://appsecnotes.blogspot.com/2010/09/latest-forgot-password-best-practices.html
This one actually recommends secret questions as a major part of the authentication process.  And sending an authentication code via email and requesting it is just an add-on layer you can optionally include.

A: It really comes down to how much security you want to have. One the one end of the extreme is a password reset process that involves contacting and certifying that you are who you claim to be, e.g. via id, because your mailbox could be compromised as well. Actually, as people tend to use the same password everywhere this is very likely. On the other end there is the standard approach that involves just sending out an email with a random new password.
"Secret" questions and answers are just another form of username and passwords with the fatal flaw that they are usually incredibly easy to guess, so good that you don't want to use them.
To your point about the token, I don't think it makes a big difference in overall security. Whether you send out a token that allows a user to change the password or whether you send out a random password right away doesn't make a big difference.
Just make sure the token is only usable once and preferably only in a limited time span, e.g. +24h after requesting it.
And, as pointed out by previous answers, NEVER EVER store plain passwords. Hash them. Preferably add salt.

A: Here's how I resolved it:
I added retrieve_token and retrieve_expiration fields to my 'users' table.
The user requests a password reset by providing their email and filling out captcha. A random hashed value is generated for their retrieve_token field - i.e. md5($user_id.time()), while retrieve_expiration will be set to a datetime that expires in next 45 minutes. Email is sent out to the user with a link:
https://example.com/reset-password?retrieve_token=912ec803b2ce49e4a541068d495ab570
SSL should be mandatory when authentication is required. You can also add a table for logging reset requests that stores email and the IP address. It helps track down possible brute attacks and you can block attacker's IP if necessary.
You could implement security question for requesting password reset, but I feel captcha would be enough to discourage anyone from repeating the request multiple times.

A: Hard to say what you should do, as pretty much any solution to this problem will weaken security. Unless maybe you want to investigate sending an SMS, callback verification, one-time password generators, or other such schemes that take password recovery to a different medium.
However, what you should not do:

*

*Send the password - because after all, as has already been mentioned, you don't have it.

*Generate a new temporary password - not only is this as insecure as sending the password, it also leads to the possibility of a denial of service attack. I can go to the site, pretend to be you, request a new password and then (if you haven't checked your email) you can't log in, don't know why and have to request a new new password ...
The token is probably the way to go. Receiving it notifies a forgotten password request, but doesn't take any action unless you confirm. You would also make it a one-time token with a relatively short expiry time to limit risk.
Of course, a lot depends on the application. Obviously protecting financial and other sensitive information is more critical than preventing your account being hacked on mytwitteringfacetube.com, because while it's inconvenient, if someone wants to steal someone's identity on a social network site, they can just open their own account and masquerade with stolen information anyway.

A: @Jay. The reason why you go to a URL to reset your password instead of just sending someone a new temporary password is more than just security. Without something like a URL with a token, a person could reset another persons password. There is no need to gain access to the email. If someone had a bone to pick with someone, they could just keep initiating a new password reset. Then the poor target has to logon and change the password again and again.
By sending a token, the user's password does not change until they login with it and confirm it. The spam of reset emails can be ignored. Tokens are just as easy (if not easier) to generate as a new password by using a GUID, it's not really extra hassle for the developer.
Also, because the GUID is unique (a generated password might not be), a token can be tied to a username. If the incorrect username is given on the URL, then the token can be cancelled (i.e. when a different person initiates it and someone intercepts it.. assuming that the username isn't the same as the email).

A: Obviously, you can't send the original password by email, because you're not storing it (right?!).  Sending a temporary password (that must be changed, because it only works for one login), and a link to reset the password are equivalent from a security point of view.

A: @Jay. The proper use of security questions is to initiate a password reset email, not for actually resetting the password. Without a mechanism such as a security question, one could initiate a password reset. Althought seemingly beign, sending a reset email could be sent to an email that might no longer belong to the original owner. This is not rare. For example, when employees leave a company, often those mails are forwarded to another employee. A security question, adds a low level of obfucation to that scenario. It also reduces issues where one person keeps initiating a password reset on the wrong account causing some poor sod to get unintentionally spammed. Security question are really not meant to be truely secure, they are just meant to reduce scenarios such as those. Anyone using a security question to actually reset the password is doing it wrong.

A: Regarding security question/answer. As a user of websites I personally don't use them (I enter garbage in them). But they are certainly not useless or meaningless as some say here.
Consider this situation:
A user of your site has left his desk to go to lunch and didn't lock his workstation. A nefarious user can now visit the page for recovering/resetting password and enter the user's username. The system will then email the recovered/reset password without prompting for the security answer.

A: Here's an example of how someone did it with Node.js, basically generate a random token, an expiry time, send out the link with the token attached, have a reset/:token route that ensures a user exists with that token (which is also not expired) and, if so, redirect to a reset password page.
http://sahatyalkabov.com/how-to-implement-password-reset-in-nodejs/


text:
Q: dplyr reordering rows by string I have the following data:
library(tidyverse)

d1 <- data_frame(Nat = c("UK", "UK", "UK", "NONUK", "NONUK", "NONUK"),
 Type = c("a", "b", "c", "a", "b", "c"))

I would like to rearrange the rows so the dataframe looks like this:
d2 <- data_frame(
 Nat = c("UK", "UK", "UK", "NONUK", "NONUK", "NONUK"),
 Type = c("b", "c", "a", "b", "c", "a"))

So the UK and Non UK grouping remains, but the 'Type' rows have shifted. This questions is quite like this one: Reorder rows conditional on a string variable
However the answer above is dependent on the rows you are reordering being in alphabetical order (excluding London). Is there a way to reorder a string value more specifically where you select order of the rows yourself, rather than relying on it being alphabetical? Is there a way to do this using dplyr?
Thanks!

A: You could use match
string_order <- c("b", "c", "a")
d1 %>%
  group_by(Nat) %>%
  mutate(Type = Type[match(string_order, Type)]) %>%
  ungroup()
#  A tibble: 6 x 2
#  Nat   Type
#  <chr> <chr>
#1 UK    b
#2 UK    c
#3 UK    a
#4 NONUK b
#5 NONUK c
#6 NONUK a

A: What about explicit the levels in a dplyr chain, to choose your order:
library(dplyr)
d1 %>%
arrange(factor(.$Nat, levels = c("UK", "NONUK")), factor(.$Type, levels = c("c", "b","a")))

# A tibble: 6 x 2
  Nat   Type
  <chr> <chr>
1 UK    c
2 UK    b
3 UK    a
4 NONUK c
5 NONUK b
6 NONUK a

Another example:
d1 %>%
arrange(factor(.$Nat, levels = c("UK", "NONUK")), factor(.$Type, levels = c("b", "c","a")))
# A tibble: 6 x 2
  Nat   Type
  <chr> <chr>
1 UK    b
2 UK    c
3 UK    a
4 NONUK b
5 NONUK c
6 NONUK a


text:
Q: How to remove all cells which contain supersets of other cells? I am working in text mining. I have 23 sentences that I have extracted from a text file along with 6 frequent words extracted from the same text file.
For frequent words, I created 1D array which shows words and in which sentences they occur. After that I took the intersection to show which word occurs with which each of other remaining words in sentence:
OccursTogether = cell(length(Out1));
for ii=1:length(Out1)
    for jj=ii+1:length(Out1)
        OccursTogether{ii,jj} = intersect(Out1{ii},Out1{jj});
    end
end
celldisp(OccursTogether)

The output is somehow like this:
OccursTogether[1,1]= 4 3
OccursTogether[1,2]= 1 4 3
OccursTogether[1,3]= 4 3

In above [1,1] shows that word number 1 occurs with word 1 in sentence 4 and 3, [1,2] shows word 1 and word 2 occurs in sentence 1 2 and 3 and so on.
What I want to do is to implement an element absorption technique, which will remove all cells which contain supersets of other cells. As we can see above 4 and 3 in [1,1] are subset of [1,2] so OccursTogether[1,2] entry should be deleted and output should be as follows:
occurs[1,1]= 4 3
occurs[1,3]= 4 3

Remember this should check all the possible subsets of entries in the system.

A: I think this does what you want:
[ii, jj] = ndgrid(1:numel(OccursTogether));
s = cellfun(@(x,y) all(ismember(x,y)), OccursTogether(ii), OccursTogether(jj));
s = triu(s,1); %// count each pair just once, and remove self-pairs
result = OccursTogether(~any(s,1));

Example 1:
OccursTogether{1,1} = [4 3]
OccursTogether{1,2} = [1 4 3]
OccursTogether{1,3} = [1 4 3 5];
OccursTogether{1,4} = [1 4 3 5];

gives
>> celldisp(result)
result{1} =
     4     3

OccursTogether{1,2} is removed because it's a superset of OccursTogether{1,1}. OccursTogether{1,3} is removed because it's a superset of OccursTogether{1,2}. OccursTogether{1,4} is removed because it's a superset of OccursTogether{1,3}.
Example 2:
OccursTogether{1,1} = [10 20 30]
OccursTogether{1,2} = [10 20 30]

gives
>> celldisp(result)
result{1} =
    10    20    30

OccursTogether{1,2} is removed because it's a superset of OccursTogether{1,1}, but OccursTogether{1,1} is not removed even if it's a superset of OccursTogether{1,2}. The comparison is done only with previous sets (third line of code).


text:
Q: 2 way XML update between Booking.com and Google Calendar Hi my name is David and I'm looking for a wizz answer on this one ;-)
A 2 way XML update between Booking.com and Google Calendar is it possible ?
And I don't mean the affiliate or something Booking.com I mean the Extranet.
So is channel management possible between Booking.com / Hotels.de and Google Calendar.
Thus being said that on http://googlesystem.blogspot.nl/2013/08/sites-that-integrate-with-google-now.html :
There's a long list of sites that integrate with Google Now: Air Berlin, Air Canada, Emirates, Booking.com, Lastminute.com, TicketWeb, Ticketfly, Orbitz, CheapTickets, OpenTable, Fandango, Rotten Tomatoes, Zillow and more.
This would be a great step for small business like mine..
Thanks in advance....
D.Corper

A: Here I have built a calendar based on the booking data that cam out from MySQL database
http://www.jardim-dos-aloes.com/en/rooms.php?currencyid=3
It can be modified to read from an XML file.


text:
Q: Why does the Python descriptor __set__ not get called I have a descriptor on a class, and its __set__ method does not get called. I have been looking long and hard on this for a few hours and have no answer for this. But what I noticed below is that when I assign 12 to MyTest.X, it erases the property descriptor for X, and replaces it with the value of 12. So the print statement for the Get function gets called. That's good.
But the print statement for the __set__ function does NOT get called at all. Am I missing something?
class _static_property(object):
    ''' Descriptor class used for declaring computed properties that don't require a class instance. '''
    def __init__(self, getter, setter):
        self.getter = getter
        self.setter = setter

    def __get__(self, instance, owner):
        print "In the Get function"
        return self.getter.__get__(owner)()

    def __set__(self, instance, value):
        print "In setter function"
        self.setter.__get__()(value)

class MyTest(object):
    _x = 42

    @staticmethod
    def getX():
        return MyTest._x

    @staticmethod
    def setX(v):
        MyTest._x = v

    X = _static_property(getX, setX)

print MyTest.__dict__
print MyTest.X
MyTest.X = 12
print MyTest.X
print MyTest.__dict__

A: The other two answers allude to using metaclasses to accomplish what you want to do. To help learn about them, here's an example of applying one to the code in your question that makes it do what you want:
class _static_property(object):
    """Descriptor class used for declaring computed properties that
       don't require a class instance.
    """
    def __init__(self, getter, setter):
        self.getter = getter
        self.setter = setter

    def __get__(self, obj, objtype=None):
        print("In the getter function")
        return self.getter(obj)

    def __set__(self, obj, value):
        print("In setter function")
        self.setter(obj, value)

class _MyMetaClass(type):
    def getX(self):
        return self._x

    def setX(self, v):
        self._x = v

    X = _static_property(getX, setX)

class MyTest(object):
    __metaclass__ = _MyMetaClass  # Python 2 syntax
    _x = 42

#class MyTest(object, metaclass=_MyMetaClass):  # Python 3 (only) syntax
#    _x = 42

print(MyTest.__dict__)
print(MyTest.X)
MyTest.X = 12
print(MyTest.X)
print(MyTest.__dict__)

Classes are instances of their metaclass which is normally type type. However you can use that as a base class and derive your own specialized meta-subclass -- that in this case is one that has class attributes which are data descriptors (aka properties). Note that the self argument in a meta or meta-subclass method is a metaclass instance, which is a class. In code above, it's named MyTest.

A: Descriptors work on instances of classes, not classes themselves.  If you had an instance of MyTest, X would work as you expect, but accessing it as a class attribute actually sets the attribute of the class object itself.  You could try defining a custom metaclass to add the descriptor to, then creating MyTest with that metaclass.

A: The __set__ only gets called when you assign to X of an instance
If you want this to work for a class attibute, you'll have to set up the descriptor on the metaclass of MyTest


text:
Q: Understanding notation of norm with three vertical lines We usually denote a norm with the notation $||\cdot ||$. However I've seen someone write $|||\cdot|||$. Is this the same as $||\cdot||$?
For instance, I have readed a note regarding functional analysis. A lemma states:
Lemma: Let $A$ be a Banach algebra with identity $I$. Then there is a norm $|||\cdot|||$ on $A$, equivalent to the original norm, such that $(A,|||\cdot|||)$ is a unital Banach algebra with $|||I|||=1$.
I am just curious. Could we just write the lemma as e.g.
Lemma: Let $A$ be a Banach algebra with identity $I$. Then there is a norm $||\cdot||$ on $A$, equivalent to the original norm, such that $(A,||\cdot||)$ is a unital Banach algebra with $||I||=1$.

A: So first, when we say something like let "$A$ be a Banach Algebra", we are implicitly assuming that there is a norm $||\cdot||$ defined on $A$ (after all, a Banach Algebra, by definition, is a type of normed space). The lemma which you have stated is saying something different. It might be the case that even though $|| \cdot ||$ is a norm, that $ ||I|| \neq 1$ with the norm $A$ has been endowed with. However, what the lemma is saying is that there exists a different norm, which they are denoting by $|||\cdot|||$, on $A$ such that $||| I ||| = 1$. They are stating this different norm is equivalent to the original norm $|| \cdot ||$ that $A$ was endowed with. The two norms are equivalent but they are not necessarily the same. Two norms $p$ and $q$ on a vector space $X$ over $\mathbb{R}$ (or $\mathbb{C}$) are equivalent if there exists real numbers $c, C >0$ such that $$cq(x) \leq p(x) \leq Cq(x) \  \text{for all} \ x \in X$$