text:
Q: View.setVisibility(View.INVISIBLE) does not work for animated view I have an activity that (when started) shows some coachmark views (All ImageButtons) on screen that indicate how the app should be used (function of certain buttons, swipe behaviour, etc). A fade out animation is associated with each of these views that triggers after some predefined interval. This works as expected. However, I would like those marks to disappear earlier if the user interacts with the activity in a certain way. When these actions are triggered I cancel the animations and callsetVisibility(View.INVISIBLE); on the coachmark views. However, the visibility of the view does not change. I have experimented with other techniques - removing the view from the parent and setting alpha to 0 and these work fine but altering view visibility does nothing.
The code that sets up the coachmark looks as follows:
private void animateCoachmark(int id) {
    AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
    final View view = findViewById(id);
    animation.setStartOffset(10000);
    animation.setDuration(500);
    animation.setAnimationListener(new AnimationListenerBase(null) {
      @Override
      public void onAnimationEnd(Animation animation) {
        view.setVisibility(View.INVISIBLE);
      }
    });
    view.startAnimation(animation);
    coachmarkViews.add(view);
  }

The problematic code to change visiblity:
for (final View coachmarkView : coachmarkViews) {
  Animation animation = coachmarkView.getAnimation();
  if (animation != null) {
    animation.cancel();
  }
  coachmarkView.setVisibility(View.INVISIBLE);
}

A: This issue seems to be that changes to visibility are not honoured as long as an animation is associated with a view even if the animation has been cancelled. Altering my cleanup code to first set the animation on the view to null allows the view to disappear as expected.
for (final View coachmarkView : coachmarkViews) {
  Animation animation = coachmarkView.getAnimation();
  if (animation != null) {
    animation.cancel();
    coachmarkView.setAnimation(null);
  }
  coachmarkView.setVisibility(View.INVISIBLE);
}


text:
Q: grunt live reload error Sorry I am new to grunt and trying to build a system where I can have a live reload with sass. Sass everything was easy to set up and compile but the livereload I am stuck, I followed this tutorial
https://www.youtube.com/watch?v=SL6uYHsl2Ic
and when I ran the command grunt server received an error saying
Path must be a string. This is my basic build system. Thanks!
module.exports = function(grunt) {
grunt.initConfig({
  sass: {                              // Task
    dist: {                            // Target
      options: {                       // Target options
        style: 'expanded'
      },
      files: {                         // Dictionary of files
        'css/main.css': 'sass/main.scss'       // 'destination': 'source'
      }
    }
  },
  watch: {
    options: {livereload:true},
    css: {
      files: ['sass/**/*.scss'],
      tasks: ['sass'],
    },
  },
  express:{
    all:{
        options:{
            port:9000,
            hostname:'localhost',
            base:'.',
            livereload:true,
        }
    }
  }
});
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-express-server');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['sass'])
grunt.registerTask('server', ['express', 'watch']);

};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swap branch merges in git I want to essentially swap the roles of two branches in a git repo, when it comes to merging. Since there are many potential ways my problem might be resolvable, I'll just explain my circumstances to avoid an X-Y -question:
I'm developing firmware for a device which has gone through several hardware revisions, which require subtle differences (mostly different constants) in the firmware. The (relevant) hardware revisions are "proto2", "proto3" and "proto4". The original main branch is called "master", and that currently corresponds to hardware revision "proto2". Back in the days when "proto3" came along, I made a new branch called (imaginatively) "proto3". I then made the changes related to the new hardware revision to the "proto3" branch, and continued developing in "master" for revision "proto2". This way I could then checkout "proto3", merge "master" into that, and have my "proto3" -compatible firmware with the new features. Since then, "proto4" has appeared which has one more change (literally a one-liner). So now I develop in "master", and then have to always merge changes to "proto3" and "proto4" (this also means that I have to do the development on the older prototype).
Now we're moving to production, and "proto4" will be the production firmware. However, since some of the older prototypes are still quite useful, I'd like to actually swap the roles of the branches, i.e. be able to develop in the branch "proto4" and merge from there to "master" without introducing the hardware related changes done previously to "proto4" back to "master".
In other words, otherwise a normal merge, except that certain (old) commits do not ever get merged from "proto4" to "master".
I can think of couple of ways to achieve this:

*

*I could simply always cherry pick the new commits from "proto4" into "master". However, this I'll need to remember to do every time I'm backporting changes, and forgetting it results in a mess.

*I could merge "proto4" to "master", and then revert the hardware related commits from "proto4" in "master", i.e. undo the changes. I will need to dig through the commit log to find those changes, but it should be doable.

Option 2. seems like a not-unreasonable way to go about this, since it's a one time trouble and only a one time opportunity for error. However, I feel like there should be a simpler way, where I don't have to manually pick out the correct commits to revert?
P.S.: I'm of course also going to rename the branches, but that seems to be covered by Switch branch names in git, and maybe even better by https://mohitgoyal.co/2018/04/07/swap-master-branch-with-another-branch-in-git/

A: Would it be possible for you to have the following:

*

*Consider master as the generic code,

*have a proto# branch per hardware, with their specific needs, all based on top of master,

*when master changes, either rebase the proto branches on top of it (will imply force push and good communication between the devs), or merge master in each of them (will make a less clean log, and makes it harder to see in a glance what is specific for the proto branch)

*maybe have the production proto branch named as production-proto# to know quickly which one is the prod one

So each hardware can have its own code, and master is the generic part only.
When you want to create a new hardware, you create a new branch from master.
And when you want to discontinue a hardware, it's just a matter of deleting its branch.

A: I figured out a way to do this:
First, take the diff between current heads of "proto4" and "master":
git diff proto4..master > diff.txt

Then merge "proto4" into "master", i.e. now "master" is what used to be "proto4". Step one completed, including the renaming. Then create a new branch "proto2", and checkout "proto2". Now apply the previously created diff:
git apply diff.txt

and commit the changes, with the appropriate message, i.e. "recreated proto2 firmware" etc.
Finally, as a cleanup step you can remove the now unneeded "proto4" branch (you can double check that diff master proto4 is empty).


text:
Q: ERROR @wdio/runner: Error: Failed to create session. session not created: This version of ChromeDriver only supports Chrome version 83 I'm getting an error 'ERROR @wdio/runner: Error: Failed to create session.
session not created: This version of ChromeDriver only supports Chrome version 83' while running a script in WebdriverIO V6 with Cucumber framework though I'm running in chrome browser (85.0.4183.83) locally and my chromedriver configuration in package.json file is "chromedriver": "^85.0.0".
The only concern here is even If I keep my chromedriver version 85.exe file in my node_modules->.selenium-> chromedriver then It's throwing a same error while running a script.
Is there any workaround to fix this issue?

A: You have to either set chromedriver version in the selenium standalone config https://webdriver.io/docs/selenium-standalone-service.html#configuration or use https://webdriver.io/docs/docs/wdio-chromedriver-service.html only but not all together.
chromedriver package is not used by selenium-standalone-service
Note: please use chromedriver (not Chrome browser!) version, see https://chromedriver.chromium.org/downloads


text:
Q: my pro just shows client side validation errors i use @Html.ValidationMessage("username") to check duplicate username.
and it is working.
but when i have serverside validation error & clientside validation error together , it just shows clientside error .i wanna both errors can to appear.
@Html.ValidationMessage("username") alone works , but when i have forexample email required error too , @Html.ValidationMessage("username") doesn't show and just email error is shows.
   //client
   @Html.TextBoxFor(m => m.email, new { @class = "group", @placeholder = "*  enter email" })
   @Html.ValidationMessageFor(model => model.email)

   //server
    @Html.ValidationMessage("username")
    @Html.TextBoxFor(m => m.username, new {@id="group" , @class = "input-block-level", @placeholder = "* enter username" })

A: This is the expected behavior for client-side validation: it prevents a form post on error, because it can very quickly determine that the input would be invalid.
If you don't want the client-side validation to run, you can disable it and rely on the corresponding server-side validation to generate the same error message (assuming you are validating server-side, which you should be).


text:
Q: Show Dialog in Android produces crash I hava a problem with a ProgressDialog in my App.
I'm doing some tasks in background and notify actions to my Activity using a Handler.
Sometimes, not always, when I try to show my Dialog app crashes and appears this exception:
android.view.windowleaked

The way of dialog is launched:
try {
    pd = new ProgressDialog(VoiceAcquisitionActivity.this);
    pd.setMessage("blablabla");
    pd.setCancelable(false);
    pd.show();
} catch (Exception e) {
    e.printStackTrace();
}

I've read and this exception is normal in .dismiss() operation but in .show()??
How can I avoid this problem?
Thanks

A: for safety you could wrap your dialog logic in a block of code like:
   if(!isFinishing()){

       pd = newProgressDialog(VoiceAcquisitionActivity.this);
       pd.setMessage("Loading message");
       pd.setCancelable(false);
       pd.show();
   }


text:
Q: LIKE on DECIMAL fields I have a search section which would let the users to see orders based on values entered in the Search Box. If the searching value is not entered (for e.g., dates, customer name, sales price etc), top 10 records with OrderDate DESC will be shown. Table with required columns are below.
CREATE TABLE OrderDetails
(
    OrderId INT IDENTITY(1, 1) PRIMARY KEY,
    OrderPrice NUMERIC(18, 2),
    OrderDate DATETIME
)

INSERT INTO dbo.OrderDetails
SELECT 100.18 OrderPrice, GETDATE() OrderDate
UNION ALL
SELECT 300.62 OrderPrice, GETDATE() OrderDate
UNION ALL
SELECT 9300.12 OrderPrice, GETDATE() OrderDate

Whenever the user enters SalesPrice, I would like to run a query like below in VB.Net from EntityFramework. Note that SalesPrice is DECIMAL field.
SELECT * FROM dbo.OrderDetails WHERE OrderPrice LIKE '%9300%'

I am using System.Data.Entity.dll version 3.5.0.0. I started writing it as below:
Dim query = From o In e.OrderDetails Select o
If (Not String.IsNullOrEmpty(sPrice)) Then
   query = query.Where(Function(i) i.SalesPrice.ToString().Contains(sPrice))
End If

Please note that the SalesPrice is a DECIMAL field and I could not use Contains. Hence I had to use a ToString(). But I get the below error.
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Any helps are appreciated....

