text:
Q: Throwing an exception after emitting to a Flowable I am trying to map the values from Flowable<T> into Flowable<T2> but if a certain value is missing in Flowable<T> (or if the converted value is missing from Flowable<T2>) it should throw an exception. As an example:
Flowable<InitialType> messages = ....;
Flowable<EndType> results = messages.map(value -> convertType(value))
                                    .HereItShouldThrow(() ->
                                           if(missingValue) {
                                                throw new Exception();
                                     });

What is the best way to do this? Use concatWith on the mapped values with some kind of lambda function that tracks the state with a boolean? Is there some function on Flowable that better fits this?

A: I ended up solving this by tracking the state with an AtomicBoolean and then using the doOnComplete function for Flowables to throw an Exception.
i.e.
AtomicBoolean foundValue = new AtomicBoolean(false);
Flowable<InitialType> messages = ....;
Flowable<EndType> results = messages.map(value -> {
                                          if (typeSoughtAfter) {
                                              foundValue.set(true);
                                          }
                                          convertType(value);
                                        }).doOnComplete(() -> {
                                          if (foundValue.get()) {
                                              throw new Exception(""Value found);
                                          }
                                        });


text:
Q: Given sales data for a product, what is the best way to calculate the trend period for it? I am looking for a statistical way to calculate an approximate in-trend period for a product from its sales data over a time period.
Of course, in the 'in-trend' period, the sales of the product would be high as compared to the remaining period. But how do I come up with an approximate period for which the product was in trend? Which method/technique should I use?
In the end, I should be able to say something like "out of 1 year, the product was in trend for approx. 6 months. During this period the sales of the product were relatively high. Before and after this 6 months period, the sales of the product were relatively low."
EDIT:
Another way to put my problem, consider below example.
Let us say there is one industry (say of televisions), people tend to buy a particular television model for only 6 months after that they move to a different model for next 6 months and so on. This is what I want to get at, to find an approximate trend period for a product/industry using sales data. Is there any statistical analysis I can do to achieve this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transpose rows to columns with multiple categories dplyr I would like to use tidyr's spread function to convert a data frame with multiple id's in the rows and several columns into a df with one row where we have indicator columns for all the combinations of id's and categories.  If dplyr and tidyr is not the most appropriate for this, open to other spread-like functions.
In the script below, I'm able to only specify 1 column as the value pair.  I would like to have cat1 and cat2 as value columns.  Also, I would like the field names to be "sentid1_cat1, sentid1_cat2" etc.
test.df <- data.frame(sentid = 1:3,
                      cat1 = c(1,0,0),
                      cat2 = c(0,1,0))

test.df %>%
    spread(key = sentid, value = cat1, sep = '_')

EDIT
Desired output:
output.df <- data.frame(sentid1_cat1 = 1,
                        sentid1_cat2 = 0,
                        sentid2_cat1 = 0,
                        sentid2_cat2 = 1,
                        sentid3_cat1 = 0,
                        sentid3_cat2 = 0)

A: A solution with dplyr + tidyr:
library(dplyr)
library(tidyr)

test.df %>%
  gather(variable, value, -sentid) %>%
  unite(variable, sentid, variable) %>%
  mutate(variable = paste0("sentid", variable)) %>%
  spread(variable, value)

Result:
  sentid1_cat1 sentid1_cat2 sentid2_cat1 sentid2_cat2 sentid3_cat1 sentid3_cat2
1            1            0            0            1            0            0


text:
Q: MongoDB, what does bulk find return I am trying to use bulk find to retrieve a set of documents and return the set, I am wondering what does bulk find return? My code is:
 def bulk_find(collection_name, key, value):

    bulk = db[collection_name].initialize_ordered_bulk_op()

    bulk.find({key: value})

    results = bulk.execute()

So, what does bulk.find returns here? The documentation didn't specify anything about it.

A: It's returns BulkWriteOperation instance. From documentation
find(selector)
Specify selection criteria for bulk operations.

Parameters:
selector (dict): the selection criteria for update and remove operations.
Returns:
A BulkWriteOperation instance, used to add update and remove operations to this bulk operation.

In pymongo bulk is a write operations interface. If you want to retrieve multiply documents from some collection you should use method find of corresponding collection. You need just
results = db[collection_name].find({key:value})

This operation returns all documents from collection collection_name where value of key field == value.

A: bulk.find return an interface allowing you to group multiple operations you want to select data.
e.g. update, delete.
It's very efficient to group queries and send to MongodB in batches to execute. e.g. you want to increment sales commision on products from certain vendor. This commision is not straight forward and you have to apply some logic on it.
Normally, without bulk.find..., you'll be retrieving all matching documents, make change and send back to server to save.
In case of bulk.find, you are essentially doing samething but instead of sending each document back to server individually, you keep caching them in bulk. Once you call bulk.execute, driver will bundle all changes together
and send them to server.
For more information, please see https://docs.mongodb.org/manual/reference/method/Bulk.find/


text:
Q: Including config.php "inside out", code explanation I was studying on how to include config.php efficiently in ever webpage of a website and I've found a great answer here on stackoverlow.
The user "user187291" gave a very interesting answer on how to include it, recommending an "inside out" approach.
$page = isset($_GET['page'])
   ? preg_replace("/\W+/", "", $_GET['page'])
   : "home";
 include "$page.php";

The question is, why does he uses preg_replace?

A: The preg_replace() function takes the regular expression first parameter and replaces anything that matches with the second parameter in the third parameter.
I believe the author was doing this in an attempt to sanitize input from $_GET, whose values you shouldn't trust until you do.
For questions on web application security, I consult The Open Web Application Security Project, or OWASP. They have pages for PHP Security Leading Practice as well as a PHP Security Cheat Sheet

A: \W detects all char that are not in [A-Za-z0-9_] (and delete it in the case of this replace) so it is to secure page parameter.

A: preg_replace is being used to strip non alphanumeric characters from the page variable.
This is a very thin attempt at security. The code is attempting to prevent an injection attack.
Consider if the user requested the page http://www.example.com/index.php?page=/etc/passwd
Without sanitizing the input, the password file for the domain would happily be dumped to the screen.
The pattern \W+ removes invalid characters such as the '/' character, preventing simple attacks such as this.


text:
Q: AC vs DC refrigerator I'm looking to purchase a refrigerator for my van.  I plan to have an inverter installed and a battery bank.  AC refrigerators are much cheaper than DC so I prefer to go that route if possible.  The AC refrigerator has a power drawl of roughly 300KWA per year while the DC refrigerator drawls roughly 48W.  The battery bank I'm planning is 200A at 12V and the inverter is 3000VA.  Can you tell me if I can get away with the AC refrigerator and how much, if any loss I'll be dealing with?

A: There isn't enough information in your post to provide a good recommendation.  However, I can make some recommendations as follows: a) you want to optimize power efficiency, so choose a refrigerator that is just as large as you need  b) the DC refrigerator is indeed a thermoelectric-based system that is extremely inefficient and should be avoided  c) you should be able to find DC, compressor-based (refrigerant) refrigerators - this is a good option  d) also consider a propane refrigerator.


text:
Q: What happens to other component's power consumption, when uC is switched to low-power mode Currently, I am using a uC (Atmel ATtiny85-PU20), which will eventually run battery powered, and I am trying to reduce power consumption of entire circuit to maximise time between battery changes. Apart from the uC this circuit has:

*

*SR HC-04 ultrasonic range sensor module

*This ISM band (433MHz) ASK/OOK transmitter module

While I understand how to put the uC into sleep mode, only to wake-up every 8 seconds using the watch-dog timer interrupt, I was wondering, what happens to the peripheral components/modules during this time ?
My initial thought was to put a NPN BJT as a switch, controlled by a GPIO pin, to switch the Vcc fed to the 2 modules, but is the behaviour of such a switch defined when uC goes to sleep state ?