A: ToString is not known by L2E, you have to use SqlFunctions static methods to do the conversion.
I'm not sure if my VB syntax is ok, but that will work.
query = query.Where(Function(i) SqlFunctions.StringConvert(CType(i.SalesPrice, System.Nullable(Of Decimal)).Contains(sPrice))

The C# Syntax is:
query = query.Where(x => SqlFunctions.StringConvert((decimal?) x.SalesPrice).Contains(sPrice));

A: You  might be able to do something like this in SQL:
SELECT * FROM dbo.OrderDetails WHERE CAST(OrderPrice, VarChar(10)) LIKE '%9300%'

This would be very inefficient on the server side if you didn't have other checks in the WHERE clause to prevent a full table scan.
I don't speak LINQ so your on your own there.


text:
Q: Can anyone explain to me why I Eclipse is claiming an invalid tag, yet the JSP seems to be working Here is my code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="root" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Create Seats</title>

            <c:forEach var="seatlessEmployee" items="${seatlessEmployeesList}" varStatus="loopCount">
            <form method="POST" action="${root}/create.do">

                    ${seatlessEmployee.employeeID }
                    ${seatlessEmployee.firstName }
                    ${seatlessEmployee.lastName }

                        <select name="emptySeatID">
                            <c:forEach var="emptySeat" items="${emptySeatsList}">
                                <option value="${emptySeat.seatID }">${emptySeat.seatName }
                            </c:forEach>
                        </select>

                        <input type="hidden" value="${seatlessEmployee.employeeID }" name="seatlessEmployeeID"/>
                        <input type="submit" value="Create"/>

            </form>
            </c:forEach>

Eclipe is claiming that the opening tr tag is in an invalid location.
This seems to be absurd as the page is rendering properly when I run it

A: The warnings you see are generated when your validator comes across content that it doesn't expect according to the content model for a tag.
I suggest turning off HTML/jsp validation. The HTML/jsp validator is pretty picky.

A: Eclipse is right and your browser will try to guess where to put things. You can't just randomly wrap elements in form elements and expect uniform rendering across browsers. Form's are not valid direct child elements of tables. A valid layout would be:
<form method="POST" action="${root}/create.do">

            <c:forEach var="seatlessEmployee" items="${seatlessEmployeesList}" varStatus="loopCount">

                ${seatlessEmployee.employeeID }
                ${seatlessEmployee.firstName }
                ${seatlessEmployee.lastName }

                    <select name="emptySeatID">
                        <c:forEach var="emptySeat" items="${emptySeatsList}">
                          <option value="${emptySeat.seatID }">${emptySeat.seatName }
                        </c:forEach>
                     </select>

                  <input type="hidden" value="${seatlessEmployee.employeeID }" name="seatlessEmployeeID"/>
                        <input type="submit" value="Create"/>

            </c:forEach>

   </form>


text:
Q: Filtering values out of two dimensional data in R, comparing themselves I'm analyzing USA election data, candidates contribution, etc.  So I got raw data from internet and trying to learn some R executing some exercises in it.  This is a CSV file that I successfully loaded and analyzed with ?summary.
I also used ?tapply successfully, to separate candidates money contribution by state:
data_amt_st = tapply(data$contb_receipt_amt, data[c('cand_nm', 'contbr_st')], sum)

?str (for a small sample) tells me the format of this data:
> str(data_amt_st)
 num [1:3, 1:21] NA NA 451 NA NA 201 NA NA 200 NA ...
 - attr(*, "dimnames")=List of 2
  ..$ cand_nm  : chr [1:3] "Bachmann, Michele" "Obama, Barack" "Romney, Mitt"
  ..$ contbr_st: chr [1:21] "33" "46" "48" "7" ...

Now I need to filter out values from data_amt_st.  I need states that "Obama, Barack" had more contributions than other candidates, but don't know how to do. Something with ?subset?
Thank you very much.

EDIT 1: Attending what guys told me, about making a more concrete question:  I need a list of the states where Barack Obama achieved a higher contribution level (more money) than other candidates.

EDIT 2: Trying to give you a reproducible example (is it correct?):
x = c("a", "b", "c")
y0 = c(3, 5, 1)
y1 = c(2, 1, 6)
y2 = c(4, 2, 3)
m = cbind(x, y0, y1, y2)
m
#      x   y0  y1  y2
# [1,] "a" "3" "2" "4"
# [2,] "b" "5" "1" "2"
# [3,] "c" "1" "6" "3"

Now, I need to know, for what y values, a is higher than b and c.

A: Maybe
## max by column (MARGIN=2)
max_amt <- apply(data_amt_st,MARGIN=2,max,na.rm=TRUE)
data_amt_st[,max_amt==data_amt_st["Obama",]]

?
(Not sure how this will work with NA values in the Obama row: using dput to give us a reproducible example ( http://tinyurl.com/reproducible-000 ) would be useful ...)
x <- letters[1:3]
y0 <- c(3, 5, 1)
y1 <- c(2, 1, 6)
y2 <- c(4, 2, 3)
m <- data.frame(y0, y1, y2)
rownames(m) <- x
maxvals <- apply(m,2,max,na.rm=TRUE)
which(m["a",]==maxvals)  ## or
names(m)[m["a",]==maxvals]


text: Q: WIn32 api and storing login securely I am creating a win32 application in C++. The user will need to login with username and password. These will be used to authenticate to a web server and then the application will communicate with the web server. I would like the user to only need to input credentials the first time opening the app by having the username and password saved somewhere. How should I accomplish this? I could just save it in some plaintext file. But it looks like from searches that there is something called DPAPI? I'm not sure what is appropriate for my use. This is my first time creating a win32 application.


text:
Q: Angular: pass dynamic parameter to controller I would like to find out how I can pass a parameter that was dynamically created using ng-repeat back to the controller by calling a controller function.
Currently when I call showItem('{{item.item_id}}'); I see {{item.item_id}} in my controller function. If I leave the parenthesis off, it seems like the function is not being called (no output in console.log).

$scope.showItem = function(itemId) {
  console.log('show item '+itemId);
 }

      {{items.name}}

A:

Note that an empty href is all you need to prevent navigation.
Also note that you could have found that by looking at the documentation, which explains what ng-click expects (an expression), and has examples.

A: Just pass it without interpolation:

      {{item.name}}


text:
Q: How to configure destination for multiple OData services? If I want to access multiple OData services on one system, how can I configure the URL of the destination?
For example, there are two OData services I want to access on the same system(see below),
should I just enter the host https://myxyz.ondemand.com in the URL of the destination?
https://myxyz.ondemand.com/sap/opu/odata/SAP/APS_IAM_SIAG_BROLE_SRV /Aps_Iam_Siag_Br_Dll?$format=json&sap-client=100
https://myxyz.ondemand.com/sap/opu/odata/SAP/APS_IAM_SIAG_USER_SRV/UserSet?sap-client=100

A: The destination service on SAP Cloudplatform offers the possibility to create multiple destinations. Thus, you can create one destination for each of your systems.
See: https://help.sap.com/viewer/cca91383641e40ffbe03bdc78f00f681/Cloud/en-US/e4f1d97cbb571014a247d10f9f9a685d.html
Also locally you can provide multiple destinations over the environment variable.
Furthermore, each destination has a unique name which you have to provide. The default one for applications built with the SAP S/4HANA Cloud SDK is ErpQueryEndpoint. However, you can also use a custom name.
When using the VDM provided by the SAP S/4HANA Cloud SDK you can select which destination to use by providing a ErpConfigContext with a custom destination name to the execute method:
final List<BusinessPartner> businessPartners = service
  .getAllBusinessPartner()
  ...
  .execute(new ErpConfigContext("MyCustomDestination"));


text:
Q: How to install Cypress from local zip file using npm I wanted to install Cypress using npm - but my corporate firewall is blocking.
So I tried the below method in my Terminal in Visual Studio Code - But getting an error (pasted below)
Any idea on why this script does not work? and solution to it?
PS C:\Users\c64881a\Desktop\NPM_Cypress> CYPRESS_INSTALL_BINARY=C:/Users/c64881a/Downloads/cypress.zip npm install cypress
CYPRESS_INSTALL_BINARY=C:/Users/c64881a/Downloads/cypress.zip : The term 'CYPRESS_INSTALL_BINARY=C:/Users/c64881a/Downloads/cypress.zip' is not recognized as
the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1

*

*CYPRESS_INSTALL_BINARY=C:/Users/c64881a/Downloads/cypress.zip npm ins ...

*
  + CategoryInfo          : ObjectNotFound: (CYPRESS_INSTALL...ads/cypress.zip:String) [], CommandNotFoundException
  + FullyQualifiedErrorId : CommandNotFoundException

A: Please, try this in PowerShell:
setx CYPRESS_INSTALL_BINARY C:/Users/c64881a/Downloads/cypress.zip


text:
Q: Prevent iOS from closing background app I use an app called "GPS Tracks" to track my movements throughout the day with my iPhone 6 on iOS 9.2.1. The app often shuts down while it is actively recording in the background, which the developer indicated is something that happens when memory runs low.
Is there anything I can do to either 1) prevent iOS from shutting down a specific app for memory reasons or 2) tell iOS which apps to shut down first or 3) be warned when the app is closed by iOS.
I am ready to jailbreak it if necessary.


text:
Q: How to prove that $x^2 + 3y^2 = 1$ is contained inside of the unit ball? What is the best way to show that $S = \{(x,y) | x^2 + 3y^2 = 1\}$ is contained in the unit ball without graphing the set?

A: $y^2$ is positive, so $y^2 \leq 3y^2$. Thus, if $x,y$ are such that $x^2 + 3y^2 = 1$ then $x^2+y^2 \leq 1$.

A: $$x^2 + 3y^2 = 1 \quad\implies\quad x^2+y^2=1-2y^2\leq 1$$

A: Suppose $(x,y)\in S$ is outside the unit ball. Then $\sqrt{x^2+y^2}>1$, or just $x^2+y^2>1$. But we also have $x^2+3y^2=1$. Subtracting this from the above gives $-2y^2>0$, which is impossible since $y^2$ is nonnegative.


text:
Q: Distinguishing Equivalent DataTypes In Java, suppose I have a method that takes in two lists of integers, and returns an arrayList of integers from the first list, based upon the second list.
public ArrayList<Integer> func(ArrayList<Integer> A, ArrayList<Integer> B){
   ArrayList result = new ArrayList();

   //A and B have the same length
   for(int index = 0; index < A.length();index++){

      //Decide if a gets added to result based on the corresponding B
      if(decisionFunction(B.get(i)){
          result.add(a.get(i));
      }
   }

 return result;
}

Now suppose I did something silly like change the insertion to
        result.add(b.get(i));

It'd be nice if I could do something like
public ArrayList<AInteger> func(ArrayList<AInteger> A, ArrayList<BInteger> B)

to ensure that regardless of sleep deprivation, the compiler would prevent me from making this type of mistake. Now we could try
class AInteger extends Integer{}; class BInteger extends BInteger{};

and call the method with
func((ArrayList<AInteger>) A, (ArrayList<BInteger>) B);

Unfortunately, downcasting will raise a runtime exception. So, this solution would require me (I think) to rebuild A and B into new Lists with the appropriate datatype, which is expensive. Aside from being more careful, and using unit tests, is there anyway to get the compiler to distinguish between the two lists?
Do other languages such as Scala, or Haskell, provide something that allows me to recast safely without copying?

A: Your question is not easy, try something like:
Receive two lists with different object types (the list items type) but "equivalent" for you and convertible in Java and the returned list contains the type you want to get items from, avoiding getting from the other list.
For example, use public ArrayList<Integer> func(ArrayList<Integer> A, ArrayList<Number> B) this prevents you from coping items from B to the returning list, as you need to perform a downcasting explicitly. You can still evaluate B items as numbers by calling Number.intValue() if you want ints and/or B items are really ints. the problem is the invocation if B is really defined as ArrayList<Integer> as you need to perform an explicit cast with generics that raises a warning that can avoid putting @SupressWarning in the method definition.
Another question is Type Erasure that prevents at runtime generic type checking as generic types are "erased" when compiling in Java. C# in .Net do not have type erasure and guarantees at runtime the types of the collections (for example).

A: Actually C++ has a feature called private inheritance. It works with classes such that all functionality of the parent is inherited, but users can't treat it as the common parent. Unfortunately this does not work with primitives.
Java does not support a feature like this. Most languages do not support this kind of "semantic differentiation" in a straightforward way. Remember, the code generated for both classes would be equal.

A: While I don't think you can do what you want in Java, you can refactor your method a little to avoid the problem:
void func(ArrayList<Integer> B /* input only */ ,
          ArrayList<Integer> A /* input-output */) {
     // remove some elements from A as necessary
}

...

ArrayList<Integer> result = new ArrayList<Integer>();
result.addAll(A);
func(B, result);

A: You would be better to make the following changes:

*

*Type the return type, so you can safely add Integers to it

*Make the method static, which you can do because your method doesn't require access any instance fields - it's just "code"

*Declare your parameters and return type using the abstract type - ie List, not the concrete type ArrayList, because someone may want to pass in a LinkedList for example - your code applies to all list types, not just ArrayLists

*Name your variables with leading lowercase - it follows the usual style so other can read your code more comfortably

Like this:
public static List<Integer> func(List<Integer> a, List<Integer> b) {
    List<Integer> result = new ArrayList<Integer>();

    for (int index = 0; index < a.length(); index++) {
       if (decisionFunction(b.get(i)) {
           result.add(a.get(i));
       }
    }

    return result;
}

This code would allow your alternative code result.add(b.get(i)) to work.
BTW, Integer is a final class; you can't extend it, so you can't do this: class AInteger extends Integer

A: By using generics, this can be solved by modifying the function declaration to be
public <IntegerA extends Integer, IntegerB extends Integer>
   List<IntegerA> func(List<IntegerA> A, List<IntegerB> B){
       ArrayList result = new ArrayList();

       //A and B have the same length
       for(int index = 0; index < A.length();index++){

           //Decide if a gets added to result based on the corresponding B
           if(decisionFunction(B.get(i)){
               result.add(A.get(i));
           }
       }

       return result;
}

This ensures that result.add(B.get(i)) raises a type error as desired.
Unfortunately... new IntegerA(int) is not allowed, which prevents new objects from being created. So resulting exported list can only contain elements from the original list (unless downcasting is performed, which nullifies any type guarantees).


text:
Q: Load different config files based on domain requested for the same .net instance We have a .net web application, we want to point two domains(ex: xxtest . com and yytest . com) to the same application. I need to have different appsettings values for keys based on domain in aspx.cs file.
when i request ConfigurationManager.AppSettings["Serverkey1"] how can i configure or code so that i get different values based on the domain (xxtest . com/yytest . c om)
Thank You

A: All you should need is the
string domain = Request.Url.Host;

Then you can do a simple string comparison and do whatever you want.
Useful Link: https://learn.microsoft.com/en-us/dotnet/api/system.uri.host?view=netframework-4.7.2#System_Uri_Host


text:
Q: Flexing in space habitats I am trying to identify the name of a science fiction book I read in the mid-1990s.
The plot loosely revolves around future humanity having spread or migrated to vast space city habitats. Very athletic humanoid creatures have been bred or created with hyper-violent temperaments. They have the ability to keep their composure most of the time, except for their periodic need to flex where they will go on violent killing sprees - much to the alarm of everyone involved.
What I remember is that the story is told from the point of view of one of these creatures and involves a lot of hopping between different space cities and ensuing adventures.
Would anyone have any idea what book this may be?

A: This might be "Humanoids from the Deep"
http://www.imdb.com/title/tt0080904/
PLOT SUMMARIZATION:
Scientific experiments backfire and produce horrific mutations: half man, half fish, which terrorize a small fishing village by killing the men and raping the women.


text:
Q: Silicon parabolic dispersion for X minima I am constructing a minimal model of the silicon conduction band minima for a monte-carlo program. Assuming the six equivalent bands are parabolic and spherical, since the conduction band minima lie at 0.85$\Delta$, does the form then look like: $E(k) = \frac{\hbar^2}{2m^*}(k-0.85\Delta)^2$?
I am confused about the implementation as the minima do not lie along $k=0$.

A: I have figured out the answer. Since the velocity depends on $\nabla_kE(k)$, it does not matter where the parabola is centered.


text:
Q: How to completely reset Postgres database on Heroku? I have a learning project deployed on Heroku. It had a Postgres database provisioned. I introduced some major changes in the models of my Django project and destroyed the old database and provisioned a new one, which is totally empty, but it is not working like an empty database.
When I run the command heroku run python manage.py makemigrations, I get the error message

You are trying to add a non-nullable field....

Why am I getting this message when I have destroyed the old database?

A: First of all, you should never run manage.py makemigrations on Heroku.
By the time your code gets there no model changes should exist to generate new migrations. Run makemigrations locally to create migration files. Run migrate locally and on Heroku to apply migrations to your database.
Now that that's out of the way, this is likely caused by existing migrations files, not anything in your database. If you truly want to start over you can delete the files from each of yours apps' migrations/ directories.
Finally, there is no need to destroy and reprovision your database to reset it. Instead you can use heroku pg:reset:

The PostgreSQL user your database is assigned doesn't have permission to create or drop databases. To drop and recreate your database use pg:reset.

A: use this command
heroku pg:reset


text:
Q: Can I change the break in a bar chart in SSRS 2008R2? Is there a way I can change when the bar chart is broken up?  I'm refering to the jagged line that shows a large difference between last value in order to save space.
Is there a way ssrs calculates this or a simple explanation of how ssrs breaks it up.
I'm getting small breaks in my chart and just wondering.
Thanks!

A: Unfortunately, it's not possible to configure where scale breaks occur in SSRS.
You cannot specify where to place a scale break on your chart.
The chart uses its own calculations based on the values in your
dataset to determine whether there is sufficient separation between
data ranges to draw a scale break on the value axis (y-axis) at run time.

http://technet.microsoft.com/en-us/library/dd220529.aspx
You can however configure the maximum number of scale breaks and there is a property called CollapsibleSpaceThreshold that can be changed to make the scale breaks less "aggressive".

A: I know that the scale break is calculated at runtime, so you can not provide a static value. However, is it possible to retrieve that calculated scale break value at runtime, so I could use it in a textbox as a label.
For example, the scale break is calculated as 100.000 euro. If I could get this value I'm able to add the label "Attention: all values above 100.000 euro are using the upper scale break section"


text:
Q: Why can't I connect to my passport middleware? I'm trying to set up passport for authentication, but I can't figure out why I can't connect. The post request is received, but I'm not sure why the authenticate function isn't working or how to debug it.  The post request is received by the router here
const express = require('express');
const passport = require('passport');
const jwt = require('jsonwebtoken');

const router = express.Router();

require("../auth/auth");

router.post('/register', (req, res, next) => {
  console.log("Posted request recieved");
  passport.authenticate('register', { session: false }, async (err, user, info) => {
    console.log("Worked");
    res.send("Worked");
  })
});

module.exports = router;

And my passport middleware is defined here in /auth/auth:
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;

module.exports = function(passport) {
  passport.use('register',
      new localStrategy(
        {
          usernameField: 'username',
          passwordField: 'password',
          passReqToCallback : true
        },
        (async (req, username, password, done) => {
          try {
              console.log("Connected!");
          }
          catch(error) {
              console.log("Error: " error)
          }
          finally { return done(null) }
        })
      )
    );

The error I'm receiving is that the callback function is never called. The post request is received, but it never calls the ansnnc function I defined in the passport middleware. "Connected!" is never printed. I'm not sure how to fix this so any help would be appreciated.

A: You need to call done() in your middleware: http://www.passportjs.org/docs/configure/
Without that, you're stuck in it and your server never replies to the request.

A: try like this for authenticate if you use Mongoose
possportLocal.js
const passport = require("passport");
const { validPassword } = require("../lib/passwordUtils");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./Model");

const customFields = {
    usernameField : "username",
    passwordField : "password"
}

const verifyCallback = (username, password, done)=>{
    User.findOne({ username: username }, function (err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          return done(null, false, { message: "Incorrect username." });
        }
        const isValid = validPassword(password,user.hash,user.salt) //it's a function that check password
        if (!isValid) {
          return done(null, false, { message: "Incorrect password." });
        }
        return done(null, user);
      });
}

const strategy = new LocalStrategy(customFields , verifyCallback);

passport.use(strategy)

passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });
  });

in app.js
require('./config/passportLocal');
var passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());

route.js
var passport = require('passport');
router.post(
  "/login",
  passport.authenticate("local", {
    failureRedirect: "/login-failure",
    successRedirect: "login-success",
  })
);


text:
Q: Breaking down a binary number into 4 digits? I need to break down a binary number into 4 decimal digits using assembly.
For example, break down 0010 0110 1001 0010 which is 9874 into '9' '8' '7' '4' and show each on a 7-segment display. I got that display part, I just don't understand the logic/process of breaking it down.
Can anyone help please?
Thanks!

A: divide by 10, capturing the remainder. (modulus operation).   Push the remainder onto a stack or other suitable structure.  Repeat until the quotient is zero.  The remainders that you pushed are the digit values.


text:
Q: Big Sur 11.2 sound autoswitch to external headphones After I updated my Macbook Pro 2020 13" to Big Sur I am getting very annoying autoswitch on my sound output to some "External Headphones" and then randomly get switched back to "MacBook Pro Speakers"
I don't have any external headphones connected to my Mac via audio cable or bluetooth.
Is it possible to remove this "External Headphones" somehow or to stop this annoying autoswitch?

Sometimes I don't even see this "External Headphones" in my audio devices and then it appears somehow and switch automatically.