A: Many microcontrollers retain their pin output state when they go into sleep mode. The ATtiny85 certainly does (as does every AVR I've ever heard of). Usually the data sheet will say in its description of the low power modes.

A: To switch something with a microcontroller such that it stays off when the microcontroller is off, one can use a "pull-down resistor", say 100 kOhms, on the MCU's output line. This line then drives the switching part, be it a BJT, MOSFET or something else.
If the microcontroller asserts a value on the output (GPIO) pin, that overcomes the ground-ward pull of the resistor, and the result is an on or off state as desired. If the microcontroller is powered off entirely or in some state where the output is "floating", the switch sees an input of low (0 volts) courtesy the pull-down, and remains off.
N.B. One can also use pull-up resistors instead, with some circuit and logic changes - my answer merely gives a simplified overview rather than a comprehensive list of possible approaches.

A: Basically, the (internal) peripherals are shut off when the AVR goes to sleep. Which modules shut down depends on what sleep mode you enter into. The tinyx5 has three sleep modes: Idle, ADC Noice Reduction, and Power Down. Unless you need something to continue working while it sleeps, I would suggest the "Power Down Mode" which still allows the watch dog to function if that is what you will use to wake it up.
The internal modules are all driven by clocks scaled down from the CPU clock. If the clocks to any one module are turned off, then that module will stop functioning until the clock(s) turns back on. Theoretically, these modules will draw zero current when they are shut down, although there is always some level of leakage.
In addition to sleep modes, there are many steps you can take to ensure your circuit does not draw much power during operation, at least as far as the AVR is concerned. Here are a few ideas. All of these steps are outlined in the datasheet:

*

*Disable unused module clocks using the PRR register

*Shut off the analog comparator: ACSR |=_BV(ACD);

*Never leave floating pins - always use a pullup or pulldown resistor.

*Use a lower voltage power source (Vcc >= 2.7V for tinyx5, 1.8V for tinyx5V)

*Lower the CPU clock by changing the clock prescale values in CLKPR

*Disable the ADC when you are not using it: ADCSRA &= ~_BV(ADEN);

*Disable the digital input buffers you aren't using with DIDR0
As far as shutting down external peripherals, you could easily do that with a transistor as you have suggested. The I/O pins are static latches they retain their state when the AVR goes to sleep, so you could (in software) turn them off before you go to sleep and turn them on when you wake up. I would suggest you use a logic level N-channel MOSFET to connect/disconnect the devices from their ground supply (low-side switching), as long as the FET Gate threshold voltage is a bit lower than your AVR supply voltage so it fully turns ON from a high output. The MOSFET is not drawing any current through the gate when it is on (once the gate capacitor has been charged) unlike an NPN BJT which will continuously draw current while it is on. Either way, you should use an external pull down resistor (10k or so) to make sure the transistor stays off when it is supposed to be off. This will draw a bit of current, so a weak pull down is recommended (5V through 10k is only 0.5mA, 50uA through 100k).
You could also use this trick to turn off the external devices any other time you aren't using them; although they might need a bit of time to fully turn back on when you do need to use them or else they will give you strange results:

*

*Turn On Device

*Delay for a few milliseconds (whatever the recommended startup time is)

*Read sensor/ transmit data

*Delay for a few milliseconds

*Turn off device

A: This is what I found from the Atmel ATtiny85-PU20 datasheet
So this will not effect you I/O. It will only turn off the oscillator and PLL. BJT swich control is the best way for your battery operated system. Even you can cut the power to ultra sonic sensor and wireless transmitter when going in to sleep and only resume power to them on wakeup. This will increase your battery life.


text:
Q: repeat random numbers each n rows I have a large dataframe with 2 columns, like this:
                    dtm                SoC
      0     2018-03-01 00:00:00 +0000   39
      1     2018-03-01 00:00:01 +0000   39
      2     2018-03-01 00:00:02 +0000   39
      3     2018-03-01 00:00:03 +0000   39
     ...               ...              ...
2678393     2018-04-01 00:59:53 +0100   39
2678394     2018-04-01 00:59:54 +0100   39
2678395     2018-04-01 00:59:55 +0100   39
2678396     2018-04-01 00:59:56 +0100   39
2678397     2018-04-01 00:59:57 +0100   39
2678398     2018-04-01 00:59:58 +0100   39
2678399     2018-04-01 00:59:59 +0100   39

the column SoC is a random generated number between 0 and 40. I would like it to be a different random number repeated each 86400 rows (and not be the same for the entire dataframe).
To be more clear:
-rows 0-86399 1st random number
-rows 86400-172800 2nd random number
-etc
I was trying df['SoC']=np.repeat(random.randint(0,40),len(df)/86400) but there is an error "Length of values does not match length of index"
ideas? thank you in advance

A: First create array with parameter size with floor division for integer and then repeat:
#possible duplicated random values
df['SoC'] = np.repeat(np.random.randint(0,40, size=len(df) // 86400), 86400)

#unique random numbers
df['SoC'] = np.repeat(np.random.choice(np.range(0, 40),
                      size=len(df) // 86400, replace=False), 86400)

A: Another way:
arr = np.arange(40)
np.random.shuffle(arr)
arr

array([15, 30, 21,  3, 10, 19, 13, 31,  5, 32,  1, 39, 24,  6, 12,  7, 22,
       38, 27, 20, 25, 35, 14, 28, 33, 18, 29, 17, 37, 36, 34,  8,  2,  0,
        4, 11, 16, 23, 26,  9])

df['SoC'] = np.repeat(arr, 86400)


text:
Q: C# função Lambda com multiplas validações, verificação usando contains com multiplas comparações
*

*_lancamento é uma List com diversos registros

*x.localizado é um bool

*x.descricao é uma string

Estou tentando da seguinte forma
if (_lancamento.Where(x => x.Localizado && x.descricao.Contains(new List<string> { "6", "9" }))){....}
não sei se é possível fazer uma validação desta forma, tentei de varias formas em lambda e não consegui fazer funcionar. Obvio que o retorno que eu quero desse if é um True ou False

A: Cara tenta essa solução ae, compara
_lancamento.Where(x => x.Localizado && new List<string> { "6", "9" }.Contains(String.Join("", Regex.Split(x.descricao, @"[^\d]")))


text:
Q: How to make a form that updates a database? I need to update a database (basically just perform some simple queries) when a user fills in some values in my form. I need the submit button to do multiple queries like:
UPDATE table SET column1 = column1 - $_POST['bananas'] WHERE id = $steamID
UPDATE table SET column1 = column1 + $_POST['bananas'] WHERE id = $_POST['steamid']

I am using this to post the information that will be used to update the database
<form action="bananas.php" method="POST">
Amount:

<input type="text" name="bananas">

Recipient SteamID:

<input type="text" name="steamid">

<input type="submit" name="bananas|steamid">

<?php
if (isset($_POST['submit']))
  {
  // Execute this code if the submit button is pressed.
  $formvalue = $_POST['bananas'];
  $formvalue = $_POST['steamid'];
  }
  echo $_POST['bananas'];
  echo $_POST['steamid'];
?>

I can't have the queries active on the page giving errors because the values aren't filled in. They must only do the query and update my database when the user presses submit. How can I use this form to execute the queries I need when the user presses submit?
Things to note: $steamID is already the variable of the id of the user that is logged in, and I already have the connection to my database and all of that setup. The form is all I need help with.

A: Well, I just had somebody else figure it our for me, sorry for the trouble.
I was stupid enough not to realize that you must put the query in action="file.php" and now that I know, the information is here for anyone else who has this question, and my problem is solved.


text:
Q: Applying a Single to an ObservableSource and not over-reading I'm pretty new to RX in general, and rxjava in particular, pardon mistakes.
This operation depends on a two async operations.
The first uses a filter function to attempt to get a single entity from a list returned by an async Observable.
The second is an async operation that communicates with a device and produces an Observable of status updates.
I want to take the Single that is created from the filter function, apply that to pairReader(...), and subscribe to its Observable for updates. I can get this to work as shown, but only if I include the take(1) commented, otherwise I get an exception because the chain tries to pull another value from the Single.
  Observable<DeviceCredential> getCredentials() {
    return deviceCredentialService()
            .getCredentials()
            .flatMapIterable(event -> event.getData());
  }

  Single<Organization> getOrgFromCreds(String orgid) {
    return getCredentials()
      // A device is logically constrained to only have a single cred per org
      .map(DeviceCredential::getOrganization)
      .filter(org -> org.getId().equals(orgid))
      .take(1)  // Without this I get an exception
      .singleOrError();
  }

  Function<Organization, Observable<Reader.EnrollmentState>> pairReader(String name) {
    return org -> readerService().pair(name, org);
  }

getOrgFromCreds(orgid)
  .flatMapObservable(pairReader(readerid))
  .subscribe(state -> {
     switch(state) {
       case BEGUN:
         LOG.d(TAG, "Pairing begun");
         break;
       case PAIRED:
         LOG.d(TAG, "Pairing success");
         callback.success();
         break;
       case NOTIFIED_SERVER:
         LOG.d(TAG, "Pairing server notified");
         break;
     }},
     error -> {
       Crashlytics.logException(error);
       callback.error(error.getLocalizedMessage());
     });

A: If the source stream emits more than one item, singleOrError() is supposed to emit an error. Doc
For your case, use either first() or firstOrError() instead.
  Single<Organization> getOrgFromCreds(String orgid) {
    return getCredentials()
      .map(DeviceCredential::getOrganization)
      .filter(org -> org.getId().equals(orgid))
      .firstOrError();
  }

A: If I got you right, you need to make some action using previously retrieved async data. So, you could use .zip() operator.
Here is an example:
Observable.zip(
                getOrgFromCreds().toObservable(),
                getCredentials(),
                (first, second) -> /*create output object here*/
)
                .subscribe(
                        (n) -> /*do onNext*/,
                        (e) -> /*do onError*/
                );

Note, that .zip() operator will wait for both emission from two streams, and then it will create outer emission using the function you provided in "create output object here".
If you don't want to wait for both items - you can use .combineLatest().

A: The problem here turned out to be that the API was designed in an odd way (and unfortunately has extremely poor documentation). I couldn't figure out why I was getting duplicates, and thought I was using flatMapIterable incorrectly.
What the deviceCredentialService.getCredentials() call actually creates is an observable that emits DataEvent objects which are simple wrappers over a list of results, and with a flag of where the results came from.
The API designer wanted to allow the user to use locally cached data to fill the UI immediately while a longer request to a REST API executes. The DataEvent.from property is an enum that flags the source, either from the local device cache or from the remote API call.
The way I solved this was to simply ignore the results coming from local cache and only emit results from the API:
  Observable<DeviceCredential> getCredentials() {
    return deviceCredentialService()
      .getCredentials()
      // Only get creds from network
      .filter(e -> e.getFrom() == SyncedDataSourceObservableFactory.From.SOURCE)
      .flatMapIterable(e -> e.getData());
  }

  Single<Organization> getOrgFromCreds(String orgid) {
    return getCredentials()
      // A device is logically constrained to only have a single cred per org
      .map(DeviceCredential::getOrganization)
      .filter(org -> org.getId().equals(orgid))
      .singleOrError();
  }

The plan then is to use memoization to cache entities in a way that gives the implementing app access to cache invalidation. Since the provided interface doesn't allow squelching the API call, there is no way to work only with cache if the app feels its is fresh.


text:
Q: TreeView is not clickable inside div tag in asp dot net I am using treeView in my application.
the HTML design is as follows

           <asp:TreeView ID="tvLocationView" Font-Names="Calibri" Font-Size="Small" ShowLines="true"
SelectedNodeStyle-Font-Bold="true" SelectedNodeStyle-ForeColor="Green"
                runat="server" OnSelectedNodeChanged="tvLocationView_SelectedNodeChanged" Width="200px">

            </asp:TreeView>

and my c# code is
enter code here

TreeNode child = new TreeNode
                {
                    Text = "PARENT",
                    Value = "PARENT"
                };
                tvLocationView.Nodes.Add(child);

                MSSQLHelper.SqlCon = ConfigurationManager.AppSettings["SqlconString"].ToString();
                DataSet ds = MSSQLHelper.ExecSqlDataSet("SP_GetAllData", CommandType.StoredProcedure, new List<SqlParameter>()
                {
                });
                if (ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    foreach (DataRow dtrow in dt.Rows)
                    {
                        TreeNode child1 = new TreeNode
                        {
                            Text = dtrow["LOCATIONNAME"].ToString(),
                            Value = dtrow["LOCATIONNUMBER"].ToString()
                        };

                        child1.SelectAction = TreeNodeSelectAction.Select;
                        child.ChildNodes.Add(child1);

                    }
                }

if i remove div class="left" this tag then i can click on any child nodes. but in the above code, I am not able to click all child nodes.
can anyone help me out to solve this issue

A: I am new and I cannot comment I will leave it as an answer:
You have the class code of the "left" style, if you can share it to be able to mislead the causes of the error.
As a suggestion you can try adding the Z-index with negative value to the class.


text:
Q: Django View Error - NoReverseMatch I am new to django and I am trying to solve a NoReverseMatch issue. I think it has something to do with the views but i'm new to this.
The code is from a popular boiler plate repo from a few years ago. PLEASE NOTE: I tried reading like every answer on stack overflow already and have been stuck for hours.
Any help would be greatly appreciated
main urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^login/', include('shopify_app.urls')),
    url(r'^', include('home.urls'), name='root_path'),
    url(r'^admin/', admin.site.urls),
]

urls.py inside of app
from django.conf.urls import url
from shopify_app import views

urlpatterns = [
        url(r'^$', views.login, name='shopify_app_login'),
        url(r'^authenticate/$', views.authenticate, name='shopify_app_authenticate'),
        url(r'^finalize/$', views.finalize, name='shopify_app_finalize'),
        url(r'^logout/$', views.logout, name='shopify_app_logout'),
]

views.py inside of  app
from django.shortcuts import redirect, render
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.conf import settings
import shopify

def authenticate(request):

    shop = request.GET.get('shop')

    print('shop:', shop)

    if shop:
        scope = settings.SHOPIFY_API_SCOPE
        redirect_uri = request.build_absolute_uri(reverse('shopify_app.views.finalize'))
        permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri)
        return redirect(permission_url)

    return redirect(_return_address(request))

def finalize(request):
    shop_url = request.GET['shop']
    try:
        shopify_session = shopify.Session(shop_url)
        request.session['shopify'] = {
            "shop_url": shop_url,
            "access_token": shopify_session.request_token(request.REQUEST)
        }

    except Exception:
        messages.error(request, "Could not log in to Shopify store.")
        return redirect(reverse('shopify_app.views.login'))

    messages.info(request, "Logged in to shopify store.")

    response = redirect(_return_address(request))
    request.session.pop('return_to', None)
    return response

Error
NoReverseMatch at /login/authenticate/
    Reverse for 'shopify_app.views.finalize' not found. 'shopify_app.views.finalize' is not a valid view function or pattern name.
    Request Method: GET
    Request URL:    http://localhost:8000/login/authenticate/?csrfmiddlewaretoken=zEwwHeTfxK7apbAp3dSxsehsafxqjSgEM4t&shop=piepiedev.myshopify.com&commit=Install
    Django Version: 1.11.6
    Exception Type: NoReverseMatch
    Exception Value:
    Reverse for 'shopify_app.views.finalize' not found. 'shopify_app.views.finalize' is not a valid view function or pattern name.

Source code / file structure-
https://github.com/Shopify/shopify_django_app
Similar issue but not working solution-
https://github.com/Shopify/shopify_django_app/issues/13

A: Change inside authenticate(request):
redirect_uri = request.build_absolute_uri(reverse('shopify_app:shopify_app_finalize'))


text:
Q: double loops stuck in forever loop I am trying to loop over my $('.fore-col') and iterate the index position of my api call variables each time incrementing upwards.  Starting at 7 and going up by 8 until at the postion of 40.  When i run this code, it is stuck in a "forever loop" i believe and didn't stop at the index position of 40.  highest count before i pulled the plug was just over 20k.
Any help would be much appreciated!
                url: forecastURL,
                method: "GET"
            }).then(function(res) {
                console.log(res);

                $(".fore-col").each(function() {
                    for (let i = 7; i < 40; i + 8) {
                        let date = res.list[i].dt_txt;
                        let icon =
                            "https://openweathermap.org/img/wn/" +
                            res.list[i].weather +
                            ".png";

                        let temp = res.list[i].main.temp;
                        let humid = res.list[i].main.humidity;
                        console.log(date, icon, temp, humid);
                    }
                });

    ```
    enter code here

A: for (let i = 7; i < 40; i + 8) should be
for (let i = 7; i < 40; i = i + 8)


text:
Q: How to render a PDF file in Android Android does not have PDF support in its libraries. Is there any way to render PDF files in the Android applications?

A: Since API Level 21 (Lollipop) Android provides a PdfRenderer class:
// create a new renderer
 PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());

 // let us just render all pages
 final int pageCount = renderer.getPageCount();
 for (int i = 0; i < pageCount; i++) {
     Page page = renderer.openPage(i);

     // say we render for showing on the screen
     page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);

     // do stuff with the bitmap

     // close the page
     page.close();
 }

 // close the renderer
 renderer.close();

For more information see the sample app.
For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:
pdfView.fromAsset(String)
  .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
  .enableSwipe(true)
  .swipeHorizontal(false)
  .enableDoubletap(true)
  .defaultPage(0)
  .onDraw(onDrawListener)
  .onLoad(onLoadCompleteListener)
  .onPageChange(onPageChangeListener)
  .onPageScroll(onPageScrollListener)
  .onError(onErrorListener)
  .enableAnnotationRendering(false)
  .password(null)
  .scrollHandle(null)
  .load();

A: Download the source code here (Display PDF file inside my android application)
Add this dependency in your Grade:
compile com.github.barteksc:android-pdf-viewer:2.0.3
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_below="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    </RelativeLayout>

MainActivity.java
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)

                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

}

A: you can use a simple method by import
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

and the XML code is
<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.github.barteksc.pdfviewer.PDFView>

and just declare and add a file to an asset folder and just assign the name
   PDFView  pdfView=findViewById(R.id.pdfv);
    pdfView.fromAsset("agl.pdf").load();

A: I finally was able to modify butelo's code to open any PDF file in the Android filesystem using pdf.js. The code can be found on my GitHub
What I did was modified the pdffile.js to read HTML argument file like this:
var url = getURLParameter('file');

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null}

So what you need to do is just append the file path after the index.html like this:
Uri path = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/data/test.pdf");
webView.loadUrl("file:///android_asset/pdfviewer/index.html?file=" + path);

Update the path variable to point to a valid PDF in the Adroid filesystem.

A: public class MyPdfViewActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView mWebView=new WebView(MyPdfViewActivity.this);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setPluginsEnabled(true);
    mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
    setContentView(mWebView);
  }
}

A: I have made a hybrid approach from some of the answers given to this and other similar posts:
This solution checks if a PDF reader app is installed and does the following:
- If a reader is installed, download the PDF file to the device and start a PDF reader app
- If no reader is installed, ask the user if he wants to view the PDF file online through Google Drive
NOTE! This solution uses the Android DownloadManager class, which was introduced in API9 (Android 2.3 or Gingerbread). This means that it doesn't work on Android 2.2 or earlier.
I wrote a blog post about it here, but I've provided the full code below for completeness:
public class PDFTools {
    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader.
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.

     *

     * BEWARE: This method
     * @param context
     * @param pdfUrl
     * @return
     */
    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}

A: Here is how you can get the thumbnail as Bitmap from a PDF file without using any third-party library.
private fun loadThumbnailFromPdfFile(file:File, thumbnailImageView: ImageView) {
        Log.d(TAG, "loadThumbnailFromPdfFile: ")
        val mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
        // This is the PdfRenderer we use to render the PDF.
        val mPdfRenderer = PdfRenderer(mFileDescriptor)
        //check if pdf have no pages then we can't show pdf thumbnail
        if (mPdfRenderer.pageCount <= 0) {
            //No pages in pdf, can't show thumbnail
            Log.d(TAG, "loadThumbnailFromPdfFile: No pages in pdf")
        } else {
            //There are page(s) in pdf, can show pdf thumbnail
            //Use `openPage` to open a specific page in PDF.
            val mCurrentPage = mPdfRenderer.openPage(0)
            // Important: the destination bitmap must be ARGB (not RGB).
            val bitmap = Bitmap.createBitmap(mCurrentPage.width, mCurrentPage.height, Bitmap.Config.ARGB_8888)
            // Here, we render the page onto the Bitmap.
            // To render a portion of the page, use the second and third parameter. Pass nulls to get
            // the default result.
            // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
            mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
            // We are ready to show the Bitmap to user.
            thumbnailImageView.setImageBitmap(bitmap)
        }
    }

A: To add a little light to this, I would have to go with the pdf.js solution from Mozilla. Here is the link to an already well written implementation of this: https://bitbucket.org/butelo/pdfviewer/.
Here are the edits that I added in my Android Activity:
private String getInternalPDFURL(String interalPDFName){
    return "file:///android_asset/pdfviewer/index.html?pdf=" + interalPDFName + ".pdf";
}

Here are the edits I made in pdffile.js:
var url = '../' + getPDFURL();

function getPDFURL(){
    var query = window.location.search.substring(1);
    var vars = query.split("=");
    var pdfPage = vars[1];
    return pdfPage;
}

A: I used the below code to open and print the PDF using Wi-Fi. I am sending my whole code, and I hope it is helpful.
public class MainActivity extends Activity {

    int Result_code = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button mButton = (Button)findViewById(R.id.button1);

        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
                String jobName =  " Document";
                printManager.print(jobName, pda, null);
            }
        });
    }

    public void openDocument(String name) {

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        File file = new File(name);
        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        if (extension.equalsIgnoreCase("") || mimetype == null) {
            // if there is no extension or there is no definite mimetype, still try to open the file
            intent.setDataAndType(Uri.fromFile(file), "text/*");
        }
        else {
            intent.setDataAndType(Uri.fromFile(file), mimetype);
        }

        // custom message for the intent
        startActivityForResult((Intent.createChooser(intent, "Choose an Application:")), Result_code);
        //startActivityForResult(intent, Result_code);
        //Toast.makeText(getApplicationContext(),"There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("NewApi")
    PrintDocumentAdapter pda = new PrintDocumentAdapter(){

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
            InputStream input = null;
            OutputStream output = null;

            try {
                String filename = Environment.getExternalStorageDirectory()    + "/" + "Holiday.pdf";
                File file = new File(filename);
                input = new FileInputStream(file);
                output = new FileOutputStream(destination.getFileDescriptor());

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = input.read(buf)) > 0) {
                     output.write(buf, 0, bytesRead);
                }

                callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
            }
            catch (FileNotFoundException ee){
                //Catch exception
            }
            catch (Exception e) {
                //Catch exception
            }
            finally {
                try {
                    input.close();
                    output.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){

            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }

           // int pages = computePageCount(newAttributes);

            PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();

            callback.onLayoutFinished(pdi, true);
        }
    };
}

A: There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.
build.Gradle
compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

dialog_pdf_viewer
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dialog_pdf_viewer_close"
        style="@style/ExitButtonImageViewStyle"
        android:src="@drawable/popup_exit" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/white"
        android:orientation="vertical">

        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

    <View style="@style/HorizontalLine" />

    <com.pozitron.commons.customviews.ButtonFont
        android:id="@+id/dialog_pdf_viewer_button"
        style="@style/ButtonPrimary2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp"
        android:text="@string/agreed" />

</LinearLayout>

DailogPDFViewer.java
public class DialogPdfViewer extends Dialog {
    PDFView pdfView;
    byte[] decodedString;

    public interface OnDialogPdfViewerListener {
        void onAgreeClick(DialogPdfViewer dialogFullEula);

        void onCloseClick(DialogPdfViewer dialogFullEula);
    }

    public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
        super(context);

        setContentView(R.layout.dialog_pdf_viewer);
        findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
            }
        });

        findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
            }
        });

        decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);

        pdfView = ((PDFView) findViewById(R.id.pdfView));
        pdfView.fromBytes(decodedString).load();

        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
                }
                return true;
            }
        });

    }
}

A: I had problems with the GoogleDrive option, sometimes it would fail to load the document and 'com.github.barteksc:android-pdf-viewer:2.7.0', though it's documentation makes it seem very easy to load a document from a link, I failed to make it work. It was always throwing a FileNotFoundException, so upon further research I got to understand that it downloads the pdf, so you'll have to make it point to that document, which I found to be a bit tedious.
You could try using this library here. It is very easy to use and is still being maintained as of date, I don't know a few years from now if they are to stop updating it. It caches the document and you don't even need to trace it's path.
https://levelup.gitconnected.com/open-pdf-files-in-android-without-webviews-or-intents-3cc960752cca


text:
Q: How to dynamic wiki table columns  {| class="wikitable"
  |-
  |Col 1
  |Col 2
  |Col 3
  |-
  |3
  |a
  |tee
  |-
  |2
  |c
  |hot
  |-
  |5
  |b
  |apple
  |}

So we have a table, just a standard table. I would like the table columns to adjust if the window is minimized adjusted to half the screen size etc... For example 3x3 wouldn't fit in the window anymore as the window space has been halved, so dynamically adjust to 2x5.

A: Usually I just do class="wikitable;" style="width: auto" and similar. For more, see https://www.mediawiki.org/wiki/Help:Tables


text:
Q: Windows shared network printer keeps using rear tray as source I am trying to set up network printing on my Linux Mint 15 (64 bit) system (dualboot with Windows 7). The printer is a Canon PIXMA MG5100 and is connected (via USB) to a computer running Windows XP. It was shared through the printer properties menu (Control Panel > Printers and Faxes) I was able to print to this printer from my computer in Windows 7.
Using system-config-printer, I've found the printer (by entering the internal IP of the XP computer as the 'host' when adding using the "Find Network Printer" option). I've tried to print a blank page to test it, but the printer simply tries to take paper from the rear tray (of which there isn't any). I want it to use paper from the cassette, but the printer won't do that.
I've tried setting all paper source related settings (in LibreOffice and the actual printer itself) to 'Cassette'. I've also tried re-adding the printer via the CUPS web interface (not sure if that's the right name for it) at http://localhost:631. I've done it using both smb and lpd in both interfaces. In the web interface, my printer isn't automatically detected, so I have to manually add it. The driver is "Canon PIXMA MG5100 - CUPS+Gutenprint v5.2.9"
Since I am able to get the printer to start printing, and since I got it working perfectly in Windows, I believe this could be related to Linux in some way. I just want the printer to use the cassette as the paper source.
Edit: Also, on the Windows XP computer, when it tries to use rear tray paper, a message appears that tells me to load paper into the rear tray. It also mentions that when paper that is not A4 or some other standard size will be taken from the rear tray. This shouldn't be anything that could affect me since I'm printing in A4. It's not mentioned clearly, but it's possible that the printer might somehow be "thinking" that I'm not printing in A4.


text:
Q: Should I lock a whole object in a function modifying a small part of it? I'm beginning with multithreading in Java, and was confronted to the following problem.
Let's say we have an object containing a collection of integers, and other variables.
I want to create a function modifying one of the collection's integers.
Should it lock the whole object, or solely the collection?
I understand locking the whole object would work, but I'm afraid I'll have a drop in performances if other threads try to access the other variables of my objects.

A:
Should it lock the whole object, or solely the collection?

This will mainly depend on what you actually have in this class. As already mentioned you need to synchronize access to all shared mutable state so here assuming that your whole object is a shared mutable state, you will need indeed to protect any read and write access to any of its fields with an implicit or intrinsic lock.
Now the question is how are those fields linked to each other?
Indeed let's say that your fields are a List of carrots and a List of cars, they have nothing in common expect being shared mutable lists, in this case you could use one dedicated implicit or intrinsic lock per field.
But if you have for example the rate Euro to Dollar and the rate Dollar to Euro that are directly connected to each other, as you need to ensure the consistency of both fields, you will need to use the same implicit or intrinsic lock for both fields.
So to summarize if all your fields are connected to each other using one implicit or intrinsic lock for all of them will be the way to go otherwise use one dedicated implicit or intrinsic lock per group of fields that are related to each other.


text:
Q: How to make a existing column "unique" in PowerBI, so I can form a "one-to-many" relationsship? I have 40 tables. One table has 20 rows, and one of the columns have 1385 distinct values.
I would like to use this in a relationship with another table.

TableName(1385 rows) Column:Name:(1385 distinct values)

But when I try to do this in Powerbi/Manage-Relations, it will only accept the option "Many-to-Many" relationship. It reports that none of the column are "Unique".
Well, the data in the column is unique. So how can I configure this column to be unique so I can use it in a "One-to-Many" relationship"?
Do I have to edit the DAX expression and put the "DISTINCT" keyword in the expression for that column? And How?
Now I have:
    }, {"Columnname", Int64.Type}, {

A: Best way would be when you group your data in the query editor. This way your table has only distinct values and you can create your relationship.
In the query designer under Home > Group By you can group after your column.
Example
Table:

Table (2):

Relationship (One to Many):

Result:

I hope this helps.

A: what you can try is to perform remove duplicates in that table(i know its already contains distinct values but you can give it a try)... and/or just load the data again.


text:
Q: Diferença entre WADL e WSDL De forma simples, qual a diferença entre as especificações WSDL e WADL, no que se referem:

*

*Método de Acesso

*Limitações

Ainda não entendi quando devo utilizar um ou outro.

A: Eles são usados para diferentes implementações de serviços:

*

*WSDL (Web Services Description Language) é usado para descrever serviços que implementam o padrão SOAP, incluindo vários protocolos conhecidos como WS-* (e.g., WS-Addressing, WS-Reliable Messaging, WS-Security, entre outros.

*WADL (Web Application Description Language) é usado para descrever "serviços web", também conhecidos como "serviços HTTP" ou ainda "serviços REST" (ainda que não sigam a especificação REST estritamente).

De modo geral, as frameworks para a definição de serviços SOAP são mais poderosas (e mais complicadas) que aquelas que são usadas para serviços HTTP. Se você já tem um serviço e só quer descrevê-lo, você deverá usar a linguagem de descrição (WSDL ou WADL) apropriada. Se o serviço ainda vai ser desenvolvido, dependendo dos requisitos você irá escolher um modelo ou o outro.
YMMV, mas nos últimos anos a tendência vem sendo para a implementação de mais serviços HTTP puro (principalmente por serem mais fácil de serem acessados por dispositivos móveis) que os serviços SOAP, mas como quase tudo na vida, a resposta certa depende da sua situação.


text: Q: Android JUnit test GoogleMap I have written an application in Android, which shows locations fetched from an external database on a map. I want to test the application, but I am new to testing. Is there any way to write such a test that when run I can see a mocked location changing on the map?


text:
Q: Select multiple non-sequential lines of code in Rstudio In Windows the user can select and copy multiple items which are not in sequence by holding down the Ctrl key and then selecting each item by either clicking on it or via pressing the space followed by the Ctrl+C key to copy.
In RStudio, how can I select and copy multiple non-sequential lines of code?


text:
Q: Associating List Item with Google map Marker If you first look at the fiddle:
https://jsfiddle.net/80m1psmy/7/
It will be easier to understand.
Basically, the li's in the first tab "bars" work fine, if you click the li, the associated marker shows it's info. However, this doesn't work for the other tabs?
I wish to have the same functionality for all tabs.
Here is the associated code:
$('#bars-list li').each(function(i, e) {
    $(e).click(function(i) {
        return function(e) {
            google.maps.event.trigger(gmarkers[i], 'click');
        }
    }(i));
});

I guess I need to add a $(this) so that it isn't specific to one particular list, but am unsure on how to implement this?
Thank you in advance!

A: The issue is your selector #bars-list li.
Even when you add the same code for the other tabs it will not work as expected, because the index(i) will be based on the items of the current tab, not on all items, so when you click on e.g. the first item of any tab it will trigger the click always for the first marker(not for the first marker of the related category).
You must use a selector which includes all items, e.g. .lists li
https://jsfiddle.net/6mqooqd9/


text:
Q: BSOD with many errors Ok I am tired of this , I have tried all possible solution but nothing works. Now I think I need to post my case.  After many years of savings , I have finally built my favorite PC and everything was working perfectly. Here is my specs :

*

*Gigabyte Aorus b550 master

*AMD Ryzen 7 5800x

*2X AORUS RGB Memory DDR4 16GB (2x8GB) 4400MHz  ( two identical kits with total of 32 GB)

*GIGABYTE OC RTX 3070

But after just one month of use , I have moved back with my chair and it has just touched the the head of the power strip cable that was inserted into the power socket and then suddenly the computer has restarted  (and the tv ) , I don't know how this has happened since it was expected that the pc should shutdown due to power loss. Since then , the computer start crashing with many BSOD errors but the majority was with MEMORY_MANAGMENT error and then I have done the following trials :
1 ) I have reinstalled the windows , however still some BSOD crashes has happened but with less frequency than before .
2) I have changed the SSD and still getting BSOD crashes with MEMORY_MANAGMENT error .
3) I have then tested my memory with Memtest 86 with 4 passes and 0 errors. Still I was getting BSOD crashes. Still I was getting BSOD crashes.
4) For making sure that the CPU and GPU are working fine , I have made a stress test for each of them and they have passed the tests. Still I was getting BSOD crashes.
5) I have then plugged in only 2 sticks at a time. The system was working fine and all the combinations have worked good with no BSOD crashes.
6) Now , I have again plugged in the 4 sticks and the system is working fine till now (  I will edit the post if any crashes happens ) , however , the memory speed is now 2666 Mhz although XMP is enabled instead of 4400 Mhz :( . Also the volt is 1.5V ( I don't have any idea about RAM voltages by the way , its just for your own information ).
Note : My Bios version is the latest version . Now I don't know what to do to fix back my RAM speed and I have no Idea what is going on with my PC right now and causing these issues.


text:
Q: Using map function instead of for loop in R Apologies if this is a dumb question- I am quite new to R and have been trying to teach myself. I've been trying to rewrite the following code using a map function instead of a for loop.
  columnmean <- function(y){
  nc <- ncol(y)
  means <- numeric(nc)
  for(i in 1:nc){
    means[i] <- mean(y[, i])
  }
  means
}

columnmean(mtcars)

My code which uses map prints out means but it also adds the column names as well. How do I utilize map properly to avoid this? Should I be using imap or map2? Thanks!
columnmean1 <- function(y){
  nc <- ncol(y)
  means <- numeric(nc)
  map(y, function (y) means <- mean(y) )
}

columnmean1(mtcars)

A: You can use map_dbl :
columnmean_map <- function(y){
   purrr::map_dbl(y, mean)
}

You can also use summarise_all
columnmean_summarise <- function(y){
   dplyr::summarise_all(y, mean)
}


text:
Q: Is it possible to execute Event Hub triggered Azure Functions locally without using an actual Event Hub? I just want to ask if it is possible to execute an Azure Function (Event Hub trigger) purely on my local machine without depending on any Azure Event Hubs resource?
I've been following Microsoft's process in developing Azure Functions locally (Link) but it seems that I need to fill in Event Hub connection string and name.
public static async Task Run([EventHubTrigger("samples-workitems", Connection = "eventhub-connectionstring")] EventData[] events, ILogger log)
Is there any way for this to be possible?

A: Each binding has an HTTP endpoint for local testing and debugging.

*

*https://localhost:7071/admin/functions/{FUNCNAME}

That's available for QueueTrigger, ServiceBusTrigger, TimerTrigger, EventHubTrigger at least.
Send a POST request with the expected data as JSON.
{ "input": "YOUR JSON SERIALIZED AND ESCAPED DATA" }

For triggers that need data put the data as serialized string into "input". See EventHubTrigger example further below.
TimerTrigger
For TimerTrigger use this:
{ "input": null }

EventGridTrigger
To execute this on some triggers it's bit tricky. Here it is for EventGridTrigger:

*

*https://localhost:7071/runtime/webhooks/EventGrid/functionName={FUNCNAME}

Send a POST request to execute. See here for details. The object must be an array.
EventHubTrigger
The EventHubTrigger receives data like the other triggers, as single JSON object. The structure follows the EventData class, but the only required field is "SystemProperties". There seems no serializer specific settings, property names do not change case etc.
Post this as body;
{
    "input": "{\"SystemProperties\":{},\"SomeId\":\"123\",\"Status\":\"Available\"}"
}

The event hub's body is the escaped and serialized value of "input".

Note that the same applies for the IoT Hub

Meta Data
For ALL triggers you can get meta data with a GET request. For an EventHubTrigger this could look like this:
{
    "name": "StateChange",
    "script_root_path_href": "http://localhost:7071/admin/vfs/StateChange/",
    "script_href": "http://localhost:7071/admin/vfs/bin/MyApp.Notifications.Functions.dll",
    "config_href": "http://localhost:7071/admin/vfs/StateChange/function.json",
    "test_data_href": null,
    "href": "http://localhost:7071/admin/functions/StateChange",
    "invoke_url_template": null,
    "language": "DotNetAssembly",
    "config": {
        "generatedBy": "Microsoft.NET.Sdk.Functions-3.0.11",
        "configurationSource": "attributes",
        "bindings": [
            {
                "type": "eventHubTrigger",
                "consumerGroup": "regular",
                "connection": "EventHub_Hub_Status",
                "eventHubName": "%EventHub_Status%",
                "name": "statusUpdateMessage"
            }
        ],
        "disabled": false,
        "scriptFile": "../bin/MyApp.Notifications.Functions.dll",
        "entryPoint": "MyApp.Notifications.Functions.StateChange.Run"
    },
    "files": null,
    "test_data": null,
    "isDisabled": false,
    "isDirect": true,
    "isProxy": false
}

And, of course you can use all the paths to retrieve the data, including the binaries. Very handy to write sophisticated integration tests.

A: No, It is not possiable.
This is because there is no official simulation tool.
For httptrigger, you can use postman or just use some code to hit the endpoint.
For trigger about azure storage, you can use local azure storage explorer.
But something like eventhub, service bus and so on can not be triggered without creating a azure resource.


text:
Q: Java while loop random number i'm new to Java and I am trying to code a little "fighting game" (more random than fight actually). I want each punch to have a random number of damages between 0 and 30. The problem is, the first number randomly sorted will be used until the end (if it's 12, both fighters will punch at 12 damages every turn until Player 1 wins). How can I generate a different random number at every iteration of the loop until there's a winner ?
package jeu_propre;

public class main {
    public static void main(String[] args){
        System.out.println("Player 1, choose your name : ");
        String nom_pone= new java.util.Scanner(System.in).nextLine();
        System.out.println("Player 2, choose your name : ");
        String nom_ptwo= new java.util.Scanner(System.in).nextLine();

        int r=new java.util.Random().nextInt(30);

        weapons fists = new weapons();
        fists.name="fists";
        fists.damage = r;

        player number_one = new player();
        number_one.name= nom_pone;
        number_one.hp= 100;

        player number_two= new player();
        number_two.name=nom_ptwo;
        number_two.hp= 100;

        boolean running=true;
        while (running == true) {
            System.out.println("Fight !");
            System.out.println(number_one.name +" hit " + number_two.name);
            String frapper= new java.util.Scanner(System.in).nextLine();
            System.out.println(fists.damage);
            number_two.hp= number_two.hp -= fists.damage;

            if (number_two.hp <=0) {
                System.out.println(number_one.name +" wins !");
                running=false;
                break;
            } else {
                System.out.println(number_two.name + " still has "+number_two.hp);
                running = true;
            }
            System.out.println("Fight !");
            System.out.println(number_two.name +" hit " + number_one.name);
            String frapper2= new java.util.Scanner(System.in).nextLine();
            System.out.println(fists.damage);
            number_one.hp= number_one.hp -= fists.damage;

            if (number_one.hp<=0) {
                System.out.println(number_two.name +" wins !");
                running=false;
                break;
            }else {
                System.out.println(number_one.name + " still has "+number_one.hp);
                running = true;
            }
        }

I tried to change the values between the brackets and associating the random command directly to "fists.damage"

A: Basically you need a new random number at every iteration. So, you should place the random statement within the loop. Then only it will make new random numbers every iteration.
Define int r outside the loop. Then move the statement from outside the loop to inside the loop.
r = new java.util.Random().nextInt(30);
fists.damage = r;

or you can make an instance of Random outside the loop like this:
java.util.Random obj = new java.util.Random();

and call the method nextInt(30) inside the loop like
r = obj.nextInt(30);

This is just a better way to write a program. Both will work but the second one is a better programming practice as suggested by @tgdavies and @Maarten Bodewes


text:
Q: can a user view vb.net settings in application I am creating a VB.net application and including my database credentials in the settings of the project, so to access i use:
My.Settings.SettingName

Is there any way a user using the application can view these settings?
I am worried about someone being able to log into the database if they ever manage to see the settings?

A: Application users can not see these settings.  The only way to see the settings is to look at the code as a developer.
EDIT:
In my humble experience, the best choice for hiding a connection string in your app, considering the environment I work in, is to hide it in the vb code.  You can make a database utilities class, and put your methods and properties there - methods being connect, execute commands etc, and a private property which is your connection string that other methods in the class use.
Other people can see the connection string, like other developers, or people who are browsing around the same files you have access to, but upon deployment, it will be very difficult for someone to extract the connection string out of yourapp.exe.


text:
Q: How to add new Columns to table in Vaadin and how to place a link in vaadin table I am new To Vaadin, I have created a Table and i can able to populate the data in that through the BeanItemCOntainer, bellow is the code for this.
public Component getMainContent(ViewChangeListener.ViewChangeEvent event) {
        List<ExecutionPlanVO> executionPlanVOs = executionPlanDelegate.getExecutionPlans(getSearchVO());
        Table table = new Table();
        BeanItemContainer<ExecutionPlanVO> container = new BeanItemContainer<ExecutionPlanVO>(ExecutionPlanVO.class, executionPlanVOs);
        container.addBean(new ExecutionPlanVO());
        table.setContainerDataSource(container);
        table.setVisibleColumns(
                new Object[] {"billOfladingNo" , "containerNo" , "houseBill" , "carrier" , "customer" , "origin" , "pol" , "transshipment" ,
                        "pod" , "destination" , "start" , "completion" , "status"});
        table.setColumnHeaders(
                new String[] {"Bill Of Lading" , "Container No." , "House Bill" , "Carrier" , "Customer" , "Origin" , "POL" , "Transshipment" ,
                        "POD" , "Destination" , "Start (LT)" , "Completion (LT)" , "Status"});
        table.setStyleName("ep-list-table");
        return table;

    }

I Have two questions here,
1. I would want to change billOfladingNo column as a link, which will permorm some action when i click ?
2. i wanted to add one more column with couple of link Icons?
can you help me how can i  add the columns ?
Thanks in advance
Kiran.

A: You can Create a class to implement ColumnGenerator to return the link and the icon. I have done a sample below
class Linker implements ColumnGenerator{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public Object generateCell(Table source, Object itemId, Object columnId) {
        // TODO Auto-generated method stub

        Item item = source.getItem(itemId);
        Link link = new Link();
        String linkCaption = item.getItemProperty("billOfladingNo").toString();
        link.setCaption(linkCaption);
        link.setResource(new ExternalResource("http:/www.domain.com/"+linkCaption));
        return link;
    }

}

class LinkIcons implements ColumnGenerator{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public Object generateCell(Table source, Object itemId, Object columnId) {
        // TODO Auto-generated method stub

        Label icons = new Label();
        icons.setIcon(FontAwesome.LINK);
        return icons;
    }
}
    table.addGeneratedColumn("billOfLading", new Linker());
table.addGeneratedColumn("link", LinkIcons);

be sure to make your billoflading from the bean invisible and add the generated column ids to the table visible ids.

A: Depends what vaadin version Your using if 7.X.X then:
You can set on the container what type is the chosen column:
container.addContainerProperty("billOfladingNo", new Link, null);

1st parameter is the property of Your column
2nd is the type You want to have
3rd is the default value
that will make Your column type: com.vaadin.ui.Link
to make a new Link with possible navigation:
        Link link = new Link("CAPTION", new ExternalResource("URL"));

For the second question u need to set the link caption to accept HTML and then set the FontAwesome icon html:
    link.setCaptionAsHtml(true);
    link.setCaption(FontAwesome.ANCHOR.getHtml());


text:
Q: Creating random number using Exponential distribution in a specified range? I need to create random numbers in a user specified range. I understood how to create random numbers and refering to Generating random numbers of exponential distribution that question. However, I need my random numbers to be in a range. I wrote a piece of code, althogh it works in theory, because it calculates very little numbers it approaches 0 and give wrong numbers.
My code is
        double u;
        double p1 =  -1.0 *  lambda * minvalue;
        double p2 =  -1.0 *  lambda * maxvalue;
        double a_min =  1 - exp(p1);
        double a_max =  1 - exp(p2);
        u = (rand() / (RAND_MAX + 1.0));
        double diff = a_min - a_max;
        u = u * (a_min - a_max);
        u = u + a_max;
        double p3 = 1.0- u;
        int x = (int)(-log(p3) / lambda);
        return x;

lambda, minvalue and maxvalue are all integers. How can I deal with this issue ot is there any alternative solutions?
My code deals with very little numbers and so it is rounded to 0 then the result is calculated wrongly .

A: Would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*
 * note: lambda should be a positive number
 *       min and max should be non-negative and min < max
 */
double rand_exp(int lambda, int min, int max)
{
    double u_min = exp(-min * lambda);
    double u_max = exp(-max * lambda);

    double u = u_min + (1.0 - rand() / (RAND_MAX + 1.0)) * (u_max - u_min);
    return -log(u) / lambda;
}

*

*Please note the function does not check the illegal parameters.

*I have defined the function to return the double value because it is
easier to test the output. Please cast it to int based on your requirement.


text:
Q: How to perform Click-Event on a hidden button In my C# form I have two buttons
button1.Hide()
private void button2_Click(object sender, EventArgs e)
{
 button1.PerformClick();
}

The button1 is hidden at form loading, I want the logic behind button1 to be perfomed when it's hidden too.

A: Just let the function outside become another function, then you can call function although you hidden the button1.
private void button1(object sender, EventArgs e)
{
  _button1();
}
private void button2(object sender, EventArgs e)
{
  _button1();
}

//Here is the function
void _button1()
{
    ...
}

A: If your Button is hidden, it seems that you need the functionality behind not or just in special cases. Keeping functionality out of events is often a simple solution to avoid problems in the future.
    private void btn_Reload_Click(object sender, EventArgs e)
    {
      // reload here - maybe you reload all your employees from a datasource
    }

    private void btn_Reload_With_Calculation_Click(object sender, EventArgs e)
    {
      // you can use functionality here from a another button and call the
      btn_Reload_Click(this, EventArgs.Empty); // DON'T DO THIS IN MY OPINION
      // ....
    }

Maybe this solution is better even if you need the functionality at other workflows.
    private void btn_Reload_Click(object sender, EventArgs e)
    {
      Reload();
    }

    private void btn_Reload_With_Calculation_Click(object sender, EventArgs e)
    {
      Reload();
      Calculate();
    }

    void Reload() { }

    void Calculate() { }


text:
Q: Very slow alter table (even without rows) I've a problem with my Mysql setup: each alter table I make takes about 5 minutes to complete, even if the table is completely empty.
Sometimes the query even fails due to a timeout (Error 2013: Lost connection to MySQL server during query SQL Statement: ALTER TABLE ...).
Furthermore, the table is in a test database, so there are no other queries going on concurrently.
I use Mysql 5.7 on a 12 CPUs machine, so I don't think that hardware is the problem.
Do you know how to solve this issue?
thanks for your time
EDIT:
When running show full processlist
Altering table  ALTER TABLE ...
Waiting for table metadata lock ALTER TABLE ...

PS: this behaviour happens on any table, and with every ALTER TABLE statement
EDIT:
The issue was solved in Mysql 5.7.8

A: Try your query here.
https://www.percona.com/doc/percona-toolkit/2.1/pt-online-schema-change.html
If Anything bad in query, you will find it.
Else
A full dump and reload is more faster than alter.
i.e.
- Create a new table (using the structure of the current table) with the new column(s) included.

- execute a INSERT INTO new_table SELECT (column1,..columnN) FROM current_table;

- rename the current table

- rename the new table using the name of the current table.


text:
Q: Using Belkin 6-Outlet Surge Protector in Morocco without a Converter Morocco uses the 220V/50Hz standard, and I was trying to use the following power strip I bought in the US with only a adapter (no converter):
https://www.belkin.com/us/p/P-BE106000-06/
When I plugged the surge protector and turned it on (with no load), there was a very short but intense spark. However, my electronics were charging fine when I later plugged them into the surge protector. I'm just wondering what the initial spark was due to, and if it is possible that I broke something inside the surge protector and if so, is it ok to continue to use the surge protector (given that my electronics were still charging fine).

A: The surge protector itself is what has failed, ones intended for 120V supplies will conduct at typically 200V or so. It's a little component with a resistive element that changes with voltage, so it conducts momentary overvoltages to limit what gets to the equipment. Most likely after plugging it into the 220V supply, if it didn't manage to take out the fuse first it will have either exploded or melted its connections - they're only intended to conduct for milliseconds.
As to whether the strip is still safe to use, it will depend on what debris is now present inside the housing.

A: Define safe.
It is not a surge protector anymore, it's just an unprotected power strip with blown and unknown components inside.
Can it still work as a power strip? sure. If there are no dangerous debris from the blown component and the rest of the internal components are rated for your line voltage. Then it is just a bunch of wires and connectors.
Now, if any of the remaining internal components (e.g., filter capacitors and fuse) are not rated for your line voltage, something else will be failing in it soon enough.


text:
Q: Convergence of $\sum_{n=1}^\infty \frac{\sqrt{n+1}-\sqrt n}{n^p}$ for $p \ge 0$ Fix $p \ge 0$. I'm having trouble determining whether or not $$\sum_{n=1}^\infty \frac{\sqrt{n+1}-\sqrt n}{n^p}$$ converges.
Clearly, the limit criterion is satisfied and I have tried to apply the ratio test to no success (I receive $|a_{n+1}/a_n| = 1$ and thus the test is inconclusive. I don't think the root test nor integral test would help since it is almost impossible to integrate or take the $n$ root of the summand.
Thus, I believe the key to solving this problem is the comparison test. I however cannot think of a series that I may use for comparison. Does anybody have a suggestion?

A: $\frac{\sqrt{n+1}-\sqrt n}{n^p} = \frac{1}{n^p(\sqrt{n+1}+\sqrt{n})},$
and the latter is equivalent to $\frac1{2n^{p+1/2}}$
You just have to compare with Riemann series.
Without $\sim$:
Let $a_n = \frac{\sqrt{n+1}-\sqrt n}{n^p}$, and $b_n = \frac1{2n^{p+1/2}}$.
Then $\frac{a_n}{b_n} \xrightarrow[n\to\infty]{} 1$, ie $a_n = O(b_n)$.
Thus, if $p>1/2$, as $\Sigma b_n$ converges, then $\Sigma a_n$ converges.
Notice also that $\frac{b_n}{a_n} \xrightarrow[n\to\infty]{} 1$, ie $b_n = O(a_n)$. The reciprocal of the comparison test asserts that if $\Sigma b_n$ diverges, then $\Sigma a_n$ diverges.
Thus, if $p\leq \frac12$, as $\Sigma b_n$ diverges, then $\Sigma a_n$ diverges too.


text:
Q: Menu item depend on user articles in my app I have multiple user rol0 (admin, distributor, buyer). By default, I show 3 menu items. But if the user in his list of articles has articleAA i show him the new item in the menu only for this article and another default item. Same, if he has articleBB I show him menu item for this article. On login, i chech this and show menu
$scope.allArticles = allArticlesFactory.get();
$scope.allArticles.$promise.then(function(data) {

angular.forEach(data, function(key, value){
    switch (key.type){
        case 'articleAA':
            $scope.articleAA= true;
            break;
        case 'articleBB':
            $scope.articleBB= true;
            break;
        default:
        $scope.articleAA= "";
        $scope.articleBB= "";
    }
});
});
})

In a menu with ng-if, I check value

articleAA

articleBB

PROBLEM: when I log in like admin I get all menu item and this is ok.
When I log in like a buyer who has articleAA and articleBB i get all menu items and this is ok.
But, when I log in like another buyer who doesn't have any of this article, this two menu is still here. When I refresh, this special menu item disappears.
I try on top of controller put
$scope.articleAA= "";
$scope.articleBB= "";

and also
$scope.articleAA= false;
$scope.articleBB= false;

But, same problem is here. Next user always get menu from previous user, but if he refresh, everything is ok.
default menu
| Home | Articles | Info |
if user have articleAA
| Home | Articles | Info | ArticleAA |
if user have articleBB
| Home | Articles | Info | ArticleBB |
if user have articleAA and articleBB
| Home | Articles | Info | ArticleAA | ArticleBB |
Thnx


text:
Q: Leakage current of ESD protection diode vs regular zener diode I am using a voltage divider to measure input voltage, a zener diode was added to protect opamp in case of voltage spike.

simulate this circuit – Schematic created using CircuitLab
I was told that the leakage current of zener will reduce measurement accuracy and advised to use ESD diode below:

simulate this circuit
How is the design better? Doesn't ESD diode also have the leakage current?

A: You can use an OA that has ESD protected inputs. You need to add a current imiting resistor.

simulate this circuit – Schematic created using CircuitLab

simulate this circuit
If you use very high impedance resistor divider, then the current can't be higher than 0.2 micro amp (5 giga resistor). The input ESD protection will easily limit the voltage. But you have to be aware that resistor divider has also a capacitance, so it is RC divider not a pure resistor divider.
Now if we look the capacitive part of the divider, you can see that output voltage is inversely proportional to the filter capacitor. If not placed, you could get very large spike on OA input. The capacitive divider takes its place when switching events occurs on the measured rail.

simulate this circuit


text:
Q: FileStream.BeginWrite advantages over FileStream.Write? I need to make a batch of writes to the same file but at different places within the file. I want to achieve this with the best performance possible and so have looked at the synchronous FileStream.Write and asynchronous FileStream.BeginWrite methods.
A synchronous implemention is trivial and simply calls the FileStream.Write the required number of times in a loop. The async version calls FileStream.BeginWrite in a loop and then does a WaitHandle.WaitAll in order to block until they have all completed. To my surprise this works slower than the simple synchronous version.
I have created the FileStream using the correct constructor so I can request async operation and I also tested the IAsyncResult.CompletedSynchronous property which indicated False and so they did indeed operate in an async fashion. It seems that the only benefit from using BeginWrite is that you are not blocking your thread whilst the write occurs. Apart from this benefit is there any point in using the async version?
Here is the test code I used for playing with the async method, maybe there is an obvious error?
        // Size of a chunk to be written to file
        var chunk = 1024 * 64;

        // Number of chunks to write async
        var reps = 32;

        // Create new file and set length
        var fs = new FileStream(@"C:\testfile.dat",
                                FileMode.Create, FileAccess.ReadWrite,
                                FileShare.None, chunk, true);
        fs.SetLength(chunk * reps);

        // Allocate resources
        byte[] bytes = new byte[chunk];
        WaitHandle[] handles = new WaitHandle[reps];

        for (int i = 0; i < reps; i++)
        {
            fs.Seek(chunk * i, SeekOrigin.Begin);
            handles[i] = fs.BeginWrite(bytes, 0, chunk, null, null).AsyncWaitHandle;
        }

        // Wait for all async operations to complete
        WaitHandle.WaitAll(handles);

        fs.Flush();
        fs.Close();

A: File writes are heavily optimized in Windows.  You don't actually write to the disk, you write to the file system cache.  A memory-to-memory copy, runs at 5 gigabytes per second or better.  From the cache, the data is then lazily written to disk.  In turn optimized to minimize the number of write head moves.
This is next to impossible to optimize with asynchronous writes.  Which do indeed take longer, grabbing the threadpool thread to make the callback doesn't come for free.  The benefit of async here is minimizing the main thread delays, not to actually make it more efficient.  You will only actually get the benefit when you write very large amounts of data.  More than will fit into the cache.  At that point, write perf will fall off a cliff from 5 GB/sec to less than ~50 MB/sec since cache space can only become available at the rate the disk can be written.
Exactly when that happens is hard to predict.  It depends how much RAM the machine has and how much of it is needed by other processes.  You basically don't worry about it when you write a gigabyte or less.  And it is important that you actually have something useful to do when the async write is pending.  Waiting for them to complete defeats the point of using it.


text:
Q: Set IDEA to make Java-based suggestions? IDEA suggests (among other things) name for some method or class member and so on.
How can I set it to propose name in the spirit of Java language?
For example, I want to create a class member of type MyClass and I want IDEA to propose the name mMyClass, instead of myClass (which is default behaviour)?
PS. I use Java as part of Android development. Here is Android Code Style.

A: settings > code style > java > code generation > naming

but putting m at the front for a method goes against convention. It sounds like a borked version of hungarian notation.


text:
Q: Using Endpoint.publish() in OSGi to publish web service? Is there a way to use Endpoint.publish() in an OSGi bundle to publish a web service? When I run the code from the command line it works, but the same code in a bundle activator produces the following exceptions:
Caused by: com.sun.xml.internal.ws.server.ServerRtException: [failed to localize] cannot.load.wsdl(file:/C:/ws/project/org.project.configuration/xml/Configuration.wsdl)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.getPrimaryWsdl(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.createEndpoint(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at org.project.internal.configuration.Activator.start(Activator.java:52)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:783)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:774)
... 11 more
Root exception:
com.sun.xml.internal.ws.server.ServerRtException: [failed to localize] cannot.load.wsdl(file:/C:/ws/project/org.project.configuration/xml/Configuration.wsdl)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.getPrimaryWsdl(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.createEndpoint(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at org.project.internal.configuration.Activator.start(Activator.java:52)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl$1.run(BundleContextImpl.java:783)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.startActivator(BundleContextImpl.java:774)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:755)
at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:370)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.resume(AbstractBundle.java:374)
at org.eclipse.osgi.framework.internal.core.Framework.resumeBundle(Framework.java:1067)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:561)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.resumeBundles(StartLevelManager.java:546)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.incFWSL(StartLevelManager.java:459)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.doSetStartLevel(StartLevelManager.java:243)
at org.eclipse.osgi.framework.internal.core.StartLevelManager.dispatchEvent(StartLevelManager.java:440)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:227)
at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:337)

A: I think I was able to finally solve this by adding the annotation: @WebService(endpointInterface, name, serviceName, targetNamespace) to the service implementation.


text:
Q: Is a circle a multivalued function? I don't really understand multi-valued function. I hope one of you can make me understand it. What I've learned from google, I suppose that a multi-valued function is a binary relation that maps the domain more than once to a single point (i can't describe it well).
So, here, can I conveniently claim that a circle (on the real plane) is a multi-valued function since from one point on the domain we can get $2$ points as the range?
Thanks in advance.

A: The circle $S$ can be viewed as a binary relation on $\Bbb{R}$, simply because it is a subset of $\Bbb{R}^2$. And indeed if $(x,y)\in S$ then also $(x,-y)\in S$, so if $y\neq0$ then this shows that $S$ is multivalued. But $S$ is not a function on $\Bbb{R}$, because it is not defined on all of $\Bbb{R}$; there is no $y\in\Bbb{R}$ such that $(2,y)\in S$, for example. So the circle cannot be viewed as a multivalued function on $\Bbb{R}$.
There are two ways to adjust your example to valid example of a multivalued function:

*

*We can adjust the domain; viewing the circle $S$ as a subset of $[-1,1]\times\Bbb{R}$, or even $[-1,1]^2$, we do get a multivalued function. This of course relates to the fact that every positive real number has precisely $2$ square roots, i.e. the function
$$f(x)=\sqrt{1-x^2},$$
can also be interpreted as a $2$-valued function on the interval $[-1,1]$.

*We can consider a hyperbola instead, for example the set of all $(x,y)\in\Bbb{R}^2$ satisfying
$$x^2-y^2=-1.$$
I leave it to you to verify that this defines a $2$-valued function on all of $\Bbb{R}$.

A: $y=(R^2-x^2)^\frac{1}{2}$ is multivalue function because exponentiation to a negative even is multivalue by disjunction.
Yes, it is correct that any function which graphical representation has multiple y for single x would be multi-value by disjunction at that point.


text:
Q: RoR devise: sign_in always returns invalid email/password Every time I log in, I get the error msg that the email/password is invalid.
routes:
devise_for :users

devise_scope :users do
  get '/users/sign_out' => 'devise/sessions#destroy', :as => :destroy_user_session
  post '/users/sign_in' => 'devise/sessions#create', :as => :user_session
end

resources :users

user model:
devise :database_authenticatable, :confirmable, :recoverable, :rememberable, :trackable

attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :gender, :remember_me

view:
<% if signed_in?(:user) %>
   Hi <%= current_user.first_name %>. | Not you? <%= link_to 'Sign out', destroy_user_session_path, :method => :delete %>
<% else %>
   <%= link_to 'Sign up', signup_path %> or <%= link_to 'Sign in', user_session_path, :method => :create %>
<% end %>

I tried changing the routes to:
get '/users/sign_in' => 'devise/sessions#new', :as => :new_user_session

and changing the respective paths, but that didn't change anything.
I even changed the code in the view from:
if signed_in?(:user)

to:
if user_signed_in?

and did a combination of these things and nothing is working.
I did ask devise to handle the confirmation as well, which I did by copying the generated link to the browser and it signs me in as the user the first time.  It also allows me to change the password via the email confirmation link, which also signs me in upon changing the password.  But once I sign out and sign back in, it tells me that the email/password is invalid again.
Can anyone help?
I am using rails 3.0.7, devise 1.4.5, capybara 1.1.1, cucumber 1.0.6, mysql2 0.2.6 and rake 0.8.7 if that helps anyone.
Thanks
EDIT:
To help future users, there is actually nothing wrong with the gem.  It works fine.  The issue is with my database.  For some reason, it is selecting a NULL email from the database instead of pulling the info of the user I am trying to log in.  I am figuring out how to fix this now and will update once I figure it out.

A: I ran into this issue when I had both
config.authentication_keys = [ :username ]

and
config.authentication_keys = [ :email ]

enabled simultaneously in config/initializers/devise.rb.

Upon removing the duplicate setting, authentication was successful.

A: When I ran across this problem I went back through my Devise config file in

config/initializers/devise.rb

I then found the part that I remembered I had changed to :username
config.authentication_keys = [ :username ]

I changed this back to :email. That ended up making it work.

A: I have been having a similar issue on a fresh install of Devise, but what I found is that if I ran bundle update then restarted my dev server it works.
At first I wasn't seeing the DB query in the development.log, but once I updated my Gemfile (to make sure I am using the latest Devise gem) and restarted the server I now see the db queries in my logfile and it works (magically).
Hope that helps.
Btw, not sure if this will help you...but these are the routes in my Routes.rb
 devise_for :users, :path_names => { :sign_up => "register",
                                      :sign_in => "login",
                                      :sign_out => "logout",
                                      :settings => "settings" }

  devise_scope :user do
    get "login", :to => "devise/sessions#new"
    get "register", :to => "devise/registrations#new"
    get "settings", :to => "devise/registrations#edit"
    get "logout",   :to => "devise/sessions#destroy"

  end

A: I think the attr_accessor messes up with attr_accessible. Do you really need to have an attr_accessor?, if not simply remove it.
Try it and please let me know how it goes.
Best regards
ED

A: The username and password could both be case sensitive. Have you checked how the username is stored in your table to make sure you are entering it correctly?
In my experience when it tells you the email/password is incorrect, you can get distracted with lots of complicated ideas, but it ends up being the email or password was incorrect. It sounds like you have tried various times with resetting the password, so it makes me wonder about the username. Are you sure the right field is set up in devise as the username (ie. it could be email or a username)?

A: config.authentication_keys = [ :username ]
and
config.authentication_keys = [ :email ]
simultaneously set in config/initializers/devise.rb will cause this error.