text:
Q: How to take depth of neural network as argument while constructing Network in Pytorch I have written following code to take depth of network as parameter in Pytorch.
Later I realized even if I am using many hidden layers, the learnable parameters remain the same.
class Net3(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output, depth, init):
        super(Net3, self).__init__()
        self.input = torch.nn.Linear(n_feature, n_hidden).float().to(device)
        self.hidden = torch.nn.Linear(n_hidden, n_hidden).float().to(device)
        self.predict = torch.nn.Linear(n_hidden, n_output).float().to(device)   =
        self.depth = depth

    def forward(self, x):
        x = F.relu(self.input(x))      # activation function for hidden layer
        for i in range(self.depth):
           x = F.relu(self.hidden(x))      # activation function for hidden layer
        x = self.predict(x)
        return x

Is there any other way to achieve this ?

A: In init you need to create multiple hidden layers, currently you're only making one. One possibility to do this with little overhead is using a torch.nn.ModuleDict that will give you named layers:
class Net3(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output, depth, init):
        super(Net3, self).__init__()
        self.layers = nn.ModuleDict() # a collection that will hold your layers

        self.layers['input'] = torch.nn.Linear(n_feature, n_hidden).float().to(device)

        for i in range(1, depth):
            self.layers['hidden_'+str(i)] = torch.nn.Linear(n_hidden, n_hidden).float().to(device)

        self.layers['output'] = torch.nn.Linear(n_hidden, n_output).float().to(device)   =
        self.depth = depth

    def forward(self, x):
        for layer in self.layers:
            x = F.relu(self.layers[layer](x))

        return x


text:
Q: Is the correct maximum runtime for this digit-removing algorithm O(1) or O(n)? I have written a small algorithm, that a changes a digit of a given number to zero. This is done in base 10. And the digits are indexed from least significant to most significant positions.
Example
unsigned int num = 1234
removeDigit(0, &num);  //  num == 1230

void removeDigit(unsigned int digit, unsigned int *num) {
    unsigned int th = 1;
    for (; digit > 0; digit--) th *= 10;
    while (*num / th % 10 != 0) *num -= th;
}

I was thinking about the runtime of the algorithm. I'm pretty sure its "technically" O(1), but I also see why you could say it is O(n).
The fact that an integer cannot have more than 11 digits, effectively makes it O(1), but you could still argue that for an arbitrary data type with an endless amount of digits, this algorithm is O(n).
What would you say? If someone were to ask me what the runtime of this is, what should I say?

A:
What would you say? If someone were to ask me what the runtime of this is, what should I say?

When you give some time/space asymptotic bounds, typically it is because the algorithm can be used on arbitrarily large inputs.
In this case, your possible inputs are so constrained that providing the absolute maximum number of given operations/cycles/time that will take place worst-case can be a much more useful metric instead, in some domains.
Also consider that, given this is a very simple algorithm, you could simply provide the exact equations for the number of given operations/cycles/time, too; which is way more precise than giving either asymptotic bounds or absolute maximums.

A: The for loop is executed digit+1 times. The while loop is executed nd times, where nd denotes the value of the designated digit. So in total generality, the asymptotic complexity is
O(digit + nd).

This formula is valid for any number length and any numeration base, but assumes that the arithmetic operations are done in constant time, which is somewhat unrealistic.
In any base, it is clear that nd = O(1), as this number is bounded by the base. So in the worst case,
O(digit).

Now for fixed-length arithmetic, digits is bounded so that digits = O(1). And as a consequence, the worst-case complexity is also
O(1).

Note that there is no incompatibility between the complexity being O(digits + nd) and the worst-case complexity being O(1). This is justified by digits and nb both being O(1).

A: Other answers and comments have missed the fact that removeDigit(1000000000,p) will do a billion iterations of the first loop...  So this is certainly not O(1).   Sometimes in this kind of analysis we make use of the fact that machine words are of constant size, but asymptotic analysis ceases to be useful when we treat the largest possible integer value as a constant.
So...  unless otherwise specified, the N in O(N) or similar refers to the size of the input.  The size of an integer x would usually be considered to be log2 x when it matters, so in terms of that usual convention, your function takes O(2n) time, i.e., exponential.
But when we use asymptotic analysis in real life we try to convey useful information when we make a statement of complexity.  In this case the most useful thing you can say is that removeDigit(digit,p) takes O(digit) time.


text:
Q: android listview row number remove zero I have List view to display title, i need to add row numbers in my getView. My code working fine but my list view Poisson Start from Zero (0), How can i disable it?
  @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View rowView;
        if(convertView == null) {
            rowView = getActivity().getLayoutInflater().inflate(R.layout.searchitemview, null);
        } else {
            rowView = convertView;
        }

        TextView firstTextView = (TextView) rowView.findViewById(R.id.txtTitle);
        firstTextView.setText(items.get(position).first);

        TextView number = (TextView) rowView.findViewById(R.id.number);
        number.setText(""+position);

        TextView thirdTextView = (TextView) rowView.findViewById(R.id.txtSize);
        if(items.get(position).fourth != "00:00" || items.get(position).fourth != ""){
            thirdTextView.setText("Duration: " + items.get(position).fourth);
        }else{
            thirdTextView.setVisibility(View.GONE);
        }

        return rowView;
    }
}

This code start row number from Zero (0) i want my list view row number start from one (1)

A: The indexes start from 0 by default, increase it yourself:
number.setText(String.valueOf(position+1));


text:
Q: Tailwind not applying a gradient Update/TLDR: Not to do with webpack as I thought below - I was overwriting the gradient classes in the config by accident.

Is there any reason why a gradient like this one: bg-gradient-to-r from-purple-500 to-pink-500
would work in a codepen, but wouldn't apply to my project? (uses webpack and a tailwind config file).
I've read a couple of solutions based around changing the config file to set up custom colors, but I'm a bit confused as to why it wouldn't just work out of the box? The element seems to be working fine (it'll take a bg color for example), and the gradient appears to be applying the classes:

I mean I can get it to work like this I guess? But I'm learning Tailwind so was interested if I was missing something
@layer{
 .grad  {
   background-image: linear-gradient(to right, #a855f7, #ec4899);
  }
 }

*Update: added a small repo example here. I've added the gradient to the second section
**Update 2: This doesn't happen when not using webpack, the gradient class works fine then. See this minimal repo

A: Adding the answer in case someone else makes the same mistake.
So it turns out I'd accidently overwritten the gradient classes by using:
backgroundImage: {
  'hero-pattern-desktop': "url('/src/images/bg-header-desktop.png')",
  'hero-pattern-mobile': "url('/src/images/bg-header-mobile.png')"
},

outside of extend.
Credit to the Tailwind creator who got back to me real quickly: here.


text:
Q: give detailed steps for installation of beautifulsoup for python to use in notepad++ Can anyone give me the detailed answer on hoe to install beautifulsoup on python. i tried to download it but got the following traceback:
Traceback (most recent call last):
  File "C:\Users\user\Desktop\Python\Programs\first_code.py", line 6, in
    from BeautifulSoup import *
ImportError: No module named BeautifulSoup
Can anyone give detailed steps to follow!!!!

A: According to documentation you use import wrong way.
Should be:
from bs4 import BeautifulSoup


text:
Q: Created AWS EC2 instance from snapshot AMI, eth0 is missing after startup I recently created a new EC2 from a snapshot of our Production EC2.
The machine started up fine, and I can ssh in, however - cannot access via anything else. No WWW, nothing.
Upon further inspection of the device, primarily the network stack - I see this:
/etc/udev/rules.d/70-persistent-net.rules
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="06:68:f3:22:91:f2", NAME="ens5"

ifconfig
ens5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 172.31.12.146  netmask 255.255.240.0  broadcast 172.31.15.255
        inet6 fe80::468:f3ff:fe22:91f2  prefixlen 64  scopeid 0x20<link>
        ether 06:68:f3:22:91:f2  txqueuelen 1000  (Ethernet)
        RX packets 492  bytes 81928 (80.0 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 474  bytes 76982 (75.1 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 6  bytes 416 (416.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6  bytes 416 (416.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Note the ens5 at the first line of the ifconfig.
[/etc] # service network restart
Restarting network (via systemctl):  Job for network.service failed because the control process exited with error code. See "systemctl status network.service" and "journalctl -xe" for details.
                                                       [FAILED]

[/etc] # systemctl status network.service
● network.service - LSB: Bring up/down networking
   Loaded: loaded (/etc/rc.d/init.d/network; bad; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2018-10-16 11:13:34 EDT; 1min 4s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 2223 ExecStart=/etc/rc.d/init.d/network start (code=exited, status=1/FAILURE)
   CGroup: /system.slice/network.service
           └─857 /sbin/dhclient -1 -q -lf /var/lib/dhclient/dhclient--ens5.lease -pf /var/run/dhclient-ens5.pid -H ip-172-31-12-146 ens5

Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal network[2223]: RTNETLINK answers: File exists
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal network[2223]: RTNETLINK answers: File exists
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal network[2223]: RTNETLINK answers: File exists
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal network[2223]: RTNETLINK answers: File exists
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal network[2223]: RTNETLINK answers: File exists
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal network[2223]: RTNETLINK answers: File exists
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal systemd[1]: network.service: control process exited, code=exited status=1
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal systemd[1]: Failed to start LSB: Bring up/down networking.
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal systemd[1]: Unit network.service entered failed state.
Oct 16 11:13:34 ip-172-31-12-146.us-west-1.compute.internal systemd[1]: network.service failed.

It cannot find eth0, nor can it restart the network stack. I have tried rebooting the machine, shutting down and starting up, with no luck. What am I missing?

A: Did you change from older instance type to T3 / M5 / C5? These have got a different hardware and use different device names.
One option is to reconfigure the network stack to reflect the new device names - that may be quite an undertaking unless you're a skilled Linux admin and know what you are doing.
Or, easier, change the instance type to the same that you made the snapshot from. That should fix the device names back to what they used to be.
You can change the size, e.g. from large to medium, but keep the type - if it was T2 use T2 again.
Also I suggest you restore it from the snapshot to a fresh instance - the current one has probably tried to accommodate the new device names and may be in inconsistent state. Better to start again from the Prod snapshot.
Hope that helps :)

A: You can modify the device name in the udev rule you posted. Edit that line and rename ens5 to eth0
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="06:68:f3:22:91:f2", NAME="eth0"


text:
Q: What does this debug log of Storm mean? I just learned storm, and tested the WordCount example code from here. It uses setDebug(true) to enable the debug logging.
But I am confused with these debug information:
13867 [storm.starter.WordCountTopology.main()] INFO  backtype.storm.daemon.nimbus -
Setting new assignment for topology id word-count-1-1403745226:
#backtype.storm.daemon.common.Assignment{:master-code-dir "/tmp/4ef1358b-92ce-4051-a4ce-
b33a25ace66d/nimbus/stormdist/word-count-1-1403745226", :node->host {"47fdd74b-65e0-4650-
a000-f1f0418dd7c7" "ms-VirtualBox"}, :executor->node+port {[2 2] ["47fdd74b-65e0-4650-a000-
f1f0418dd7c7" 1027], [3 3] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027], [4 4] ["47fdd74b-
65e0-4650-a000-f1f0418dd7c7" 1027], [5 5] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027], [6
 6] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027], [7 7] ["47fdd74b-65e0-4650-a000-
f1f0418dd7c7" 1027], [8 8] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027], [9 9] ["47fdd74b-
65e0-4650-a000-f1f0418dd7c7" 1027], [10 10] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027],
[1 1] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027]}, :executor->start-time-secs {[2 2]
1403745226, [3 3] 1403745226, [4 4] 1403745226, [5 5] 1403745226, [6 6] 1403745226, [7 7]
1403745226, [8 8] 1403745226, [9 9] 1403745226, [10 10] 1403745226, [1 1] 1403745226}}

...

14547 [Thread-6] INFO  backtype.storm.daemon.supervisor - Launching worker with
assignment #backtype.storm.daemon.supervisor.LocalAssignment{:storm-id "word-count-1-
1403745226", :executors ([2 2] [3 3] [4 4] [5 5] [6 6] [7 7] [8 8] [9 9] [10 10] [1 1])} for
 this supervisor 47fdd74b-65e0-4650-a000-f1f0418dd7c7 on port 1027 with id 80043f34-85af-
4862-840e-99a58b1cf1f5

...

    16140 [Thread-6] INFO  backtype.storm.daemon.executor - Loading executor count:[2 2]
    16153 [Thread-6] INFO  backtype.storm.daemon.task - Emitting: count __system ["startup"]
    16155 [Thread-6] INFO  backtype.storm.daemon.executor - Loaded executor tasks count:[2
2]
    16182 [Thread-6] INFO  backtype.storm.daemon.executor - Finished loading executor count:[2 2]
    16186 [Thread-8-count] INFO  backtype.storm.daemon.executor - Preparing bolt count:(2)
    16198 [Thread-6] INFO  backtype.storm.daemon.executor - Loading executor count:[3 3]
    16198 [Thread-6] INFO  backtype.storm.daemon.task - Emitting: count __system ["startup"]
    16198 [Thread-6] INFO  backtype.storm.daemon.executor - Loaded executor tasks count:[3
3]
    16206 [Thread-8-count] INFO  backtype.storm.daemon.executor - Prepared bolt count:(2)
    16213 [Thread-6] INFO  backtype.storm.daemon.executor - Finished loading executor count:
[3 3]
    16217 [Thread-10-count] INFO  backtype.storm.daemon.executor - Preparing bolt count:(3)
    16221 [Thread-10-count] INFO  backtype.storm.daemon.executor - Prepared bolt count:(3)

What does [1 1],[2 2] ... mean? Can someone give me some detailed explanation. Thanks very much.

A: Thanks for the comment, I found something useful there.
After taking a deep look at the concepts of component, node, worker, executor, task, I know what [1 1] means.
Firstly
:node->host {"47fdd74b-65e0-4650-a000-f1f0418dd7c7" "ms-VirtualBox"}

This means there's only one node here. Node id is 47fdd74b-65e0-4650-a000-f1f0418dd7c7, responding to the host machine ms-VirtualBox.
Secondly
:executor->node+port {[2 2] ["47fdd74b-65e0-4650-a000-f1f0418dd7c7" 1027],
...

The executor is a thread that runs spout/bolt instance, the above sentence shows where the executor is. [2 2] is the executor id, which responds to the node 47fdd74b-65e0-4650-a000-f1f0418dd7c7's 1027 port.
Since the WordCountTopology has the code snippet conf.setMaxTaskParallelism(3);, and there are 3 spout/bolt, the maximum number of executors for spout/bolt are 9 (from [2 2] to [10 10]). (1 task responds to 1 executor in this case) In addition, another executor ([1 1]) is spawned called acker, which will track tuple trees and detect when a spout tuple has been fully processed. So, there are 10 executors totally, from [1 1] to [10 10].

*

*Useful references:
Understanding the Parallelism of a Storm Topology


text:
Q: How to create a function that activates within a time limit unless user gives input in python I am trying to create a button in tkinter that once pressed, program waits for a specific time (here 1 second) and if the user doesn't press that button again, the function fun() is executed.
How can I get it to work?
To note, the button by default executes fun(), and also executes fun2() first time only.
import time
import threading
from tkinter import *

def fun():
    global label
    restart = time.perf_counter()
    label.pack()

def fun2(event, start):
    global restart
    restart = start
    but.unbind("<Button-1>", bind_no)
    t1 = threading.Thread(target = fun3)
    t1.start()

def fun3():
    global restart
    while True:
        while time.perf_counter()-restart<1:
            pass
        label.pack()

root = Tk()

label = Label(root, text="fun")

but = Button(root, text= "Click", command= fun)
bind_no = but.bind("<Button-1>", lambda eff: fun2(eff, time.perf_counter()))
but.pack()

root.mainloop()

A: You do not need threading or time; the mechanism to achieve the delayed/cancel behavior you describe can be implemented using tk.after
Maybe like this:
1- the button calls delay_action_fun
2- delay_action_fun triggers a callback that will call fun in one second.
3- if the button is not pressed again, fun is executed.
3.1 - if the button is pressed again before the callback is executed, the callback to fun is cancelled.
rinse & repeat.
import tkinter as tk

def fun():
    global call_back
    print('executing fun')
    call_back = None

def delay_action_fun():
    """calls fun to xeq in 1 second, but cancels the callback if
    triggered again within that time period
    """
    global call_back
    print('pressed')
    if call_back is None:
        call_back = root.after(1000, fun)
    else:
        print('cancelling cb')
        root.after_cancel(call_back)
        call_back = None

root = tk.Tk()

call_back = None
tk.Button(root, text= "xeq fun", command=delay_action_fun).pack()

root.mainloop()


text:
Q: C++ scoped variables re-ordering and timers I am very much trilled with the how a scoped_lock works and was wondering weather a similar implementation can be done as to time a particular code of execution
If say I implement a simple class scoped_timer which on construction initiates a timer and on deletion it stops and report the time elapsed, then would this sample code be timed correctly
func()
{
    //some code
    {
       scoped_timer a;
       //some code that does not include a
     }
     //some code
 }

In practice am I guaranteed that scoped_time a is constructed at the beginning  and destructed exactly when it is out of scope. Can the compiler decide to reorder the code in such a way as not to destruct it exactly at the end of scope or construct it at the beginning since there is no dependence on the object a? Are there guarantees from C++ standard?
Thanks
Daniel

A: The code is guaranteed to behave as you would like.
This guarantee is important in C++, because C++ is not a functional programming language, due to the fact that almost any function in C++ can have side effects (either from the flow of execution of the current thread, or from other threads or even other processes, whether or not the data is declared as volatile).  Because of this, the language specification makes guarantees about the sequencing of full expressions.
To piece this together from the C++11 standard, there are a number of clauses that must be considered together.
The most important clause is §1.9:

§1.9 Program execution [intro.execution]
1 The semantic descriptions in this International Standard define a
  parameterized nondeterministic abstract machine. This International
  Standard places no requirement on the structure of conforming
  implementations. In particular, they need not copy or emulate the
  structure of the abstract machine. Rather, conforming implementations
  are required to emulate (only) the observable behavior of the abstract
  machine as explained below. * (<-- the footnote is in the standard itself)
* This provision is sometimes called the "as-if" rule, because an implementation is free to disregard any requirement of this
  International Standard as long as the result is as if the requirement
  had been obeyed, as far as can be determined from the observable
  behavior of the program. For instance, an actual implementation need
  not evaluate part of an expression if it can deduce that its value is
  not used and that no side effects affecting the observable behavior of
  the program are produced.

(The bolding of the text is mine.)
This clause imposes two important requirements that are relevant for this question.

*

*If an expression may have side effects, it will be evaluated.  In your case, the expression scoped_timer a; may have side effects, so it will be evaluated.

*"...conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.", where "below" includes Clauses 13 and 14 of the same section:

§1.9.13 Sequenced before is an asymmetric, transitive, pair-wise
  relation between evaluations executed by a single thread (1.10), which
  induces a partial order among those evaluations. Given any two
  evaluations A and B, if A is sequenced before B, then the execution of
  A shall precede the execution of B. If A is not sequenced before B and
  B is not sequenced before A, then A and B are unsequenced. [ Note: The
  execution of unsequenced evaluations can overlap. —end note ]
  Evaluations A and B are indeterminately sequenced when either A is
  sequenced before B or B is sequenced before A, but it is unspecified
  which. [ Note: Indeterminately sequenced evaluations cannot overlap,
  but either could be executed first. —end note ]
§1.9.14 Every value computation and side effect associated with a
  full-expression is sequenced before every value computation and side
  effect associated with the next full-expression to be evaluated. * (<-- the footnote here is not relevant)

Therefore, your expression scoped_timer a; (which is a full expression) may have side effects and will be evaluated; so the computation of the value of a will be sequenced before any of the following statements in the block.
Regarding destruction of the object a, that is simpler.

§3.7.3.3 If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be
  destroyed before the end of its block, nor shall it be eliminated as
  an optimization even if it appears to be unused, except that a class
  object or its copy/move may be eliminated as specified in 12.8.

This makes clear that the destructor will not be called until the block exits.
ADDENDUM And to confirm that all block-level variables are destroyed (and their destructor called) at the end of block scope, here it is in the C++11 standard:

§3.7.3.1 Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration.
  The storage for these entities lasts until the block in which they are
  created exits.
§3.7.3.2 [ Note: These variables are initialized and destroyed as described in 6.7. —end note ]

... and the above-mentioned §6.7:

§6.7.2 Variables with automatic storage duration (3.7.3) are initialized each time their declaration-statement is executed.
  Variables with automatic storage duration declared in the block are
  destroyed on exit from the block (6.6).

The block is defined as all code between a pair of curly braces {} here:

§6.3.1 So that several statements can be used where one is expected, the compound statement (also, and equivalently, called "block") is provided.
compound-statement:

    { statement-seq }

statement-seq:

    statement

    statement-seq statement

A compound statement defines a block scope (3.3).

Note: The compount-statement (etc) section takes a while to get used to, but the important point is that here, the open curly brace { and close curly brace } actually mean a literal open curly brace and close curly brace in the code.  This is the exact place in the C++11 standard where block scope is defined as the sequence of statements between curly braces.
Putting the pieces together: Because the standard, as quoted above, says The storage for these entities lasts until the block in which they are created exits and that Variables with automatic storage duration declared in the block are destroyed on exit from the block, you are assured that the object a in your question (and ANY block-level object) will last until the end of the block, and will be destroyed and have its destructor called when the block exits.


text:
Q: php script is parsing content from RTE (tt_news) but internal links are not appearing as speaking url I have a news article with internal links. In the RTE I see links like
http://www.yourdomain.com/?id=3
in the html text mode. The problem is that this link also appears on the frontend. RealURL should convert this link to something like
http://www.yourdomain.com/products/
The content of RTE is currently parsed like this
$parseObj = t3lib_div::makeInstance('t3lib_parsehtml_proc');
$txt = $parseObj->TS_links_rte($result['bodytext']);
$txt = $parseObj->TS_transform_rte($txt);

I read that I should use something like this
$pObj = t3lib_div::makeInstance('tslib_pibase');
$txt = $pObj->pi_RTEcssText($result['bodytext']);

but I don't know how can I access this function. I get
Fatal error: Call to a member function parseFunc() on a non-object in /home/myuser/www/home/typo3/sysext/cms/tslib/class.tslib_pibase.php on line 1384
What is the right way doing this? How can I access the function pi_RTEcssText? Do I have to use a class? Are there other ways doing it without a class?
EDIT:
I created a new template with TemplaVoila and defined lib.newscontent as TS object path.
TS Main Template
includeLibs.user_news = fileadmin/templates/php_scripts/news/class.news.php

lib.newscontent = USER_INT
lib.newscontent {
  userFunc = user_news->main
  userFunc.bodytext.parseFunc < lib.parseFunc_RTE
}

class.news.php
<?

class user_news {

    var $cObj;

    private $conf;

    function main($content,$conf) {
        $this->conf = $conf;
        $this->setPreferences();
        $content .= $this->aktuelleNews();

        return $content;
    }

    private function aktuelleNews() {
        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                '*',         // SELECT ...
                'tt_news',     // FROM ...
                'pid=22 AND deleted=0 AND hidden=0',    // WHERE...
                '',            // GROUP BY...
                'datetime DESC'    // ORDER BY...
        );

        $i = 1;
        $out_list = '
';
        while ($data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
            $date = date("d.m.Y",$data['datetime']);
            $out_list .= '
'.$date.': '.$data['title'].'
';
            $out_detail.= $this->outputnewsdetail($data,$i);

            $i++;
        }
        $out_list .= '
';
        return $out_list . $out_detail;
    }

    private function outputnewsdetail($result,$count){
        $this->cObj->start($result, 'tt_news');

        $bodytext = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext']);
        $bodytext = $this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);

        return $bodytext;

    }

    private function setPreferences() {

    }

}
?>

localconf.php
include(PATH_site.'fileadmin/templates/php_scripts/news/class.news.php');

Remaining question
Why does the rendering part in the TS Main Template doesn't work? I used
$this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);

to get my result.

A: I would prefer:
$txt = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext.']);

You need in your main method: $this->conf = $conf;
In your TypoScript add the parseFunc to bodytext:
 plugin.tx_yourplugin_pi1 {
    bodytext.parseFunc < lib.parseFunc_RTE
 }

The main idea is to use the usual parseFunc which is used by content elements. So you have the same rendering. Another benefit is, that your application is more flexible.
Just as a side note. It is worth to make a lokal cObj for that and hand over the complete data. So you are able to use alle fields in TypoScript. F.e. field = bodytext in your case.
# create lokal cObj - do not override the original data!
$cObj = t3lib_div::makeInstance('tslib_cObj');
foreach ($row = ...) {
   # override data array with row. Every field in $row is now accesible via
   # TypoScript field = fieldname
   $cObj->start($row, $tableName);
   $content .= $cObj->stdWrap($row['bodytext'], $this->conf['bodytext.']);
}

# TS Setup:
# in your case you could do somesthing like:
plugin.tx_yourplugin_pi1 {
    bodytext.parseFunc < lib.parseFunc_RTE
    bodytext.wrap =
|

    bodytext.prepend = TEXT
    bodytext.prepend.field = bodytext
    bodytext.prepend.stripHtml = 1
    bodytext.prepend.crop = 30 | ... | 1
    bodytext.prepend.wrap = info
}

If you need it in an user function try it like this:
function user_yourfunction($content,$conf) {
    $result = *magic*
    $cObj = t3lib_div::makeInstance('tslib_cObj');
    $cObj->start($result, 'your table name');
    return $cObj->stdWrap($result['bodytext'], $conf['bodytext.']);
}

In TypoScript:
includeLibs.something = media/scripts/example_callfunction.php
page.10 = TEXT
page.10 {
   value = Hello World
   postUserFunc = user_yourfunction
   postUserFunc.bodytext.parseFunc < lib.parseFunc_RTE
}


text:
Q: What is the concept of "Last Good Reply" and "Rapid Action Value Estimation" in Monte Carlo Simulation? I have developed a simple hex player based on Monte Carlo Tree Search for the game of Hex. Now I want to extend the hex player using RAVE (Rapid Action Value Estimation) and LGP (last good reply). The articles are here and here.
I was wondering if anyone here has used any of these methods to improve the tree search performance and could help me understand it?
I also want to know why these algorithms are called AMAF (All Moves As First) heuristics?

A: In the realm of monte carlo tree search in games which takes advantage of reinforcement learning, there are two types of back-propagation, AMAF and UCT.
UCT method back-propagates the path which during selection phase it has passed. only nodes which during selection are met are back-propagated exactly at their states. But in AMAF, All the nodes that are met during roll_out phase are stored and in the back-propagation phase, along with nodes in the selection path, are back-propagated without considering the states.
UCT gives a very precise and local value of a (state,action) pair, but it is too slow to converge. on the other hand AMAF heuristic converges very fast, but (state,action) pair value is too general and can't be reliable.
We can have benefits of both strategies by using a decreasing coefficient for values like this:
a * UCT + (1 - a) * AMAF
This is RAVE(Rapid Action Value Stimation) heuristic.
Last-Good-Reply is AMAF-based but could benefit from RAVE. its general idea is that in playout phase, when we use moves against opponent moves, if these moves were successful against opponents', so we might be able to store these moves and use them in next playouts.


text:
Q: How can i read specified rows in Google Spreadsheets I have a question that is , how to read rows which have data ? Rows are empty i dont want to read them. Otherwise , i want to.
Here is my code:
from queue import Empty
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scopes = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]

cred = ServiceAccountCredentials.from_json_keyfile_name("C:/Users/dell/OneDrive - khang06/My-Workspace/Programming/CLB-Stem-TamPhu/EmailSender/my_key.json" , scopes=scopes)

file = gspread.authorize(cred)
workbook = file.open("Application_to_Tam_Phu_Stem_Club")

sheet = workbook.worksheet("Responses")

Hopefully , i can be helped. Thanks a lot

A: Hi unfortunately if you don't know which row has data and which row doesn't before you run your code, that won't be possible.
Basically you have 2 options:

*

*You already know that, let say the first 10 rows contain data, so you only read the first 10 rows ( which does not seem to be your case)

*You read the entire sheet or one row at the time and you check what is in it.
You can't ask gspread or Google spreadsheet to return only rows with data.


text:
Q: Exclusive filtering by tag I'm using rails 3.0 and MySql 5.1
I have these three models:
Question, Tag and QuestionTag.
Tag has a column called name.
Question has many Tags through QuestionTags and vice versa.
Suppose I have n tag names. How do I find only the questions that have all n tags, identified by tag name.
And how do I do it in a single query.
(If you can convince me that doing it in more than one query is optimal, I'll be open to that)
A pure rails 3 solution would be preferred, but I am not adverse to a pure SQL solution either.
Please notice that the difficulty is in making a query which does not give all the questions that have any of the tags, but only the questions that have all the tags.

A: This is the solution I found for myself. Unmodified, it will only work in Rails 3 (or higher).
In the Tag model:
scope :find_by_names, lambda { |names|
  unless names.empty?
    where("tags.name IN (#{Array.new(names.length, "?").join(",")})", *names)
  else
    where("false")
  end
}

In the Question model:
scope :tagged_with, lambda { |tag_names|
  unless tag_names.blank?
    joins(:question_tags).
    where("questions.id = question_tags.question_id").
    joins(:tags).where("tags.id = question_tags.tag_id").
    group("questions.id").
    having("count(questions.id) = ?", tag_names.count) & Tag.find_by_names(tag_names)
  else
    scoped
  end
}

The & Tag.find_by_names(tag_names) combines the two scopes such that the join on tags is really a join on the scoped model.
[Update]
My sql-fu has improved a little, so I thought I'd offer a pure SQL solution also:
SELECT q.*
FROM (
SELECT DISTINCT q.*
FROM `questions` q
JOIN question_tags qt
ON qt.question_id = q.id
JOIN tags t
ON t.id = qt.tag_id
WHERE t.name = 'dogs'
) AS q
JOIN question_tags qt
ON qt.question_id = q.id
JOIN tags t
ON t.id = qt.tag_id
WHERE t.name = 'cats'

This finds all the questions that have been tagged with both 'cats' and 'dogs'. The idea is to have a nested subquery for each tag I want to filter by.
There are several other ways to this. I'm not sure if it makes a difference to have the subquery in the FROM clause instead of the WHERE clause. Any insight would be appreciated.


text:
Q: An interesting limit property of zeros of Bessel functions? I was trying to prove the orthogonality relations
\begin{equation}
\int\limits_0^\infty k r \cdot J_n[k r] \cdot J_n[k^{'} r] dr  = \delta(k-k^{'}) \tag{1}
\end{equation}
for the Bessel functions, as quoted here  for example. I followed the Sturm-Liouville approach as described here for example. Starting from the ODE being satisfied by the functions in question  it is fairly easy to show that the following identity holds true:
\begin{equation}
\int\limits_0^M r \cdot J_n[ \frac{\theta_n^{(p)}}{M} r] \cdot J_n[ \frac{\theta_n^{(q)}}{M} r] dr = \delta_{p,q}  \cdot \frac{M^2}{2} (-1) J_{n-1}[\theta_n^{(p)}] J_{n+1}[ \theta_n^{(p)}] \tag{2}
\end{equation}
where $M >0$ and $\left( \theta_n^{(p)} \right)_{p=1}^\infty $ are zeros of the Bessel function $J_n()$.
If we now multiply $(2)$ by $\theta_n^{(p)}/M$ and then by $(\theta_n^{(p)} - \theta_n^{(p-1)})/M$ and then take the limit $M \rightarrow \infty $ then, if $(1)$ is true, we should be getting the following:
\begin{equation}
\lim\limits_{p \rightarrow \infty}\frac{1}{2} (\theta_n^{(p)} - \theta_n^{(p-1)}) (-\theta_n^{(p)}) \cdot J_{n-1}[\theta_n^{(p)}] J_{n+1}[ \theta_n^{(p)}] = 1 \tag{3}
\end{equation}
Now we have tested $(3)$ numerically using the code below:
n = RandomReal[{1/10, 5}]; mm = 50;
ths = Table[BesselJZero[n, k], {k, 1, mm}];

ListPlot[Table[(ths[[p]] - ths[[p - 1]])/2 (-ths[[p]]) BesselJ[n - 1,
    ths[[p]]] BesselJ[n + 1, ths[[p]]], {p, 2, mm}]]

As you can see truncating the left hand side of $(3)$ at $p \le 10$ gives already the right hand side to three digits of precision.
Therefore my question would be twofold. Firstly, how do you go about proving $(1)$.
Secondly, can we prove that odd conjecture $(3)$ without using $(1)$?

A: The meaning of the expression is that the Hankel transform followed by the inverse Hankel transform (which is the same as the Hankel transform) gives you back the original function $f$:
$$
           f(r)=\int_0^\infty J_{\nu}(kr)\left(\int_0^\infty f(\rho)J_\nu(k\rho)\rho d\rho\right) kdk
$$
Without regard to issues of interchanging order of integration, you can rewrite this expression as
$$
            f(r)=\int_0^{\infty}\left(\int_0^\infty J_{\nu}(kr)J_{\nu}(k\rho)k dk\right)f(\rho)\rho d\rho
$$
So the inner integral appears to be
$$
           \int_0^{\infty}J_{\nu}(kr)J_{\nu}(k\rho)kdk = \delta(r-\rho).
$$
You really need to deal with the truncated integral and allow the upper limit on this integral to tend to $\infty$. Then things can be made rigorous. The first integral in your post does not converge, and neither does my last integral. However, this does make sense under reasonable Fourier-type conditions on $f$:
$$
    \lim_{R\rightarrow\infty}\int_0^\infty\left(\int_0^{R}J_{\nu}(kr)J_{\nu}(k\rho)kdk \right)f(\rho)\rho d\rho = f(r).
$$


text:
Q: AutoComplete for UITextfield in iOS I am working on new iOS application. In that app, I have 5 UITextFields and those are
1. first interest, second interest upto 5 interests.
I need to add Autocomplete for those 5 UITextFields. I have searched google for one day. I got some forums and tutorial for that. But I even have tried with Github links also.
According to my requirement, I have an array of data which is getting from my server. In that array, I have data like, coffee, cricket, etc. That is Autocomplete data. I need to display that array whenever user entered text in UITextField, if its related to my array of data, need to display below of that UITextFields.
For that purpose i used following code.
**// String in Search textfield
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

NSString *substring = [NSString stringWithString:textField.text];
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    [self searchAutocompleteEntriesWithSubstring:substring];
    return YES;
}

**
// Take string from Search Textfield and compare it with autocomplete array
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {

// Put anything that starts with this substring into the autoCompleteArray
// The items in this array is what will show up in the table view

[autoCompleteArray removeAllObjects];
NSLog(@"autoCompleteArray %@",autoCompleteArray);
for(NSString *curString in elementArray) {
    NSRange substringRangeLowerCase = [curString rangeOfString:[substring lowercaseString]];
    NSRange substringRangeUpperCase = [curString rangeOfString:[substring uppercaseString]];

    if (substringRangeLowerCase.length != 0 || substringRangeUpperCase.length != 0) {
        [autoCompleteArray addObject:curString];
    }
}

autoCompleteTableView.hidden = NO;
[autoCompleteTableView reloadData];
      }

And I created UITableView as AutocompleteTableview in ViewDidLoad method.
**Issue is, if I type text as suppose "c", from my array of data displaying whatever text contains as "c" letter in tableview. But, if i typed "coff" no data displaying in that UITableView. Also how to validate which UITextField user clicking in tableviewdidselectrowatindexpath delegate method. I tried with assigning tag for those UITextFields, but its working in UITextFields delegate methods only, not in other place. so, whenever i selected data from UITableView, first UITextField only taking data not other UITextField.
Please give your valuable suggestion, which is the best way to display the autocomplete for UITextfields in iOS for multiple UITextfields and how to handle UITableView for displaying data. If anything mistakes in my content forgive me and please provide your valuable suggestions to fix this issue.
Thanks****

A: Here is swift 3 inline autocomplete textfield example

*

*Image look like bellow

*create a project & add a textfield. Connect to viewcontroller named txtAutoComplete

*View controller code bellow
 import UIKit

   class ViewController: UIViewController ,UITextFieldDelegate{

    @IBOutlet weak var txtAutoComplete: UITextField!

     var autoCompletionPossibilities = ["01921687433", "01553377642", "0155776622"]
    var autoCompleteCharacterCount = 0
   var timer = Timer()

  override func viewDidLoad() {
     super.viewDidLoad()

      txtAutoComplete.delegate = self
 }

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //1
       var subString = (textField.text!.capitalized as NSString).replacingCharacters(in: range, with: string)
subString = formatSubstring(subString: subString)

   if subString.characters.count == 0 {
   // 3 when a user clears the textField
    resetValues()
       } else {
     searchAutocompleteEntriesWIthSubstring(substring: subString)
    }
   return true
  }

 func formatSubstring(subString: String) -> String {
    let formatted = String(subString.characters.dropLast(autoCompleteCharacterCount)).lowercased().capitalized //5
    return formatted
 }

func resetValues() {
   autoCompleteCharacterCount = 0
   txtAutoComplete.text = ""
  }

  func searchAutocompleteEntriesWIthSubstring(substring: String) {
  let userQuery = substring
  let suggestions = getAutocompleteSuggestions(userText: substring)

    if suggestions.count > 0 {
      timer = .scheduledTimer(withTimeInterval: 0.01, repeats: false, block: { (timer) in //2
        let autocompleteResult =   self.formatAutocompleteResult(substring: substring, possibleMatches: suggestions)
           self.putColourFormattedTextInTextField(autocompleteResult: autocompleteResult, userQuery : userQuery)
          self.moveCaretToEndOfUserQueryPosition(userQuery: userQuery)
      })

     } else {
       timer = .scheduledTimer(withTimeInterval: 0.01, repeats: false, block: { (timer) in //7
          self.txtAutoComplete.text = substring
       })
       autoCompleteCharacterCount = 0
     }

}

 func getAutocompleteSuggestions(userText: String) -> [String]{
   var possibleMatches: [String] = []
   for item in autoCompletionPossibilities { //2
      let myString:NSString! = item as NSString
      let substringRange :NSRange! = myString.range(of: userText)

      if (substringRange.location == 0)
       {
          possibleMatches.append(item)
      }
   }
   return possibleMatches
}

 func putColourFormattedTextInTextField(autocompleteResult: String, userQuery : String) {
      let colouredString: NSMutableAttributedString = NSMutableAttributedString(string: userQuery + autocompleteResult)
colouredString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSRange(location: userQuery.characters.count,length:autocompleteResult.characters.count))
self.txtAutoComplete.attributedText = colouredString
}

 func moveCaretToEndOfUserQueryPosition(userQuery : String) {
    if let newPosition = self.txtAutoComplete.position(from: self.txtAutoComplete.beginningOfDocument, offset: userQuery.characters.count) {
    self.txtAutoComplete.selectedTextRange = self.txtAutoComplete.textRange(from: newPosition, to: newPosition)
}
      let selectedRange: UITextRange? = txtAutoComplete.selectedTextRange
txtAutoComplete.offset(from: txtAutoComplete.beginningOfDocument, to: (selectedRange?.start)!)
   }

 func formatAutocompleteResult(substring: String, possibleMatches: [String]) -> String {
     var autoCompleteResult = possibleMatches[0]
autoCompleteResult.removeSubrange(autoCompleteResult.startIndex..<autoCompleteResult.index(autoCompleteResult.startIndex, offsetBy: substring.characters.count))
autoCompleteCharacterCount = autoCompleteResult.characters.count
return autoCompleteResult
    }
  }

*Source code is given to GitHub.GitHub Link :https://github.com/enamul95/AutoCompleteTextField

A: - (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring{

    //Assume this array is the autocomplete array for which you get data from server

    NSMutableArray *autoCompleteArray = [[NSMutableArray alloc] initWithObjects:@"Coffee",@"Cricket",@"Volleyboll",nil];

    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];

   // This is to create predicate filter for getting matched text

   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@",text];

// store matched data for autocompletion in results array and reload data in your tableview based on this array's data

   NSArray *resultArray = [[NSArray alloc] initWithArray:[autoCompleteArray filteredArrayUsingPredicate:predicate]];
}

A: Take two Global Array
NSMutableArray *muary_Interest_Main;
NSMutableArray *muary_Interest_Sub;

IN viewDidLoad Method
muary_Interest_Main = [[NSMutableArray alloc]initWithObjects:@"Cricket",@"Dancing",@"Painting",@"Swiming",@"guitar",@"movie",@"boxing",@"drum",@"hockey",@"chessing",@"gamming",
    @"hunting",@"killing",@"shoping",@"jamm"@"zooming", nil];
muary_Interest_Sub = [[NSMutableArray alloc]init];

tbl_Search = [[UITableView alloc] initWithFrame:
CGRectMake(4, 200, 320, 120) style:UITableViewStylePlain];
tbl_Search.delegate = self;
tbl_Search.dataSource = self;
tbl_Search.scrollEnabled = YES;

[self.tbl_Search registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CellIdentifier"];
[self.view addSubview:self.tbl_Search];

[tbl_Search setHidden:TRUE];

Now write a below code in textfield delegates.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"%d",textField.tag);
int_TextFieldTag = textField.tag;

[self searchText:textField replacementString:@"Begin"];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
tbl_Search.hidden = TRUE;
return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
tbl_Search.hidden = TRUE;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[self searchText:textField replacementString:string];
return YES;
}

Write a method for search text
-(void) searchText:(UITextField *)textField replacementString:(NSString *)string
{

    if(int_TextFieldTag == 1)
    {
        tbl_Search.frame = CGRectMake(4, 200, 320, 120);

    }
    else if(int_TextFieldTag == 2)
    {
        tbl_Search.frame = CGRectMake(4, 248, 320, 120);
    }
    else if(int_TextFieldTag == 3)
    {
        tbl_Search.frame = CGRectMake(4, 268, 320, 120);
    }
    else if(int_TextFieldTag == 4)
    {
        tbl_Search.frame = CGRectMake(4, 268, 320, 120);
    }
    else
    {
        tbl_Search.frame = CGRectMake(4, 268, 320, 120);
    }

    NSString *str_Search_String=[NSString stringWithFormat:@"%@",textField.text];
    if([string isEqualToString:@"Begin"])
        str_Search_String=[NSString stringWithFormat:@"%@",textField.text];
    else if([string isEqualToString:@""])
        str_Search_String = [str_Search_String substringToIndex:[str_Search_String length] - 1];
    else
        str_Search_String=[str_Search_String stringByAppendingString:string];

    muary_Interest_Sub=[[NSMutableArray alloc] init];
    if(str_Search_String.length>0)
    {
        NSInteger counter = 0;
        for(NSString *name in muary_Interest_Main)
        {
            NSRange r = [name rangeOfString:str_Search_String options:NSCaseInsensitiveSearch];
            if(r.length>0)
            {
                [muary_Interest_Sub addObject:name];
            }

            counter++;

        }

        if (muary_Interest_Sub.count > 0)
        {
            NSLog(@"%@",muary_Interest_Sub);
            tbl_Search.hidden = FALSE;
            [self.tbl_Search reloadData];
        }
        else
        {
           tbl_Search.hidden = TRUE;
        }

    }
    else
    {
        [tbl_Search setHidden:TRUE];

    }

}

Tableview Delegates methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [muary_Interest_Sub count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CellIdentifier"];
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
;
}
cell.textLabel.text = [muary_Interest_Sub objectAtIndex:indexPath.row];
return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.view endEditing:YES];
if(int_TextFieldTag == 1)
{
txt1.text=[muary_Interest_Sub objectAtIndex:indexPath.row];

}
else if(int_TextFieldTag == 2)
{
txt2.text=[muary_Interest_Sub objectAtIndex:indexPath.row];
}
else if(int_TextFieldTag == 3)
{
txt3.text=[muary_Interest_Sub objectAtIndex:indexPath.row];
}
else if(int_TextFieldTag == 4)
{
txt4.text=[muary_Interest_Sub objectAtIndex:indexPath.row];
}
else
{
txt5.text=[muary_Interest_Sub objectAtIndex:indexPath.row];
}

}

This also works on backspace of textfield.
Try this. Hope this will suit your requirements.

A: You can use the following links which describes how we can use autocompletion. I tried with the AutocompletionTableview (second link) and it worked perfectly.
https://github.com/EddyBorja/MLPAutoCompleteTextField
https://github.com/keyf/AutocompletionTableView


text:
Q: React, Using Refs to scrollIntoView() doesn't work in componentDidUpdate() I'm using Redux in my app, inside a Component I want to scroll to an specific div tag when a change in the store happens.
I have the Redux part working so it triggers the componentDidUpdate() method (I routed to this compoennt view already).
The problem as far as I can tell, is that the method scrollIntoView() doesn't work properly cos componentDidUpdate() has a default behavior that scrolls to the top overwriting the scrollIntoView().
To work-around it I wrapped the function calling scrollIntoView() in a setTimeout to ensure that happens afeterwards.
What I would like to do is to call a preventDefault() or any other more elegant solution but I can't find where to get the event triggering the 'scrollTop'
I looked through the Doc here: https://facebook.github.io/react/docs/react-component.html#componentdidupdate
and the params passed in this function are componentDidUpdate(prevProps, prevState) ,since there is no event I don't know how to call preventDefault()
I've followd this Docs: https://facebook.github.io/react/docs/refs-and-the-dom.html
And tried different approaches people suggested here: How can I scroll a div to be visible in ReactJS?
Nothing worked though
Here is my code if anyone has any tip for me, thanks
class PhotoContainer extends React.Component {

  componentDidUpdate(){
    setTimeout(() => {
     this.focusDiv();
    }, 500);

  }
  focusDiv(){
    var scrolling = this.theDiv;
    scrolling.scrollIntoView();

  }

  render() {
    const totalList = [];
    for(let i = 0; i < 300; i += 1) {
        totalList.push(

{`hello ${i}`}

        );
    }

  return (

          {totalList}

 this.theDiv = el}>this is the div I'm trying to scroll to

  )

};
    }

A: Ok it's been a while but I got it working in another project without the setTimeOut function so I wanted to answer this question.
Since Redux pass the new updates through props, I used the componentWillRecieveProps() method instead of componentDidUpdate() , this allowes you a better control over the updated properties and works as expected with the scrollIntoView() function.
class PhotoContainer extends React.Component {

  componentWillReceiveProps(newProps) {
    if (
      this.props.navigation.sectionSelected !==
        newProps.navigation.sectionSelected &&
      newProps.navigation.sectionSelected !== ""
    ) {
      this.focusDiv(newProps.navigation.sectionSelected);
    }
  }

  focusDiv(section){
    var scrolling = this[section]; //section would be 'theDiv' in this example
    scrolling.scrollIntoView({ block: "start", behavior: "smooth" });//corrected typo
  }

  render() {
    const totalList = [];
    for(let i = 0; i < 300; i += 1) {
        totalList.push(

{`hello ${i}`}

        );
    }

    return (

          {totalList}

 this.theDiv = el}>
            this is the div I am trying to scroll to

         )
      };
    }

A: I also struggled with scrolling to the bottom of a list in react that's responding to a change in a redux store and I happened upon this and a few other stackoverflow articles related to scrolling. In case you also land on this question as well there are a few ways this could be a problem. My scenario was that I wanted a 'loading' spinner screen while the list was rendering. Here are a few wrong ways to do this:

*

*When loading = true, render spinner, otherwise render list.

{loading ?
   <Spinner />
:
   <List />
}

as stated above this doesn't work because the list you might want to scroll to the bottom of isn't rendered yet.

*When loading set the display to block for the spinner and none for the list. When done loading, reverse the display.

   <Spinner />

   <List />

This doesn't work either since the list you want to scroll to the bottom of isn't actually being displayed likely when you call the scroll.
The better approach for the above scenario is to use a loading  that acts as an overlay to the  component. This way both the spinner and list are rendered and displayed, the scroll happens, and when the loading is complete, the spinner can be de-rendered or set to be invisible.


text:
Q: Finding strrpos of \ in a String Here's a puzzler. I have a variable that contains computer file paths. I need to separate the filename from the path.
Example:
 From this:
$filepath = C:\\User\Me\Myfiles\file.jpg

I need this:
$path = C:\\User\Me\Myfiles\
$file = file.jpg

I know how to get the substrings of $filepath using substr. The problem is using "\" as a "needle" to get the position of the filename.
This causes an error:
$pos = strrpos("\",$filepath);

This doesn't cause an error, but doesn't give me a value for $pos:
$pos = strrpos("\\",$filepath);

As always, any help with be rewared with my eternal gratitude.

A: $pos = strrpos("\\",$filepath);

This is trying to find the position of $filepath in the string "\\". Unless the $filepath is a single backslash, no position will be returned.
You want to swap the two arguments around.
$pos = strrpos($filepath, "\\");

Also, basename($filepath) or pathinfo($filepath, PATHINFO_BASENAME) can be used to get the file name.

A: Look at the output of pathinfo($filepath), or for an oo approach, at the available methods of SplFileInfo.

A: preg_match('#^(.+)\\\\(.+)$#', $filepath, $matches);
$path = $matches[1];
$file = $matches[2];

This works because the + regex quantifier is greedy, so it will match all the characters it can.  The \ is double-escaped, once for the PHP string, and once for the regex.


text:
Q: What is this syntax in java? I find a syntax String[]::new in this answer.
but I search this in google can't find useful information.

A: This is actually a shorthand for a lambda, a recent addition to Java:
size -> new String[size]

which in turn is shorthand for an IntFunction:
new IntFunction<String[]> {
  @Override
  String[] apply(int size) {
    return new String[size];
  }
}

As you can see, these additions to Java 8 make the language a bit less verbose.

A: This is a method reference to a constructor. The ClassName::method is just a terser syntax for using lambda expressions that call existing methods (in this case new), as opposed to those which call anonymous methods.


text:
Q: How do I count distinct events over sequential seconds? I have a database with multiple columns, date, timestamp (HH:MM:SS), and phone numbers. I am trying to find a way to find unique calls in sequential seconds. For Example:
Date          Timestamp     Phone_number
10-12-2019    15:15:23      999-999-9999
10-12-2019    15:15:23      999-999-9999
10-12-2019    15:15:24      999-999-9999
10-12-2019    15:15:24      999-999-9999
10-12-2019    15:15:25      999-999-9999
10-12-2019    15:20:21      111-111-1111
10-12-2019    15:20:21      111-111-1111
10-12-2019    15:20:22      111-111-1111
10-12-2019    15:22:33      999-999-9999

Ideally, I'd like to count the first 999-999-9999 as one call and 111-111-1111 as one call, and the second 999-999-9999 call as a call on the basis of the calls have the same timestamp or occurred in sequential seconds.
With an output similar to this with a count of 1 with the min(timestamp) of the non sequential call:
Date          Timestamp     Phone_number
10-12-2019    15:15:23      999-999-9999
10-12-2019    15:20:21      111-111-1111
10-12-2019    15:22:33      999-999-9999

I'm not entirely sure where to start. I believe I'd have to create a subselect of the time based on the previous second. Not sure how to implement it...or if it would hand timestamps with the same second
SELECT t1.time, t1.phone_number, COUNT(DISTINCT t2.x)
FROM myTable AS t1
JOIN myTable AS t2 ON t2.timestamp BETWEEN DATE_SUB(t1.timestamp, INTERVAL 1 second) AND t1.timestamp
GROUP BY t1.timestamp, t1.phone_number

I'm using MySql. Open to any help! Thank you in advance

A: In MySQL 8.0, this can be solved using window function lag(). You can recover the date/time of the previous call to the same number in a subquery, and then filter out records for which a previous call to the same number occured one second before:
select date, timestamp, phone_number
from (
    select
        t.*,
        lag(concat(date, ' ', timestamp))
            over(partition by phone_number order by date, timestamp) lag_datetime
    from mytable t
) x
where
    lag_datetime is null
    or concat(date, ' ', timestamp) > lag_datetime + interval 1 second

Note: storing date and time in separated columns is not a good idea, since it complicates the logic when you need to actually compare date/times.
Demo on DB Fiddle:
| date       | timestamp | phone_number |
| ---------- | --------- | ------------ |
| 2019-10-12 | 15:15:23  | 999-999-9999 |
| 2019-10-12 | 15:20:21  | 111-111-1111 |
| 2019-10-12 | 15:22:33  | 999-999-9999 |

A: This is a complicated problem.  It is difficult because:

*

*You have the date/time columns in two columns.

*You have duplicate rows.

*Calls could span multiple days.

So, I think the best approach is a range partition after combining the date and time columns into a single column:
select t.*
from (select t.*,
             max(phone_number) over (partition by phone_number
                                     order by timestamp(date, timestamp)
                                     range between 1 second preceding and current row
                                    ) as prev_phone_number
      from t
     ) t
where prev_phone_number is null or prev_phone_number <> phone_number;