text:
Q: How to add a label with directlabels when using multiple geoms? I'm struggling to create labels at the right end of a line plot with directlabels when I'm using more than one geom. Here is an example:
#load packages
library(dplyr)
library(ggplot2)
library(tidyr)
library(directlabels)

#create data
set.seed(1)
test <- tibble(year = as.factor(rep(1990:2000, 4)),
     label = rep(replicate(4, paste0(sample(letters, 20), collapse = "")), each =11), #create long random labels
     value = rnorm(44))
test[which(test$year==2000),]$value <- seq(0,0.1, length.out = 4) # make final values very similar

average <- test %>%
     group_by(year) %>%
     summarize(value = mean(value)) %>%
     bind_cols(label = "average")

#draw plot
ggplot(test, aes(x = year, y = value, group = label, color = label)) +
  geom_line() +
  geom_smooth(data = average,
              mapping = aes(x = year, y = value, group = label, color = label),
              inherit.aes = F, col = "black") +
  geom_dl(aes(label = label,
              color = label),
          method = list(dl.combine("last.bumpup"))) +
  theme(legend.position = "none")

This gives this plot:

Now I'm looking to add a black-colored label at the right of the geom_smooth line that says "average". One of the problems I found with some of the methods I've tried is that it overlaps with the other labels when I create it separately and that it does not show up in black.
For example:
ggplot(test, aes(x = year, y = value, group = label, color = label)) +
  geom_line() +
  geom_smooth(data = average,
              mapping = aes(x = year, y = value, group = label, color = label),
              inherit.aes = F, col = "black") +
  geom_dl(aes(label = label,
              color = label),
          method = list(dl.combine("last.bumpup"))) +
  geom_dl(data = average,
          mapping = aes(label = label,
              color = label),
          method = list(dl.combine("last.bumpup"))) +
  theme(legend.position = "none")

gives this plot:

To summarize, I'm looking to create a label for geom_smooth that has the same color as the geom_smooth line and does not collide with the other labels.
One caveat: I can't use the stat_summary (as proposed elsewhere) because in my actual data, the average is weighted and since I don't know the weights, I can't go from individual data points to the average. So I need to take the averages provided in the dataframe.
Update
In my actual data, the labels are much longer (10-30 characters) and some of them have very similar y-values at the highest year. This is why I used directlabels with the bumpup argument. There will likely be overlap if the labels don't repel each other.

A: Try using ggrepel as an alternative to directlabels.
(Updated approach following revised question)
Note it might be more elegant to include the average data line and label in the test data adapted for labelling. This approach requires some manual tweaking for the "Average" label.
There are other geom_text_repel() arguments not used which might allow improvement of positioning.
library(dplyr)
library(ggplot2)
library(tidyr)
library(ggrepel)

set.seed(1)
test <- tibble(year = as.factor(rep(1990:2000, 4)),
               label = rep(replicate(4, paste0(sample(letters, 20), collapse = "")), each =11), #create long random labels
               value = rnorm(44))
test[which(test$year==2000),]$value <- seq(0,0.1, length.out = 4) # make final values very similar

average <- test %>%
  group_by(year) %>%
  summarize(value = mean(value)) %>%
  bind_cols(label = "average")

# initial plot with labels for lines
# For fuller description of possible arguments to repel function, see:
# https://ggrepel.slowkow.com/articles/examples.html
p <-
  ggplot(test, aes(x = year, y = value, group = label, color = label)) +
  geom_line() +
  geom_smooth(data = average,
              mapping = aes(x = year, y = value, group = label, color = label),
              inherit.aes = F, col = "black") +
  geom_text_repel(data = filter(test, year == 2000),
                  aes(label = label,
                      color = label),
                  direction = "y",
                  vjust = 1.6,
                  hjust = 0.5,
                  segment.size = 0.5,
                  segment.linetype = "solid",
                  box.padding = 0.4,
                  seed = 123) +
  coord_cartesian(clip = 'off')+
  scale_x_discrete(expand = expansion(mult = c(0.06, 0.0)))+
  theme(legend.position = "none",
        plot.margin = unit(c(5, 50, 5, 5), "mm"))

# find coordinates for last point of geom_smooth line, by inspection of ggplot_buildt

lab_avg <-
  slice_tail(ggplot_build(p)$data[[2]], n = 1) %>%
  mutate(label = "Average")

# plot with label for geom_smooth line
# positioning of the Average label achieved manually varying vjust and hjust,
# there is probably a better way of doing this

p1 <-
  p +
  geom_text_repel(data = lab_avg,
          aes(x = x, y = y, label = label),
          colour = "black",
          direction = "y",
          vjust = 3.5,
          hjust = -7,
          segment.size = 0.5,
          segment.linetype = "solid",
          segment.angle = 10,
          box.padding = 0.4,
          seed = 123)
p1

Created on 2021-08-22 by the reprex package (v2.0.0)
Initial answer to original question.
You could try with geom_text() using data from the average dataset and adjusting the location of "Average" using hjust and vjust.
Use scale_x_discrete(expand...) to create a bit of extra space for the text label.

ggplot(test, aes(x = year, y = value, group = label, color = label)) +
  geom_line() +
  geom_smooth(data = average,
              mapping = aes(x = year, y = value, group = label, color = label),
              inherit.aes = F, col = "black") +
  geom_dl(aes(label = label,
              color = label),
          method = list(dl.combine("last.bumpup"))) +
  scale_x_discrete(expand = expansion(mult = c(0.06, 0.2)))+
  geom_text(data = slice_tail(average, n = 1),
            aes(x = year, y = value, label = "Average"),
            colour = "black",
            hjust = -0.2,
            vjust = 1.5)+
  theme(legend.position = "none")

Created on 2021-08-21 by the reprex package (v2.0.0)


text:
Q: can't access to symfony installer in symfony.com I'm a newcomer to Symfony and I have problem installing it . On the Symfony website it says that I have to type:
 php -r "file_put_contents('symfony', file_get_contents('https://symfony.com/installer'));"

it errors :
Warning: file_put_contents(symfony): failed to open stream: Permission denied in Command line code on line 1

Note: I installed composer already and I have WAMP server and I can create a folder in c directory,
and also when I typed
php -r "readfile('https://symfony.com/installer');" > symfony

in cmd it says:
Access is denied

I surfed on stackoverflow but I couldn't find any useful answers although some topics are related to my problem!!

A: You might be having a permissions issue on Windows.
Try starting the command prompt by right-clicking it and selecting "Run as Administrator". Also run the command from the folder that you created. For example if you created the folder C:\bin, run the command from that folder.

A: *

*download it by the URL in your navigator https://symfony.com/installer

*put the downloaded symfony.phar in your project's folder

*go in the folder with the console and run "php symfony.phar new yourProjectName"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems starting UPS sync service When provisioning the User Profile Service Application via Powershell, we can not start the User Profile Synchronization Service, no matter what.
It gets stuck on starting, and after a while gets the status "Stopped".
We have checked all the pre-requisities, and run this script also:
http://sharepointbjorn.com/2014/06/25/user-profile-synchronization-autofixer/
If we create the service application manually, then the "User Profile Synchronization Service" can be started.
Have been trying with a lot of different scripts from different blogs and Technet, but tested with this now.
$appPool = New-SPServiceApplicationPool -Name "UPS" -Account "SP2013\SP_ProfilesAppPool"

if($appPool -eq $null)
{
    Write-Host "App pool is null"
}
else
{
    $ups = New-SPProfileServiceApplication –Name "User Profile"  -ApplicationPool $appPool  -ProfileDBServer "SP2013Dev" -ProfileDBName "ProfilesDB"   -SocialDBServer "SP2013Dev" -SocialDBName "SocialDB"   -ProfileSyncDBServer "SP2013Dev" -ProfileSyncDBName "SyncDB"  -MySiteHostLocation "http://my.test.com:8081"
}

$app = Get-SPServiceApplication -Name "User Profile"

if($app -eq $null)
{
    Write-Host "Null"
}
else
{
    New-SPProfileServiceApplicationProxy -Name "User Profile Proxy" -ServiceApplication $app
}

The service application gets created, the proxy gets created. The service application is clickable and looks good.
The databases are created, but the User Profile Synchronization Service will never start when provisioned with PowerShell.

A: The User Profile Synchronization Service must be provisioned by the farm account. So if you run your Powershell script using another account (the setup account typically), it will fail.
The solution is either:
1) To run your Powershell script using the farm account. Try shift+right click on Powershell shortcut -> "run as another user"; or directly log in to the server with the farm account (not a best practice, the farm account is a service account, we are not supposed to use it directly).
or
2) Launch the provisionning using another identity. See this post from Harbar for instance (I never tried this 'Start-Job' method): http://www.harbar.net/archive/2010/10/30/avoiding-the-default-schema-issue-when-creating-the-user-profile.aspx
Note: remember to temporarily add the farm account to the local Administrators group during provisionning.


text:
Q: Push a number in useState array In a form having multiple checkbox, I want to store the values of the check box in an useState array after clicking submit. Also the user may check/uncheck a check box multiple times before submitting the form. What can be the approach/code?

A: Every checkbox have a "checked" property, so in state you must have an array with all the checked checkboxes.
const [selectedCheckboxes, setSelectedCheckboxes] = useState([]);

For example you might store also the checkboxes on an array:
const checkboxes = [{name: 'cb1', label:'cb1'}, {name: 'cb2', label:'cb3'}, ...];

and all of them should have the same onChange method:
onCheckBoxChange = (event) => {
const selectedCheckboxes = [...selectedCheckboxes];
const isChecked = selectedCheckboxes.includes(event.target.name);
if (!isChecked) {
  selectedCheckboxes.push(event.target.name);
} else {
  selectedCheckboxes.splice(selectedCheckboxes.indexOf(event.target.name), 1);
}
setSelectedCheckboxes(selectedCheckboxes);

};
a common function that verify if a checkbox is checked:
isChecked = (cb) => selectedCheckboxes.includes(cb.name);

and every checkbox should look like:
   <CheckBox
  name={cb.name}
  checked={isChecked(cb)}
  onChange={onCheckBoxChange}
  {...props}
/>

A: You can make it multiple ways. You can just make const checkboxOpenArray = [] where you will just store boolean values like [true, false, false, true] so later in the code where you probably .map through all checkboxes you just check if checkboxOpenArray[idx] where idx you get from .map. If it is true you just set checkbox to true. Same for onChange - you just find idx in the checkboxOpenArray and set it to false or true.


text:
Q: Cassandra N copies in N cluster? I'm trying to configure Cassandra cluster on EC2.
The thing is that (for my purposes) I want to have N replicas in N machine cluster (all machine should have the same data).
I did the following:
- made a N machine cluster; all seeds; I deployed schema with replication factor N
- populate the base with WRITE ALL consensus
- now I'm trying to access data with WRITE ANY, and READ ONE.
- I load balance my clients and theoretically I should have a N time better throughput, however that is not the case.
nodetool shows in Owns column sum of 100%, instead of N*100% (each node should have all data).
any suggestions?

A: If you increase replicas to N you will not see any throughput benefits, since Cassandra now has to write N copies.  You will also not see any throughput benefits on reads, unless you disable read repair.
Best practice is to keep replica count constant as you increase N.


text: Q: Muted microphone ubuntu I was trying to enable noise cancellation on ubuntu 20.04 LTS and was able to do it from  here. Then I was trying to fix echo from local speakers and followed this tutorial and I was no longer able to get sound from the microphone, anyone can please help me and also enable noise cancellation and also fix echo from local speakers ? thanks in advanced !!


text:
Q: How to get the value of a Business Central Page field based on a global variable In the Demand Forecast page 99000919, all of the "Header" data fields are backed by global variables. I need to default the View by Period (PeriodType) to Month and then validate the value. I have not been successful at doing so.
A. Using Modify(PeriodType) to get the value from the OnAfterValidate trigger. PeriodType shows up in intellisense when I use the Modify, but when I try to use it, I get a compiler error that PeriodType does not exist in the current context.
    modify(PeriodType)
    {
    trigger OnAfterValidate()
    begin
        MyPeriodType := PeriodType;
    end;
    }

B. I also tried to use the VS Code teventsub code snippet to subscribe to the OnAfterValidate event for PeriodType, but there is nothing exposed.
    [EventSubscriber(ObjectType::Page, Page::"Demand Forecast", 'OnBeforeValidateEvent', 'PeriodType', true, true)]

Can this be done in the SaaS solution with extensions? Any ideas or suggestions are welcomed.

A: At the moment there does not appear to be any events for you to subscribe to, that would help you solve the problem.
The first thing to do then is to submit a request to Microsoft to add the needed events to the product. Request New Events
That being said there is a workaround for your problem, which involves a few steps:

*

*Create a copy of Demand Forecast (Page 99000919).

*Code your required changes in your copy of the page

*Substitute the original page with your copy

The last step is achieved by identifying all places where the original page is opened and then overtaking the code.
There are three places where Demand Forecast is opened:

*

*Page 99000921, Demand Forecast Names, Action Edit Demand Forecast

*Page 8907, Sales & Marketing Manager RC, Action Forecast

*Codeunit 5530, Calc. Item Availability

1 and 2 are run non-modal which means in both cases you can do the following:
[EventSubscriber(ObjectType::Page, Page::"Demand Forecast Names", 'OnBeforeActionEvent', 'Edit Demand Forecast', true, true)]
local procedure Page_DemandForecastNames_OnBeforeActionEvent_EditDemandForecast(var Rec: Record "Production Forecast Name")
var
    DemandForecastCopy: Page "Demand Forecast"; // this variable should reference your copy
begin
    DemandForecastCopy.SetProductionForecastName(Rec.Name);
    DemandForecastCopy.Run();
    Error(''); // this creates a silent error which cancels the original execution of the action.
end;

SetProductionForecastName should not be called for "Sales & Marketing Manager RC".
The third one is a bit trickier because the page is run modal from the codeunit, but since we have now replaced all occurrences where the page is run non-modal, we can now assume that every time the original Demand Forecast is opened it should be modal.
Unfortunately subscribing to the Demand Forecast OnOpenPageEvent won't help you because there are no parameters to get values from. So you have to backtrack the code from Calc. Item Availability to find all possible entry points and then override the default implementation as described earlier.


text: Q: jQuery Validation - Can you get it to validate disabled fields? Natively the jQuery validation plugin will not validate fields that are disabled. How can I override this behavior? I still want the fields disabled, but I want them to be validated too.


text:
Q: How do I pull in new products and have them be displayed in a carousel in Magento? I'm somewhat of a noob with Magento. I was wondering if there was a way to display new products on the home page by using jcarouselLite? I have static content in there now for a placer. Is there a way to pull in products that are newly listed and have it be displayed in the carousel? If so, how would I go about doing that? I unfortunately don't have a link to show as of right now. I appreciate any help/advice.

A: For any product, check if current date matches with new from date or new to date for that product then that product will be considered as a new product.
Alternately you can create a category and associate the products to be shown as new with this category and then show the product associated with that category


text:
Q: Подключить libcurl к проекту в MinGW Studio Я скачал библиотеку curl для win32. Там есть библиотека с расширением .a. Как ее подключить к проекту? Я использую MinGW Studio

A: Первое, что нужно сделать, после распаковки архива с библиотекой - указать дополнительные пути, по которым компилятор сможет найти её заголовочные файлы, а линковщик - саму библиотеку. Соответственно, в архиве должны быть как минимум вот эти папки, со всеми необходимыми файлами внутри:
bin\      - *.dll
include\  - *.h
lib\      - *.a

Для MinGW могу порекомендовать вот этот репозиторий:

*

*curl: https://bintray.com/vszakats/generic/curl#files

*openssl: https://bintray.com/vszakats/generic/openssl#files
Пути можно указывать либо через глобальные настройки Edit - Options - Directories, либо, в каждом проекте и в каждой конфигурации (Debug/Release) отдельно, через Project - Settings:

*

*на вкладке Compile, в Additional include directories нужно прописать полный путь к include папке:

*

*на вкладке Link, в Additional library path - полный путь к папке lib:

И наконец, на вкладке Link, в поле Libraries нужно прописать название линкуемой библиотеки, без приставки lib и без расширения. Т.е. если на диске файл лежит под именем libcurldll.a, то мы должны записать его как curldll.
После этого можно собирать проект. А чтобы собранный exe запустился, рядом с ним должны находиться зависимые dll: libcurl.dll, libcrypto-1_1.dll, libssl-1_1.dll (либо, они должны находиться в PATH).
И кстати, MinGW Studio нужна с GCC 4.8.1 и в настройках компиляции обязательно нужно указать флаг -std=c99. Иначе, ничего не скомпилируется.


text:
Q: Multi line comment in SASS throwing error I am using multi-line comments
/*
* common styles go here
*/
style definitions continue...
I get an error in compilation. It says:
Error: Invalid CSS after "*/": expected identifier, was ""

Please note: I am not using SCSS and I do not wish. Don't ask me why. So kindly post answers that do not contain SCSS solutions.

A: Try to indent the comment */ along with the content by at least 2 spaces, if you are using it on a multiline. Here's an example on codepen: http://codepen.io/anon/pen/XjJAbQ

/* This should work */

///*
//This won't work!
//*/

///*
//This will not work
//  */

/**
  * This is a multi line comment
  * And this should work.
  */

// This is a sass comment
.someClass
  width: 200px
  height: 200px
  background: #000
<div class="someClass">

</div>


text:
Q: Can't connect to WPA2/PEAP/MSCHAPv2 enterprise wifi network without a certificate. Fedora 34 My university wifi uses WPA2 Enterprise for students to connect with their logins and passwords and I cannot do it, network manager always says the password is incorrect and prompts me for another one even though the password is correct.
My problem is simmiliar to https://askubuntu.com/questions/279762/how-to-connect-to-wpa2-peap-mschapv2-enterprise-wifi-networks-that-dont-use-a-c but none of the solutions work for me. I use Fedora 34 Gnome, my wifi adapter model is Intel AX200
My /etc/NetworkManager/system-connections/UNIVERSITY.WIFI look like this
[connection]
id=UNIVERSITY.WIFI
uuid=0cdeb50f-03dd-45ba-85df-465027f0e12a
type=wifi
interface-name=wlp1s0
permissions=

[wifi]
hidden=true
mac-address-blacklist=
mode=infrastructure
ssid=UNIVERSITY.WFIFI
[wifi-security]
key-mgmt=wpa-eap

[802-1x]
eap=peap;
identity=my_login
password=my_password
phase2-auth=mschapv2

[ipv4]
dns-search=
method=auto

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

[proxy]

A: Here's your answer:

Looks like after setting the phase 2 crypto settings with:
update-crypto-policies --set LEGACY

as indicated here: I was able to connect with no issues.

Your TLS certificate probably uses either SHA-1 (most likely) or RSA-1028 (less likely). Both are rejected now.
Test by downgrading your system policy to allow all crypto that was permitted in Fedora 32:
$ sudo dnf install crypto-policies-scripts
$ sudo update-crypto-policies --set DEFAULT:FEDORA32

If my guess is wrong, you'll want to revert to secure Fedora 33 default > settings:
$ sudo update-crypto-policies --set DEFAULT

TL;DR:
sudo update-crypto-policies --set LEGACY


text:
Q: Is it possible to add click function that would pop up audio files for my code? I have written code with mouseover to display gifs over an image. Is it possible to add a mouse enter so that audio files will be displayed when I click on the image.
I am new to jQuery and lost at the moment.

A: I would use sme data- attributes to store the second image source and the sound to play.
Then using .on(), you can define the handlers for every events. And this is a much clearer way than inline onmouseover and onmouseout handlers which you have to repeat the same code everywhere...
I suggest you to use one single class for all those images having the same behavior. See the example below.

$(".someClass").on({

  "mouseenter": function(){
    // Save the original src in a data attribute
    $(this).data("original_src",$(this).attr("src"));
    // change the src with the second src
    $(this).attr("src",$(this).data("alt_src"));
  },

  "mouseleave": function(){
    // Restore the original src
    $(this).attr("src",$(this).data("original_src"));
  },

  "click": function(){
    // Play the sound
    var sound = $("<audio>").attr("src",$(this).data("sound"));
    sound[0].play();
  }
});
.someClass{
  max-width: 300px;
  max-height: 400px;
  cursor: pointer;
}


text:
Q: Android - Download excel folder and store it to database I want to download an excel file and store it into SQLite, i"ve been searching but couldn't find anything, thanks

A: Storing binary files in SQLite database is really bad idea. I should store Excel files in application (cache) directory and store filename to this file in SQLite only.
Anyway if you wants really store these files in SQLite you have to have BLOB column type.


text:
Q: Deserialize collection type virtual data member I'm trying to deserialize json to RequestWithDefault object
JSON:
{
  "fields":["f1","f2"]
}

My simple class diagram:
[DataContext]
public abstract class BaseRequest
{
  [DataMember]
  public virtual List<string> Fields { get; set; }
}

[DataContext]
public class RequestWithDefault : BaseRequest
{
  [DataMember]
  public override List<string> Fields {get; set; } = new List<string> {"test"}
}

After deserializing json to RequestWithDefault object Fields property contains ["test", "f1", "f1"]. I want to be sure that this default values are applied only in case when Fields were not specified in request, or was specified as null. How I can do this? I tried with [OnDeserializing] attribute but without success. Result is the same
According to this:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/collection-types-in-data-contracts
Looks like during deserialization DataContractSerializer calling Add method from collection. That's why I have also default value and rest of items are added. When I will replace List<string> to string[] everything works fine.

A: It seems WCF serialization never use setter to set the value of the DataMember with type of collection, but use Add instead. Because of this, the only way to check whether the fields has any value is to check after it has been deserialized (not while deserializing).
[DataContext]
public abstract class BaseRequest
{
  [DataMember]
  public virtual List<string> Fields { get; set; }
}

[DataContext]
public class RequestWithDefault : BaseRequest
{
    [System.Runtime.Serialization.OnDeserialized]
    void OnDeserialized(System.Runtime.Serialization.StreamingContext c)
    {
        if (Fields == null
            || Fields.Count < 1)
        {
            Fields = new List<string> { "test" };
        }
    }
}


text:
Q: Issue with simultaneous development & testing - SP 2010 There is a server where both development & testing is going on simultaneously. Now SIT team has raised 5 issues. Development team has fix 1 issue & want to redeploy that functionality. If we deploy code sit team cannot test at that time. Now question is how to overcome this situation so that both redeployment of code & testing by SIT team can run simultaneously? What is the way-out?
let's say this is a hypothetical situation & developer is redeploying the dll, but main question is how both can happens together?

A: You cannot expect deploy code and test at the same time.
Two options come to mind:

*

*Deploy the new code during an agreed upon maintenance window. You can use the same server but you will need to communicate with the team doing the testing and let them know they can't test during this time.

*Get another server purely for testing. IMO, this is the better option because then you can do development at the same time the other team is testing without interrupting each other.


text:
Q: Deriving Equation of a Plane Suppose that in the following graphic, the orange parallelogram represents a plane in $\mathbb{R}^3$ which does not pass through the origin, whilst $P_1$ and $P_2$ represent points which lie on the plane. Is it possible to derive the equation of the plane with no more information than that given here (i.e. the two known points - $P_1$ and $P_2$)?

A: No. Two points are not enough ! Example: the planes
$x+y+z=1$
and
$2x+2y=2$
both contain the points $P_1=(1,0,0)$ and $P_2=(0,1,0).$

A: Two points determine a line, and there are infinitely many planes containing that line, so it is not possible to specify the equation of the plane containing them, without further information.  If, however, we are given a particular normal vector to the plane, then it is possible.  Note that the normal vector must be perpendicular to $P_2-P_1$.  For example, if $P_1=(1,0,0)$ and $P_2=(0,1,0)$, then $P_2-P_1=(-1,1,0)$, so the normal vector must be in the direction $(1,1,k),$ for some $k,$ in order to be perpendicular to (i.e., have zero dot product with) $(-1,1,0)$.  The equation of the plane will then be $1x+1y+kz=D$.  In order to find $D$, note that plugging in either $P_1$ or $P_2$ (both of which must lie in the plane) shows $D=1$.  So the equation of a plane containing $P_1$ and $P_2$ is $x+y+kz=1$, where $k$ is arbitrary.  (Note that the stipulation that the plane does not contain the origin excludes the plane $0x+0y+kz=0$.)


text:
Q: Recursive Functions return value I don't seem to understand the logic behind this particular code. I don't understand why the answer is 18. You can check for the answer in a compiler as well. Anyone wh understands the logic please let me know.
Here's the code:
#include <stdio.h>
int GuessMe(int,int);
main() {
    printf("%d", GuessMe(8,2));
}

int GuessMe(int x, int y) {
    if ( y >  x)
        return x
    else
        return GuessMe(x-2, y+2) + x;
}

A: Initially, GuessMe is passed x=8,y=2:
x | y | y > x ? | initial return value |  final return value
8 | 2 |    NO   |  GuessMe(6, 4) + 8   |     18
6 | 4 |    NO   |  GuessMe(4, 6) + 6   |     10
4 | 6 |   YES   |         4            |      4

Read down the initial return value column and then read back up the final return value column once you hit an initial return value that isn't recursive.


text:
Q: Generate an error if number is repeated in a form I have a web form for admin purposes where the user can change the order that a group of records is shown on a webpage.
For example: A table (tblStuff) in a database has three fields:
ContentID, Content, RecordPosition

The table has, say, four records:
1, Guess what, 1
2, More stuff, 2
3, Some stuff, 3
4, That's right, 4

The SQL code is:
SELECT * FROM tblStuff ORDER BY RecordPosition ASC

The user can use the form to change the RecordPosition number so that the order can read:
3, Some stuff, 1
2, More stuff, 2
1, Guess what, 3
4, That's right, 4

So... How can I validate the form so that the same number isn't entered twice into the RecordPosition field?
Hope this makes sense.
Here's the whole page
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>

<%
' *** Restrict Access To Page: Grant or deny access to this page
MM_authorizedUsers=""
MM_authFailedURL="../default.asp"
MM_grantAccess=false
If Session("MM_Username") <> "" Then
  If (true Or CStr(Session("MM_UserAuthorization"))="") Or _
         (InStr(1,MM_authorizedUsers,Session("MM_UserAuthorization"))>=1) Then
    MM_grantAccess = true
  End If
End If
If Not MM_grantAccess Then
  MM_qsChar = "?"
  If (InStr(1,MM_authFailedURL,"?") >= 1) Then MM_qsChar = "&"
  MM_referrer = Request.ServerVariables("URL")
  if (Len(Request.QueryString()) > 0) Then MM_referrer = MM_referrer & "?" & Request.QueryString()
  MM_authFailedURL = MM_authFailedURL & MM_qsChar & "accessdenied=" & Server.URLEncode(MM_referrer)
  Response.Redirect(MM_authFailedURL)
End If
%>
<%
If Request.Form("action")="update" Then
  'Set variables for update
  Dim updateSQL, i
  Dim cContentID, cPositionNumber

'Loop through records on screen and update
For i = 1 To fFormat(Request.Form("counter"))

'Create the proper field names to reference on the form
cContentID = "ContentID" & CStr(i)
cPositionNumber = "PositionNumber" & CStr(i)

'Create the update sql statement
updateSQL = "UPDATE tblContent SET PositionNumber=" & fFormat(Request.Form(cPositionNumber)) & " WHERE ContentID=" & fFormat(Request.Form(cContentID))

'Run the sql statement
Call sRunSQL(updateSQL)
Next

'Refresh page
Response.Redirect("record-order-modify-updated.asp")
End If

Function fFormat(vText)
  fFormat = Replace(vText, "'", "''")
End Function

Sub sRunSQL(vSQL)
  set cExecute = Server.CreateObject("ADODB.Command")
  With cExecute
    .ActiveConnection = MM_ENG_STRING
    .CommandText = vSQL
    .CommandType = 1
    .CommandTimeout = 0
    .Prepared = true
    .Execute()
  End With
End Sub
%>
<%
Dim rsCharityDetails
Dim rsCharityDetails_cmd
Dim rsCharityDetails_numRows

Set rsCharityDetails_cmd = Server.CreateObject ("ADODB.Command")
rsCharityDetails_cmd.ActiveConnection = MM_ENG_STRING
rsCharityDetails_cmd.CommandText = "SELECT * FROM tblCharityDetails"
rsCharityDetails_cmd.Prepared = true

Set rsCharityDetails = rsCharityDetails_cmd.Execute
rsCharityDetails_numRows = 0
%>
<%
Dim rsNavBar
Dim rsNavBar_cmd
Dim rsNavBar_numRows

Set rsNavBar_cmd = Server.CreateObject ("ADODB.Command")
rsNavBar_cmd.ActiveConnection = MM_ENG_STRING
rsNavBar_cmd.CommandText = "SELECT * FROM tblMainMenu WHERE MainMenuID <6  OR MainMenuID >7"
rsNavBar_cmd.Prepared = true

Set rsNavBar = rsNavBar_cmd.Execute
rsNavBar_numRows = 0
%>
<%
Dim rsContent__smID
rsContent__smID = "1"
If (Request.QueryString("smID")   <> "") Then
  rsContent__smID = Request.QueryString("smID")
End If
%>
<%
Dim rsContent
Dim rsContent_cmd
Dim rsContent_numRows

Set rsContent_cmd = Server.CreateObject ("ADODB.Command")
rsContent_cmd.ActiveConnection = MM_ENG_STRING
rsContent_cmd.CommandText = "SELECT tblContent.*, tblMainMenu.MainMenuName, tblSubMenu.SubMenuName, tblSubMenu.SubMenuID FROM (tblContent LEFT JOIN tblMainMenu ON tblContent.MainMenuID = tblMainMenu.MainMenuID) LEFT JOIN tblSubMenu ON tblContent.SubMenuID = tblSubMenu.SubMenuID WHERE tblContent.SubMenuID = ? AND tblContent.DisplayRecord =1 ORDER BY tblContent.PositionNumber"
rsContent_cmd.Prepared = true
rsContent_cmd.Parameters.Append rsContent_cmd.CreateParameter("param1", 5, 1, -1, rsContent__smID) ' adDouble

Set rsContent = rsContent_cmd.Execute
rsContent_numRows = 0
%>
<%
Dim rsMenuList
Dim rsMenuList_cmd
Dim rsMenuList_numRows

Set rsMenuList_cmd = Server.CreateObject ("ADODB.Command")
rsMenuList_cmd.ActiveConnection = MM_ENG_STRING
rsMenuList_cmd.CommandText = "SELECT tblMainMenu.MainMenuID, tblMainMenu.MainMenuName, tblSubMenu.SubMenuID, tblSubMenu.SubMenuName FROM tblMainMenu INNER JOIN tblSubMenu ON tblMainMenu.MainMenuID = tblSubMenu.MainMenuID WHERE tblSubMenu.SubMenuID <> 6 AND tblSubMenu.SubMenuID <16 OR tblSubMenu.SubMenuID >19"
rsMenuList_cmd.Prepared = true

Set rsMenuList = rsMenuList_cmd.Execute
rsMenuList_numRows = 0
%>
<%
Dim rsHeaderImage
Dim rsHeaderImage_cmd
Dim rsHeaderImage_numRows

Set rsHeaderImage_cmd = Server.CreateObject ("ADODB.Command")
rsHeaderImage_cmd.ActiveConnection = MM_ENG_STRING
rsHeaderImage_cmd.CommandText = "SELECT MainMenuImage, MainMenuID FROM tblMainMenu"
rsHeaderImage_cmd.Prepared = true

Set rsHeaderImage = rsHeaderImage_cmd.Execute
rsHeaderImage_numRows = 0
%>
<%
Dim navBar__numRows
Dim navBar__index

navBar__numRows = -1
navBar__index = 0
rsNavBar_numRows = rsNavBar_numRows + navBar__numRows
%>
<%
Dim rptContent__numRows
Dim rptContent__index

rptContent__numRows = -1
rptContent__index = 0
rsContent_numRows = rsContent_numRows + rptContent__numRows
%>
<%
Dim Repeat_MenuList__numRows
Dim Repeat_MenuList__index

Repeat_MenuList__numRows = -1
Repeat_MenuList__index = 0
rsMenuList_numRows = rsMenuList_numRows + Repeat_MenuList__numRows
%>
<!DOCTYPE HTML>

<meta charset="iso-8859-1">

<meta name="viewport" content="width=device-width; initial-scale=1.0">

<title><%=(rsCharityDetails.Fields.Item("CharityName").Value)%> | English Website Administration</title>

<link href="../../scripts/mfm-standard-stylesheet.css" rel="stylesheet" type="text/css">

<link href="../scripts/mfm-admin-stylesheet.css" rel="stylesheet" type="text/css">

<link href="../../scripts/lightbox.css" rel="stylesheet" type="text/css" media="screen" />

Record Order

<%
Dim txtOldHeading
txtOldHeading = ""
    While ((Repeat_MenuList__numRows <> 0) AND (NOT rsMenuList.EOF))
If txtOldHeading = rsMenuList.Fields.Item("MainMenuName").Value Then
Else
txtOldHeading = rsMenuList.Fields.Item("MainMenuName").Value
%>

<%=(rsMenuList.Fields.Item("MainMenuName").Value)%>

<%
END IF
%>

 <% If (rsMenuList.Fields.Item("SubMenuID").Value) = "3" Then %>
     <%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
 <% ElseIf (rsMenuList.Fields.Item("SubMenuID").Value) = "15" Then %>
     <%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
 <% ElseIf (rsMenuList.Fields.Item("SubMenuID").Value) = "20" Then %>
     <%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
 <% Else %>
     <a href="record-order-modify.asp?smID=<%=(rsMenuList.Fields.Item("SubMenuID").Value)%>"><%=(rsMenuList.Fields.Item("SubMenuName").Value)%>
     <% End If %>

 <%
 Repeat_MenuList__index=Repeat_MenuList__index+1
 Repeat_MenuList__numRows=Repeat_MenuList__numRows-1
 rsMenuList.MoveNext()
Wend
%>

<% IF Request.ServerVariables("QUERY_STRING") <> "" THEN %>

Order/Re-order records for: <%=(rsContent.Fields.Item("SubMenuName").Value)%>

<%
Dim counter
While ((rptContent__numRows <> 0) AND (NOT rsContent.EOF))
counter = counter + 1
%>
<form action="record-order-modify.asp" method="post" class="recordPosition">

<%=(rsContent.Fields.Item("ContentTitle").Value)%>
<input type="hidden" value="<%=(rsContent.Fields.Item("ContentID").Value)%>" name="ContentID<%=counter%>">

      <%
    Dim tmp
    tmp = rsContent.Fields.Item("ContentData").Value
    %>
        <% =LEFT(tmp, INSTR((tmp & "."), ".")) %>..

      <% IF (IsNull(rsContent.Fields.Item("ContentImage").Value)) THEN %>

      <% ELSE %>

        <img src="<%=(rsContent.Fields.Item("ContentImage").Value)%>">

      <% END IF %>

      Current Record Position: (You may change it here)  <input type="text" name="PositionNumber<%=counter%>" tabindex="<%=counter%>" value="<%=(rsContent.Fields.Item("PositionNumber").Value)%>">

  <%
  rptContent__index=rptContent__index+1
  rptContent__numRows=rptContent__numRows-1
  rsContent.MoveNext()
Wend
%>

<input name="Submit" type="submit" value="Update Positions" tabindex="<%=counter%>">
<input name="Reset" type="reset" value="Reset All Changes" tabindex="<%=counter%>">

<input type="hidden" name="action" value="update">
<input type="hidden" name="counter" value="<%=counter%>">
</form>
<% ELSE %>

Select a listing to order/re-order using the list on the left.

<% END IF %>

<%
rsCharityDetails.Close()
Set rsCharityDetails = Nothing
%>
<%
rsNavBar.Close()
Set rsNavBar = Nothing
%>
<%
rsContent.Close()
Set rsContent = Nothing
%>
<%
rsMenuList.Close()
Set rsMenuList = Nothing
%>
<%
rsHeaderImage.Close()
Set rsHeaderImage = Nothing
%>

As requested by Allende, here's the generated form code.
<form action="record-order-modify.asp" method="post" class="recordPosition">

Investing in people and the environment
<input type="hidden" value="15" name="ContentID1">

Madagascar is an environmental hotspot...

      Current Record Position: (You may change it here)  <input type="text" name="PositionNumber1" tabindex="1" value="1">

The next generation
<input type="hidden" value="16" name="ContentID2">

Teaching Malagasy children to respect and nurture their environment is critical to the survival of Madagascar's biodiversity...

      Current Record Position: (You may change it here)  <input type="text" name="PositionNumber2" tabindex="2" value="2">

Recognition for our work
<input type="hidden" value="17" name="ContentID3">

Our work over 2 decades with 73 villages surrounding the Reserve of Betampona recently gained recognition at an international conference held at the University of East Anglia...

      Current Record Position: (You may change it here)  <input type="text" name="PositionNumber3" tabindex="3" value="3">

Adding value by adding forests
<input type="hidden" value="18" name="ContentID4">

Often the best way to protect an old forest is to plant a new one...

      Current Record Position: (You may change it here)  <input type="text" name="PositionNumber4" tabindex="4" value="4">

<input name="Submit" type="submit" value="Update Positions" tabindex="4">
<input name="Reset" type="reset" value="Reset All Changes" tabindex="4">

<input type="hidden" name="action" value="update">
<input type="hidden" name="counter" value="4">
</form>

A: If you want to prevent duplicate values in RecordPosition no matter how you insert/update them you can create a unique constraint this column
CREATE UNIQUE INDEX uq_idx_RecordPosition ON tblStuff(RecordPosition);

Here is SQLFiddle demo

A: If you're trying to do some client-side validation, you'd have to build an array that contains all the RecordPosition values.
Once you have that, you can check the array for duplicates. This has been asked a couple of times on SO: Easiest way to find duplicate values in a JavaScript array
Unfortunately I can't help any more than that because you don't include any code that shows how this is structured on your web page

A: Check before inserting data in to data base
ex: recordposition value 3 --> 1 then pass value 1
SELECT * FROM tblStuff Where RecordPosition=1
if record exist then give message to user this position is exist

A: Let's suppose you have form like this (notice all the inputs has the same class):
<form id="myForm" method="POST" action"someUrl">
    <input type="text" class="recordPosition"></input>
    <input type="text" class="recordPosition"></input>
    <input type="text" class="recordPosition"></input>
    <input type="text" class="recordPosition"></input>
</form>

You could do with jQuery something like this:
 $(document).ready(function(){

 $(".recordPosition").on("blur", function(){
     var allFieldsForOrder = $('.recordPosition');
     var count = 0;
     var i=0
    //console.log(allFieldsForOrder.length );
      while((i<allFieldsForOrder.length) && (count < 2)){
             if ($(allFieldsForOrder[i]).val()===$(this).val())
            {
             count++
            }
            i++;
     }

     if (count==2){
        alert("A duplicated value"); return false;}
    });
 });

For the html you posted you can use this:
Notice I don't store the position of the  duplicated the value.
$(document).ready(function(){
    //console.log($("input[type='text'][name^='PositionNumber'").length);
    $("input[type='text'][name^='PositionNumber'").each(function(){
         $(this).on("blur", function(){

         var allFieldsForOrder = $("input[type='text'][name^='PositionNumber'");
         var count = 0;
         var i=0

         while((i<allFieldsForOrder.length) && (count < 2)){
                if ($(allFieldsForOrder[i]).val()===$(this).val())
                {
                 count++
                }
                i++;
         }

         if (count==2){
            alert("A duplicated value");
         }

       });
    });
  });

For the code above we assume you want to check for all the fields where the attribute name starts with the string "PositionNumber"
I will try to reduce the code later, I think there's a shortest way to check if is duplicated the "RecordPosition" value, but need to test some ideas.
This will be your solution (one of them):
  $(document).ready(function(){

    $('form').on("submit",function(){
            var tempArray=[];
            $("input[type='text'][name^='PositionNumber'").each(function(){
                tempArray.push($(this).val());
            });

            var i=0;
            var duplicated=false;
            var currentElement;
            while((tempArray.length >= 0) && (duplicated==false)){
                //pop it out from the array
               currentElement = tempArray.pop();
               duplicated = tempArray.indexOf(currentElement)

            }

            //after you can use "duplicated" to cancel the submit
            if (duplicated){
                alert("duplicated value:" + currentElement);
                return false;
            }

    });
  });

I shorter version:
$(document).ready(function(){
 $('form').on("submit",function(){
         var tempArray=[];
        var exists=0;
         $("input[type='text'][name^='PositionNumber'").each(function(){
             exists = tempArray.indexOf($(this).val());
             if (exists>=0){
                 return false;//break the loop
             }
             tempArray.push($(this).val());
         });

         //after you can use "exist" to check if duplicated and retrieve the value to cancel the submit
         if (exists>=0){
             alert("duplicated value:" + tempArray[exists]);
         } else{
             alert("no duplicated value:");
         }

        return false;
 });
});


text:
Q: Groovy: java.lang.VerifyError: Expecting to find integer on stack when I want to migrate java geohash code to groovy platform, then it report
ERROR: Groovy: java.lang.VerifyError: (class: GeoHash, method:
recombineLatLonBitsToHash signature: (Ljava/lang/Object;[J)LGeoHash;)
Expecting to find integer on stack

this is the java geohash code:
protected GeoHash recombineLatLonBitsToHash(long[] latBits, long[] lonBits) {
    GeoHash hash = new GeoHash();
    boolean isEvenBit = false;
    latBits[0] <<= (MAX_BIT_PRECISION - latBits[1]);
    lonBits[0] <<= (MAX_BIT_PRECISION - lonBits[1]);
    double[] latitudeRange = [-90.0, 90.0];
    double[] longitudeRange = [-180.0, 180.0];

    for (int i = 0; i < latBits[1] + lonBits[1]; i++) {
        if (isEvenBit) {
            divideRangeDecode(hash, latitudeRange, (latBits[0] & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED);
            latBits[0] <<= 1;
        } else {
            divideRangeDecode(hash, longitudeRange, (lonBits[0] & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED);
            lonBits[0] <<= 1;
        }
        isEvenBit = !isEvenBit;
    }
    hash.bits <<= (MAX_BIT_PRECISION - hash.significantBits);
    setBoundingBox(hash, latitudeRange, longitudeRange);
    hash.point = hash.boundingBox.getCenterPoint();
    return hash;
}

public GeoHash getSouthernNeighbour() {
    long[] latitudeBits = getRightAlignedLatitudeBits();
    long[] longitudeBits = getRightAlignedLongitudeBits();
    latitudeBits[0] -= 1;
    latitudeBits[0] = maskLastNBits(latitudeBits[0], latitudeBits[1]);
    return recombineLatLonBitsToHash(latitudeBits, longitudeBits);
}

then I change the recombineLatLonBitsToHash parameters type long[] to def, it doesn't report error:
protected GeoHash recombineLatLonBitsToHash(def latBits, def lonBits) {
    GeoHash hash = new GeoHash();
    boolean isEvenBit = false;
    latBits[0] <<= (MAX_BIT_PRECISION - latBits[1]);
    lonBits[0] <<= (MAX_BIT_PRECISION - lonBits[1]);
    double[] latitudeRange = [-90.0, 90.0];
    double[] longitudeRange = [-180.0, 180.0];

    for (int i = 0; i < latBits[1] + lonBits[1]; i++) {
        if (isEvenBit) {
            divideRangeDecode(hash, latitudeRange, (latBits[0] & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED);
            latBits[0] <<= 1;
        } else {
            divideRangeDecode(hash, longitudeRange, (lonBits[0] & FIRST_BIT_FLAGGED) == FIRST_BIT_FLAGGED);
            lonBits[0] <<= 1;
        }
        isEvenBit = !isEvenBit;
    }
    hash.bits <<= (MAX_BIT_PRECISION - hash.significantBits);
    setBoundingBox(hash, latitudeRange, longitudeRange);
    hash.point = hash.boundingBox.getCenterPoint();
    return hash;
}

public GeoHash getSouthernNeighbour() {
    long[] latitudeBits = getRightAlignedLatitudeBits();
    long[] longitudeBits = getRightAlignedLongitudeBits();
    latitudeBits[0] -= 1;
    latitudeBits[0] = maskLastNBits(latitudeBits[0], latitudeBits[1]);
    return recombineLatLonBitsToHash(latitudeBits, longitudeBits);
}

I want to know why the error is reported and why I change the type to def then work. thx!


text:
Q: knit_expand fails when subsetting based on a character vector I'm essentially trying to modify this answer to programmatically produce chunks with plots for each level of a variable.
In my particular case, however, I'm passing along a character vector to be used for subsequent subsetting, which seems to be the source of the code failure.
# My report (test.Rmd)

```{r}
library(ggplot2)
library(knitr)
data(diamonds)
diamonds$cut <- factor(gsub(" ", "_", diamonds$cut)) # Get rid of spaces
cut.levels <- levels(diamonds$cut)
```

## Generate report for each level of diamond cut
```{r, include=FALSE}
src <- lapply(cut.levels, function(cut) knit_expand(file = "template.Rmd"))
```

`r knit(text = unlist(src))`

And the template (template.Rmd):
```{r, results='asis', echo = FALSE}
cat("### {{cut}} cut")
```

```{r {{cut}}-cut, eval = FALSE}
with(subset(diamonds, cut == "{{cut}}"),
     plot(carat, price, main = paste("{{cut}}", "cut"))
)

```

Running this with the second chunk in template.Rmd set to eval=FALSE produces the expected output - a series of headers for each chunk with the echoed code.  However, the substituted values from the cut.levels character string in the subset call have lost their quotes which, I expect, causes the following error when the eval=FALSE chunk option is removed:
Quitting from lines 6-8 (test.Rmd)
Quitting from lines 12-12 (test.Rmd)
Error in eval(expr, envir, enclos) : object 'Fair' not found
Calls: <Anonymous> ... with -> subset -> subset.data.frame -> eval -> eval

It's now looking for the object Fair rather than those records with cut == "Fair".
Thanks for your assistance!
> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

A: I see 2 problems.
First, as you pointed out, {{cut}} is expanded without quotes so you'll need to wrap the tag in quotes. Second, your closing paren for plot() is misplaced. It should run with the following edits:
### {{cut}} cut

```{r {{cut}}-cut}
with(subset(diamonds, cut == "{{cut}}"),
     plot(carat, price, main = paste("{{cut}}", "cut"))
)
```


text:
Q: How to generate a Random number for a calculated field in SharePoint? Is there a way to generate a random number for a calculated field, in a SharePoint list ?

A: I don't believe that there is a way to do this within the SharePoint UI.
I would create a SharePoint event for the field that would programatically assign the random number whenever the event is fired (i.e. list item updated, list item created, etc...)


text:
Q: How to alert users on new update to local database? I'd like to receive some advice from all of you.
What is the best way for me to alert users on an update to my app? My app is a very knowledge-based & it works like a dictionary, so there will always be updates to it.
The database I have used is by DB Browser for SQLite, and they are all local database where it is uploaded into the assets folder in Android Studio.
Currently, the limitations are that:
1) it's obviously not real-time because it's stored locally;
2) every update I make to the database structure, I am required to upload the new database into the assets folder again, followed by uninstalling the old app on my phone, then run the app to install in my phone again so that the new database is overwritten.
I have read (How can I regularly update a database of content on an Android app?) & some others, and it seemed like I have to have a server, a cloud-based database & live app in market, to solve the limitations?
Is there really no way for me to overcome the limitations if I want to stick to a local database? At the same time, I kinda wish to avoid setting up a server because I am not intending to make the app live on market, and also this is just a school project I am working on and as such, I have very limited skill sets & knowledge about it and would like to make it on a school-project-based level.
Thanks in advance.

A: One way to do it is to connect to your local DB through local network instead of assets folder. Therefore, you can update the information by querying the local DB.
As for syncing the information between DB and your application, you should create a trigger or watcher that notify your application when the DB is updated. Therefore, your application can know when to query the DB for the updates. Another way is to just query the database periodically.
Bonus: you could move your database to a cloud-based database. Usually there are several providers that provide free database hosting up to a certain size, which should be enough for your project.


text: Q: Using WebSphereUowTransactionManager in a stand alone application I want to use "WebSphereUowTransactionManager" of Spring  for transaction managemnt in a  simple stand alone java application . Is it possible ?


text:
Q: How to create a PolygonRDD from H3 boundary? I'm using Apache Spark with Apache Sedona (previously called GeoSpark), and I'm trying to do the following:

*

*Take a DataFrame containing latitude and longitude in each row (it comes from an arbitrary source, it neither is a PointRDD nor comes from a specific file format) and transform it into a DataFrame with the H3 index of each point.

*Take that DataFrame and create a PolygonRDD containing the H3 cell boundaries of each distinct H3 index.

This is what I have so far:
import org.apache.spark.serializer.KryoSerializer
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.sedona.core.spatialRDD.PolygonRDD
import org.apache.sedona.sql.utils.SedonaSQLRegistrator
import org.apache.sedona.viz.core.Serde.SedonaVizKryoRegistrator
import org.apache.sedona.viz.sql.utils.SedonaVizRegistrator
import org.locationtech.jts.geom.{Polygon, GeometryFactory, Coordinate}
import com.uber.h3core.H3Core
import com.uber.h3core.util.GeoCoord

object Main {
  def main(args: Array[String]) {
    val sparkSession: SparkSession = SparkSession
      .builder()
      .config("spark.serializer", classOf[KryoSerializer].getName)
      .config("spark.kryo.registrator", classOf[SedonaVizKryoRegistrator].getName)
      .master("local[*]")
      .appName("Sedona-Analysis")
      .getOrCreate()
    import sparkSession.implicits._

    SedonaSQLRegistrator.registerAll(sparkSession)
    SedonaVizRegistrator.registerAll(sparkSession)

    val df = Seq(
      (-8.01681, -34.92618),
      (-25.59306, -49.39895),
      (-7.17897, -34.86518),
      (-20.24521, -42.14273),
      (-20.24628, -42.14785),
      (-27.01641, -50.94109),
      (-19.72987, -47.94319)
    ).toDF("latitude", "longitude")

    val core: H3Core = H3Core.newInstance()
    val geoFactory = new GeometryFactory()
    val geoToH3 = udf((lat: Double, lng: Double, res: Int) => core.geoToH3(lat, lng, res))

    val trdd = df
      .select(geoToH3($"latitude", $"longitude", lit(7)).as("h3index"))
      .distinct()
      .rdd
      .map(row => {
        val h3 = row.getAs[Long](0)
        val lboundary = core.h3ToGeoBoundary(h3)
        val aboundary = lboundary.toArray(Array.ofDim[GeoCoord](lboundary.size))
        val poly = geoFactory.createPolygon(
          aboundary.map((c: GeoCoord) => new Coordinate(c.lat, c.lng))
        )
        poly.setUserData(h3)
        poly
      })
    val polyRDD = new PolygonRDD(trdd)
    polyRDD.rawSpatialRDD.foreach(println)

    sparkSession.stop()
  }
}

However, after running sbt assembly and submitting the output jar to spark-submit, I get this error:
Exception in thread "main" org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:416)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:406)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2362)
    at org.apache.spark.rdd.RDD.$anonfun$map$1(RDD.scala:396)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.RDD.map(RDD.scala:395)
    at Main$.main(Main.scala:44)
    at Main.main(Main.scala)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
    at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:928)
    at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
    at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
    at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1007)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1016)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.io.NotSerializableException: com.uber.h3core.H3Core
Serialization stack:
    - object not serializable (class: com.uber.h3core.H3Core, value: com.uber.h3core.H3Core@3407ded1)
    - element of array (index: 0)
    - array (class [Ljava.lang.Object;, size 2)
    - field (class: java.lang.invoke.SerializedLambda, name: capturedArgs, type: class [Ljava.lang.Object;)
    - object (class java.lang.invoke.SerializedLambda, SerializedLambda[capturingClass=class Main$, functionalInterfaceMethod=scala/Function1.apply:(Ljava/lang/Object;)Ljava/lang/Object;, implementation=invokeStatic Main$.$anonfun$main$2:(Lcom/uber/h3core/H3Core;Lorg/locationtech/jts/geom/GeometryFactory;Lorg/apache/spark/sql/Row;)Lorg/locationtech/jts/geom/Polygon;, instantiatedMethodType=(Lorg/apache/spark/sql/Row;)Lorg/locationtech/jts/geom/Polygon;, numCaptured=2])
    - writeReplace data (class: java.lang.invoke.SerializedLambda)
    - object (class Main$$$Lambda$1710/0x0000000840d7f040, Main$$$Lambda$1710/0x0000000840d7f040@4853f592)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:41)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:47)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:101)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:413)
    ... 22 more

What is the proper way to achieve what I'm trying to do?

A: So, basically just adding the Serializable trait to an object containing the H3Core was enough. Also, I had to adjust the Coordinate array to begin and end with the same point.
import org.apache.spark.serializer.KryoSerializer
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.sedona.core.spatialRDD.PolygonRDD
import org.apache.sedona.sql.utils.SedonaSQLRegistrator
import org.apache.sedona.viz.core.Serde.SedonaVizKryoRegistrator
import org.apache.sedona.viz.sql.utils.SedonaVizRegistrator
import org.locationtech.jts.geom.{Polygon, GeometryFactory, Coordinate}
import com.uber.h3core.H3Core
import com.uber.h3core.util.GeoCoord

object H3 extends Serializable {
  val core = H3Core.newInstance()
  val geoFactory = new GeometryFactory()
}

object Main {
  def main(args: Array[String]) {
    val sparkSession: SparkSession = SparkSession
      .builder()
      .config("spark.serializer", classOf[KryoSerializer].getName)
      .config("spark.kryo.registrator", classOf[SedonaVizKryoRegistrator].getName)
      .master("local[*]")
      .appName("Sedona-Analysis")
      .getOrCreate()
    import sparkSession.implicits._

    SedonaSQLRegistrator.registerAll(sparkSession)
    SedonaVizRegistrator.registerAll(sparkSession)

    val df = Seq(
      (-8.01681, -34.92618),
      (-25.59306, -49.39895),
      (-7.17897, -34.86518),
      (-20.24521, -42.14273),
      (-20.24628, -42.14785),
      (-27.01641, -50.94109),
      (-19.72987, -47.94319)
    ).toDF("latitude", "longitude")

    val geoToH3 = udf((lat: Double, lng: Double, res: Int) => H3.core.geoToH3(lat, lng, res))

    val trdd = df
      .select(geoToH3($"latitude", $"longitude", lit(7)).as("h3index"))
      .distinct()
      .rdd
      .map(row => {
        val h3 = row.getAs[Long](0)
        val lboundary = H3.core.h3ToGeoBoundary(h3)
        val aboundary = lboundary.toArray(Array.ofDim[GeoCoord](lboundary.size))
        val poly = H3.geoFactory.createPolygon({
          val ps = aboundary.map((c: GeoCoord) => new Coordinate(c.lat, c.lng))
          ps :+ ps(0)
        })
        poly.setUserData(h3)
        poly
      })

    val polyRDD = new PolygonRDD(trdd)
    polyRDD.rawSpatialRDD.foreach(println)

    sparkSession.stop()
  }
}


text:
Q: How prove that $(a_{n})_{n \in \mathbb{N}}$ is convergent with $a_{0}=1$, $a_{n+1}= \sqrt{2a_{n}}$?
Prove that $(a_{n})_{n \in \mathbb{N}}$ is convergent with $a_{0}=1$,
  $a_{n+1}= \sqrt{2a_{n}}$ and calculate its limit.
You got the info that the square-root-function is strictly monotonic
  increasing and also continuous.

I'm very confused how this could be solved because there isn't really a sequence given here. It seems to be a recursive one and I also don't know how to form $a_{n+1}$.
Could I form it to $a_{n}+ a_{1}$ ?(I don't care if it's useful here but I'd like to know if this would be correct at first.)

I have started by forming to $a_{n}$:
$$2a_{n} = (a_{n+1})^{2}$$
$$a_{n}=\frac{(a_{n+1})^{2}}{2}$$
Then I also formed to $a_{1}:$
$$a_{n}+ a_{1} = \sqrt{2a_{n}}$$
$$a_{1} = \sqrt{2a_{n}} - a_{n}$$
But it seems like this won't lead to anything.. Also I don't know what we can do with the given info, $a_{0} = 1$, the continuity and monotonic increasing...

A: The most basic, but still readable proof (in my opinion) is by using the following theorem:

A monotonically increasing, bounded sequence of real numbers is convergent.

So we need to prove that $a_n$ is increasing and bounded. Specifically, I will prove that $1\leq a_n \leq a_{n+1} \leq 2$ for all $n$ using induction.
Base case: The inequality clearly holds for $n = 0$, since $1 \leq 1 \leq \sqrt 2 \leq 2$.
Induction step: Assume the inequality holds for $n = k$, i.e. that $1\leq a_k \leq a_{k+1}\leq 2$. We want to show
$$
1 \leq a_{k+1} \leq a_{k+2} \leq 2
$$
The first inequality follows from the induction hypothesis and transitivity of $\leq$ (we assumed $1 \leq a_k$ and $a_k \leq a_{k+1}$). For the second inequality, we have
$$
a_{k+1} = \sqrt{a_{k+1}\cdot a_{k+1}} \leq \sqrt{2a_{k+1}} = a_{k+2}
$$
where we used $ a_{k+1}\leq 2$, as well as the monotonically increasing nature of the square root.
For the last inequality, we have
$$
a_{k+2} = \sqrt{2\cdot a_{k+1}} \leq  \sqrt{2\cdot 2} = 2
$$
which concludes the proof that $1 \leq a_{k+1} \leq a_{k+2} \leq 2$.

A: By induction $$a_{n+1}=\sqrt{2a_n}=\sqrt{2\cdot\sqrt{2a_{n-1}} }=2^{1/2}2^{1/4}a_{n-1}^{1/4}=...=a_0\prod_{i=1}^{n+1}2^{\frac{1}{2^{i}}}.$$
As robjohn suggest, define $b_{n+1}=\log(a_{n+1})$ and conclude.

A: Note that
$$
\frac{a_n}{a_{n-1}}=\left(\frac{a_{n-1}}{a_{n-2}}\right)^{1/2}\tag{1}
$$
Therefore, by induction
$$
\frac{a_n}{a_{n-1}}=\left(\frac{a_1}{a_0}\right)^{1/2^{n-1}}\tag{2}
$$
Since
$$
\begin{align}
a_n
&=a_0\prod_{k=1}^n\frac{a_k}{a_{k-1}}\\
&=\prod_{k=1}^n2^{1/2^k}\\
&=2^{\sum\limits_{k=1}^n1/2^k}\tag{3}
\end{align}
$$
Since $\sum\limits_{k=1}^n1/2^k$ converges, the sequence converges. Since $\sum\limits_{k=1}^\infty1/2^k=1$, this also tells to what the sequence converges.

A: With $a_0=1$, $a_{n+1}= \sqrt{2a_{n}}$, so show $(a_n)$ is monotone and bounded.

First show $(a_n)$ is bounded.
Let $P(n)$ be the statement $1\leq a_n\leq 2$.
Base Case
We have $a_0=1$, and $1\leq 1\leq 2$.
Inductive Step
Let $P(k)$ be true: $1\leq a_{k}\leq 2$. Now check validity of $P(k+1)$ from assumed truth of $P(k)$. Since
$$\sqrt{2\cdot1}\leq a_{k+1}= \sqrt{2a_{k}}\leq \sqrt{2\cdot 2}=2$$
we have $1\leq a_{k+1}\leq 2$ as required, and so $(a_n)$ is bounded.

Now show $(a_n)$ is monotone.
Base Case
We have $a_1=\sqrt{2a_0}=\sqrt{2}\geq a_0=1$. Now $a_2=\sqrt{2a_1}=\sqrt{2\sqrt{2}}$ and so $a_2>a_1$.
Inductive Step
Let $P(k)$ be true: $a_{k}\geq a_{k-1}$. Now check validity of $P(k+1)$ from assumed truth of $P(k)$. Since
$$a_k=\sqrt{2a_{k-1}},\quad\text{and}\quad a_{k+1}=\sqrt{2a_k}$$
then, since the square-root-function is strictly monotonic increasing
$$a_{k+1}=\sqrt{2a_k}\geq a_k=\sqrt{2a_{k-1}}$$
since we assumed $a_{k}\geq a_{k-1}$.

Hence the sequence is monotone increasing, bounded above by $2$, and so must converge to some limit $L$, say. Then
$$\sqrt{2a_{n}}\to \sqrt{2L}, \qquad\text{as $n\to\infty$}$$
But the sequences $(a_{n})$ and $(a_{n+1})$ converge to the same limit, $$\lim_{n\to\infty}(a_{n+1})=\lim_{n\to\infty}(\sqrt{2a_{n}})$$
from which:
$$L=\sqrt{2L}$$
and so $L=2$.

A: Hint:
Always start by evaluating a few terms.
$$a_0=1=2^0,a_1=\sqrt2=2^{1/2},a_2=\sqrt{2\sqrt2}=2^{1/2+1/4},a_3=\sqrt{2\sqrt{2\sqrt2}}=2^{1/2+1/4+1/8},\cdots$$
As you can show by induction (or by the geometric series formula),
$$a_n=2^{1-1/2^n}=\frac2{\sqrt{\sqrt{\cdots\sqrt2}}}.$$


text:
Q: How to pass HTML attributes to child component in React? I have a parent and a child component, child component has a button, which I'd like to disable it after the first click. This answer works for me in child component. However the function executed on click now exists in parent component, how could I pass the attribute down to the child component? I tried the following and it didn't work.
Parent:

const Home = () => {
  let btnRef = useRef();
  const handleBtnClick = () => {
    if (btnRef.current) {
        btnRef.current.setAttribute("disabled", "disabled");
    }
  }

  return (
    <>
      <Card btnRef={btnRef} handleBtnClick={handleBtnClick} />
    </>
  )
}

Child:

const Card = ({btnRef, handleBtnClick}) => {
  return (

      <button ref={btnRef} onClick={handleBtnClick}>Click me</button>

  )
}

A: In general, refs should be used only as a last resort in React. React is declarative by nature, so instead of the parent "making" the child disabled (which is what you are doing with the ref) it should just "say" that the child should be disabled (example below):
const Home = () => {
  const [isButtonDisabled, setIsButtonDisabled] = useState(false)
  const handleButtonClick = () => {
    setIsButtonDisabled(true)
  }

  return (
    <>
      <Card isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />
    </>
  )
}

const Card = ({isDisabled, onButtonClick}) => {
  return (

      <button disabled={isDisabled} onClick={onButtonClick}>Click me</button>

  )
}

A: Actually it works if you fix the typo in prop of Card component. Just rename hadnlBtnClick to handleBtnClick

A: You don't need to mention each prop/attribute by name as you can use javascript Object Destructuring here.
const Home = () => {
  const [isButtonDisabled, setIsButtonDisabled] = useState(false)
  const handleButtonClick = () => {
    setIsButtonDisabled(true)
  }

  return (
    <>
      <Card isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />
    </>
  )
}

const Card = (props) => {
  return (

      <button {...props}>Click me</button>

  )
}

You can also select a few props and use them differently in the child components. for example, see the text prop below.
const Home = () => {
  const [isButtonDisabled, setIsButtonDisabled] = useState(false)
  const handleButtonClick = () => {
    setIsButtonDisabled(true)
  }

  return (
    <>
      <Card text="I'm a Card" isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />
    </>
  )
}

const Card = ({text, ...restProps}) => {
  return (

      <button {...restProps}>{text}</button>

  )
}


text:
Q: Who can explain this Haskell function? The Haskell function
foo = zipWith ($) . repeat

does exactly the same as
map

but I cannot see why :-(
Who can give an explanation?
Thx a lot!

A: OK, so we have
foo = zipWith ($) . repeat

which is the same as
foo f = zipWith ($) (repeat f)

The repeat f generates an infinite list of copies of f. Then zipWith uses the ($) operator to apply each element of the [infinite copies of f] list to each element of the incoming list. Which is what map does.
Yes?


text:
Q: Filling Word forms using Access isn't always working I'm using a code i found online to fill in form fields in a Word document. When i use it on an empty document and add to it a form field, it works. However, when i use it on the form i'm trying to fill nothing happens when i execute the code. I checked the name of the fields in Word and they match the code, i don't know what's wrong.
  I also checked the data type in Access and it's not the problem, i don't have access to the code right now but does anyone have any idea of what's causing this?
  Edit: Here is a similar code, i don't have access to the exact same one:
Dim appWord As Word.Application
Dim doc As Word.Document
'Avoid error 429, when Word isn't open.
Err.Clear
'Set appWord object variable to running instance of Word.
Set appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
Set appWord = New Word.Application
End If
Set doc = appWord.Documents.Open("C:\Users\" & Environ$("Username") & "\Desktop\Form.doc", , True)
With doc

.FormFields("TextEn").Result = DLookup("[End date]", "[Table1]", "[Table1]![ID Number] =" & [ID2])
.FormFields("TextSt").Result = DLookup("[Starting date]", "[Table1]", "[Table1]![ID Number] =" & [ID2])

.Visible = True
.Activate
End With
Set doc = Nothing
Set appWord = Nothing
Exit Sub
errHandler:
MsgBox Err.Number & ": " & Err.Description

A: You could try to validate that your dlookup is returning a value with the following:
If DCount("[End date]", "[Table1]", "[Table1]![ID Number] =" & [ID2]) > 0 then
  .FormFields("TextEn").Result = DLookup("[End date]", "[Table1]", "[Table1]![ID Number] =" & [ID2])
End If

You would have to do this for each lookup before trying to set your fields.


text:
Q: Refactoring ugly ruby code The code below gets some text, find commas, and returns an array of a split up version without the commas.
class A
  def separate_comma_values(text)
    txt_len = text.length
    if txt_len == 0
      return [""]
    end
    final = []
    sub_arry = ""

    for i in (0...txt_len)
      ch = text[i]
      if ch == ","
        final << sub_arry
        final << ""
        sub = ""
      else
        sub_arry += ch
      end
    end
    return final
  end
end

This is a sample input and output:
s = A.new
print s.separate_comma_values("dh,,,dhhd,jhb")
# => ["dh", "", "dh", "", "dh", "", "dhdhhd", ""]

Although it does what I want it to do, I feel that there is something just not right about it. It's just dirty.
I am aware that I can use a built in method provided by ruby to achieve the split.
Edit: I guess this was edit out of my original post. The motivation behind this was to apply the knowledge I found after reading a ruby book.

A: There's a method in Ruby that does what you want.
http://ruby-doc.org/core-2.0/String.html#method-i-split
2.0.0p0 :001 > "dh,,,dhhd,jhb".split(',')
 => ["dh", "", "", "dhhd", "jhb"]

So, your code might end up being as simple as
def separate_comma_values(text)
  text.split(',')
end

Update: Sorry, I missed the part where you mention you already know about split. Oops.

A: This is a little cleaner, although as @depa points out, if you're trying to split based on commas, there's an easier way, and your (and thus this) code doesn't work right.
class A
  def separate_comma_values(text)
    return [""] if text.empty?

    final = []
    sub_arry = ""

    text.each_char do |ch|
      if ch == ","
        final << sub_arry
        final << ""
      else
        sub_arry += ch
      end
    end

    return final
  end
end

s = A.new
print s.separate_comma_values("dh,,,dhhd,jhb")
puts

This outputs
["dh", "", "dh", "", "dh", "", "dhdhhd", ""]

just as your does.
Here's how I would implement your algorithm:
class A
  def separate_comma_values(text)
    return [""] if text.empty?

    array = []
    value = ""

    text.each_char do |c|
      if c == ","
        array << value
        value = ""
      else
        value += c
      end
    end

    array << value if !value.empty?

    array
  end
end

s = A.new
print s.separate_comma_values("dh,,,dhhd,jhb")
puts

This outputs
["dh", "", "", "dhhd", "jhb"]

A: Just as a small trick for looking nicer (in my opinion), you should be able to skip the word 'return' at the end of the method, and your 'seperate_comma_values(text)' could be just 'seperate_comma_values text' without the parens (in your text editor, syntax color highlighting makes this not a problem of clarity at all)

A: The only proper way to refactor your code is, obviously, to use String#split.
Although, just for fun:
def separate_comma_values(text)
  text.each_char.reduce(['']) do |splitted, char|
    if char == ','
      splitted << ''
    else
      splitted.last << char
    end
    next splitted
  end
end


text:
Q: getting form undefiend in angularjs I am creating web app using angularjs. I have integrate the dirPaginate directive for pagination.I am paginate the forms, Pagination works fine.When I submit the form first time.Form submit Succesfully. When I click on next number on pagiantion list and submit form again it says form is undefiend.
Here is Form:
var form = amazon.form; // first time works, after paginate gives undefiend
        $rootScope.amazonForm = form;

        // Show error messages and exit.
        if (form.$invalid) {
            if (form.$pristine) {
                form.$setDirty();
            }
         }

A: You can watch the form and can save the form to $scope
$scope.$watch('amazon.form', function(amazonForm) {
     if(amazonForm) {
      $scope.amazonForm = amazonForm;
     }
 });

then can use below code in your function
$scope.amazon.form = $scope.amazonForm;

var form = $scope.amazon.form;


text:
Q: Rstudio won't open browser to authorize rtwewt I just bought a new laptop. Installed R, Rstudio. I tried to use rtweet without creating a twitter app--which i have done tens of times in my old laptop.
Installed rtweet, installed httpuv, then when i ran my command:
tw<-get_timeline ("user)
Instead of the usual process of opening a browser and giving authorization, I get this error message
Error in `default_cached_auth()`:
! No default authentication found. Please call `auth_setup_default()`

and when I run auth_setup_default()'
it gives me this error message:
Error in httr::init_oauth1.0(endpoint, app, permission = permission, is_interactive = is_interactive,  :  Not Found (HTTP 404).


text:
Q: Неверная кодировка при развертывании проекта на хостинг Здравствуйте!
Подскажите, пожалуйста, в чем может быть проблема. Я написал приложение на Java с использованием MySQL без фреймворков. На каждой jsp странице указываю кодировку utf-8 и для servlet'ов также, для response и request тоже. На моем компьютере все работает правильно, если я заполняю какую-либо форму на русском, все нормально и в базе данные также отображаются на русском, но стоит только задиплоить проект на хостинге - вместо русского получаются иероглифы. Версия tomcat & MySQL на хостинге та же, что и у меня.
В чем проблема? Также да, при подключении к базе в url указываю use names 'utf8'.
A: Может быть проблема в том, что на сервере прописана кодировка по умолчанию windows-1251
Надо явно указать серверу Вашу кодировку. В яве я ноль, но думаю тут без разницы - в .htaccess дописывается кодировка

AddDefaultCharset UTF-8

и все работает, пробуйте.
A: Здравствуйте Ozim.
Можно, конечно, в начале каждого файла jsp прописать следующий программный код, с нужной Вам кодировкой:
<%request.setCharacterEncoding("windows-1251");%>
По крайней мере у меня так работает.
С уважением, Евгений.


text:
Q: Spark Shell unable to find the Hbase Class I am trying to load data from HDFS to a Hbase table using Spark Streaming.
    I am placing data in a HDFS directory run time and reading it using the textFileStream function.
    Since  spark doesnt have the hbase jars in the classpath, it gives me an error even while doing the import of the Hbase jars in the spark shell.
scala> import org.apache.hadoop.hbase.mapred.TableOutputFormat
<console>:10: error: object hbase is not a member of package org.apache.hadoop
       import org.apache.hadoop.hbase.mapred.TableOutputFormat

But if i add the hbase jars in the classpath while starting the spark shell then i am not getting any error. But it is still not able to find certain classes down the path.

bin/spark-shell --jars /hbase/hbase-0.94.13/hbase-0.94.13-mapr-1401.jar

scala> import org.apache.hadoop.hbase.{ HBaseConfiguration, HColumnDescriptor, HTableDescriptor }
import org.apache.hadoop.hbase.{HBaseConfiguration, HColumnDescriptor, HTableDescriptor}

scala> import org.apache.hadoop.hbase.client.{ HBaseAdmin, Put }
import org.apache.hadoop.hbase.client.{HBaseAdmin, Put}

scala> import org.apache.hadoop.hbase.io.ImmutableBytesWritable
import org.apache.hadoop.hbase.io.ImmutableBytesWritable

scala> import org.apache.hadoop.hbase.mapred.TableOutputFormat
import org.apache.hadoop.hbase.mapred.TableOutputFormat

scala> import org.apache.hadoop.hbase.mapreduce.TableInputFormat
import org.apache.hadoop.hbase.mapreduce.TableInputFormat

scala> import org.apache.hadoop.hbase.util.Bytes
import org.apache.hadoop.hbase.util.Bytes

scala> import org.apache.hadoop.mapred.JobConf
import org.apache.hadoop.mapred.JobConf

scala> import org.apache.spark.SparkContext
import org.apache.spark.SparkContext

scala> import org.apache.spark.rdd.{ PairRDDFunctions, RDD }
import org.apache.spark.rdd.{PairRDDFunctions, RDD}

scala> import org.apache.spark.streaming._
import org.apache.spark.streaming._

scala> import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.streaming.StreamingContext._

scala> import org.apache.hadoop.hbase.client.mapr.{BaseTableMappingRules}
import org.apache.hadoop.hbase.client.mapr.BaseTableMappingRules

scala> val conf = HBaseConfiguration.create()
conf: org.apache.hadoop.conf.Configuration = Configuration: core-default.xml, core-site.xml, mapred-default.xml, mapred-site.xml, hbase-default.xml, hbase-site.xml

scala> val hbaseTableName = "/app/dev/MarketingIt/hbasetables/spark_test"
hbaseTableName: String = /app/dev/MarketingIt/hbasetables/spark_test

scala> val admin = new HBaseAdmin(conf)
java.lang.RuntimeException: java.io.IOException: java.lang.RuntimeException: Error occurred while instantiating com.mapr.fs.MapRTableMappingRules.
==> org/apache/hadoop/hbase/client/mapr/BaseTableMappingRules.
        at org.apache.hadoop.hbase.client.HBaseAdmin.commonInit(HBaseAdmin.java:356)
        at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:156)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:31)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:36)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:38)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:40)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:42)
        at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:44)
        at $iwC$$iwC$$iwC$$iwC.<init>(<console>:46)
        at $iwC$$iwC$$iwC.<init>(<console>:48)
        at $iwC$$iwC.<init>(<console>:50)
        at $iwC.<init>(<console>:52)
        at <init>(<console>:54)
        at .<init>(<console>:58)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:788)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1056)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:614)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:645)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:609)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:796)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:841)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:753)
        at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:601)
        at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:608)
        at org.apache.spark.repl.SparkILoop.loop(SparkILoop.scala:611)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply$mcZ$sp(SparkILoop.scala:936)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:884)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:884)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:884)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:982)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:303)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:55)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.io.IOException: java.lang.RuntimeException: Error occurred while instantiating com.mapr.fs.MapRTableMappingRules.
==> org/apache/hadoop/hbase/client/mapr/BaseTableMappingRules.
        at org.apache.hadoop.hbase.client.mapr.TableMappingRulesFactory.create(TableMappingRulesFactory.java:65)
        at org.apache.hadoop.hbase.client.HBaseAdmin.commonInit(HBaseAdmin.java:348)
        ... 47 more
Caused by: java.lang.RuntimeException: Error occurred while instantiating com.mapr.fs.MapRTableMappingRules.
==> org/apache/hadoop/hbase/client/mapr/BaseTableMappingRules.
        at org.apache.hadoop.hbase.client.mapr.GenericHFactory.getImplementorInstance(GenericHFactory.java:40)
        at org.apache.hadoop.hbase.client.mapr.TableMappingRulesFactory.create(TableMappingRulesFactory.java:47)
        ... 48 more
Caused by: java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/client/mapr/BaseTableMappingRules
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:412)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:190)
        at org.apache.hadoop.hbase.client.mapr.GenericHFactory.getImplementorInstance(GenericHFactory.java:30)
        ... 49 more
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.client.mapr.BaseTableMappingRules
        at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        ... 65 more

Here  as you can see i have added all the hbase jars and spark is able to find some of the hbase classes and cant find some
All the classes are in the same jar i added. Since it is saying Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.client.mapr.BaseTableMappingRules. I have imported that class specifically. But i still get the same error.

A: If you are using Spark 1.+, try setting extra Class Path property in Spark configuration
Add this line to spark-defaults.conf  --

spark.executor.extraClassPath
  /opt/cloudera/parcels/CDH/lib/hive/lib/hive-hbase-handler.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar:/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar

If you are using another distribution, lookup appropriate path for the jar files.
In addition to the configuration change, add driver class path to spark shell or while submitting your spark job as --

--driver-class-path
  /opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar:/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar

You can add the jar files to spark class path in spark-env.sh to avoid specifying the full path every time you want to start spark-shell or submit a spark job, but I run into other issues while using this approach. I have found the options above to work better for me.

export
  SPARK_CLASSPATH=/opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar:/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar

Nothing more is needed for Spark 1.+
If you are using Spark 0.9, please see this link -- yes, links can break but I have not tested on Spark 0.9 and this blog has useful information
http://www.abcn.net/2014/07/lighting-spark-with-hbase-full-edition.html

A: Add line in conf/spark-env.sh
Replace ${HBASE_HOME} with  Full path
export SPARK_CLASSPATH=${HBASE_HOME}/lib/*


text:
Q: Make Visual Studio debugger auto refresh an Angular 6 application like ng serve I've got a Visual Studio solution containing a .NET Web API project as well as an Angular 6 project. I'd like to be able to run the Visual Studio debugger on the Angular app and have it auto refresh on changes to the Angular code just like ng serve would do. Is there a way to do this, or similar, in Visual Studio Professional 2015 or Visual Studio Enterprise 2017?

A: Check this one out. I think I know what you talking about. It can reload the page after you make changes.
https://marketplace.visualstudio.com/items?itemName=MadsKristensen.BrowserReloadonSave


text:
Q: Java - pattern for textfield I want user to type some text in JTextField and it must match some "pattern".
Pattern is - int x, String("hours"), so f.e. 5 hours ; 12 hours etc.
I googled something with patterns, matchers, regex or whatever, and I am pretty confused.
If someone ever experienced similar problem, or knows how to handle mine, please post.
Or at least some API to read ...

A: JFormattedTextField should do.


text:
Q: mysql join query with many fields I have following tables in mysql.
focus
focus_id focus
1        Company
2        Name

events_focus
id  event_id    focus_id
1   1           2
2   1           1
3   2           1

events
event_id name
1        event
2        evemt2

story
story_id name
2        storyname
3        testname

events_story
id event_id story_id
2           2

and this is my query
SELECT `focus`.`focus_id`, `focus`.`focus`, `events`.`event_id`, `events`.`name`, `story`.`story_id`, `story`.`name`
FROM (`focus`)
JOIN `events_focus` ON `events_focus`.`focus_id` = `focus`.`focus_id`
JOIN `events` ON `events`.`event_id` = `events_focus`.`event_id`
JOIN `events_story` ON `events_story`.`event_id` = `events`.`event_id`
JOIN `story` ON `story`.`story_id` = `events_story`.`story_id`
WHERE `focus`.`focus` = 'Company'

but I am getting zero result for this.
can anyone help me how to get all this data related to the tables I have shown.

A: event_id blank in the single row present in events_story
so the following join does not work,
JOIN `events_story` ON `events_story`.`event_id` = `events`.`event_id`

If this data is expected/valid, you might want to change the join from JOIN to LEFT OUTER JOIN.

A: Use LEFT JOIN instead of JOIN. You'll find out which table returns NULL values, i.e. will provoke 0 results when using just JOIN


text:
Q: Calculate difference between values with nearly identical timestamp Please consider these input data:

*

*I have two instruments (41 and 54).

*They both measure the pressure of several tanks (T1 and T2).

*They measure the pressure nearly at the same time, but not exactly.

Example data:
data  <- data.table(
   time = as.POSIXct(paste("2017-01-01", c("11:59", "12:05", "12:02", "12:03", "14:00", "14:01", "14:02", "14:06")), tz = "GMT"),
   instrumentId = c(41, 54, 41, 54, 41, 54, 41, 54),
   tank = c("T1", "T1", "T2", "T2", "T1", "T1", "T2", "T2"),
   pressure = c(25, 24, 35, 37.5, 22, 22.2, 38, 39.4))

I want to calculate the difference between the pressure measured by instrument 41 and by instrument 54, for each tank, assuming that values measured within 20 minutes belong to the same sample.
Ideall, the timestamp of the difference will be the mean of the timestamp of the two compared values.
Here is a script is use so far:
## Calculate difference of time between 2 consecutive lines
data <- data[, timeDiff := difftime(time, shift(time, type = "lag", fill = -Inf), tz = "GMT", units = "mins"),
                     by = tank]

# Assign the same timestamp to all the measures of a same sample
referenceTimes <- data[timeDiff > 20, .(time)]
data <- data[timeDiff < 20, time := referenceTimes]

# Calculate the difference between the values measured by both instruments
wideDt <- dcast.data.table(data,time + tank ~ instrumentId, value.var = c( "pressure"))
instruments <- as.character(unique(data$instrumentId))
wideDt <- wideDt[, difference := get(instruments[1]) - get(instruments[2])]

It does the job, but its biggest problem is that the data should be sorted the proper way, otherwise time shift calculation returns nonsense.
With the example input data it is OK, but try to "unsort" them with data <- data[order(pressure)] for example. In that case, data <- data[order(tank, time, instrumentId)] should be added.
Moreover, I have the impression that it could be more concise, more efficient, and cleaner. In a word, it could better use data.table's strength.
Expected result is:
time                 tank  41   54    difference
-------------------------------------------------
2017-01-01 11:59:00  T1    25   24.0   1.0
2017-01-01 12:02:00  T2    35   37.5  -2.5
2017-01-01 14:00:00  T1    22   22.2  -0.2
2017-01-01 14:02:00  T2    38   39.4  -1.4

Any idea how to perform this task properly?

A: You can easily perform a rolling self-join on two subsets on both tank and time which won't require any initial reordering while specifying the maximum rolling interval (20 mins = 20 * 60 secs)
res <-
 data[instrumentId == 54, .SD[data[instrumentId == 41], on = .(tank, time), roll = -20*60]]
res
#                   time instrumentId tank pressure i.instrumentId i.pressure
# 1: 2017-01-01 11:59:00           54   T1     24.0             41         25
# 2: 2017-01-01 12:02:00           54   T2     37.5             41         35
# 3: 2017-01-01 14:00:00           54   T1     22.2             41         22
# 4: 2017-01-01 14:02:00           54   T2     39.4             41         38

Then, calculating the difference is just a matter of res[, difference := pressure - i.pressure]
But if you want your exact desired format, I'm afraid it will require some melting/dcasting
res2 <-
  dcast(
    melt(res, c("time", "tank"),
         measure = patterns("instrumentId", "pressure")),
    time + tank ~ value1, value.var = "value2"
        )[, difference := `41` - `54`]

res2
#                   time tank 41   54 difference
# 1: 2017-01-01 11:59:00   T1 25 24.0        1.0
# 2: 2017-01-01 12:02:00   T2 35 37.5       -2.5
# 3: 2017-01-01 14:00:00   T1 22 22.2       -0.2
# 4: 2017-01-01 14:02:00   T2 38 39.4       -1.4


text:
Q: Spark Scala UDF Parameters limitation of 10 I need to create a Spark UDF of having 11 arguments . Is there any way to achive it ?
I know we can create an UDF having upto 10 arguments
Below is the code for 10 arguments . It works
val testFunc1 = (one: String, two: String, three: String, four: String,
                 five: String, six: String, seven: String, eight: String, nine: String, ten: String) => {
    if (isEmpty(four)) false
    else four match {
        case "RDIS" => three == "ST"
        case "TTSC" => nine == "UT" && eight == "RR"
        case _ => false
    }
}
import org.apache.spark.sql.functions.udf
udf(testFunc1)

Below is the code for 11 arguments . Facing "unspecified value parameters:dataType" Issue
val testFunc2 = (one: String, two: String, three: String, four: String,
                 five: String, six: String, seven: String, eight: String, nine: String, ten: String, ELEVEN: String) => {
  if (isEmpty(four)) false
  else four match {
    case "RDIS" => three == "ST"
    case "TTSC" => nine == "UT" && eight == "RR" && ELEVEN == "OR"
    case _ => false
  }
}
import org.apache.spark.sql.functions.udf
udf(testFunc2) // compilation error

A: I would suggest to pack the parameters in a Map:
import org.apache.spark.sql.functions._

val df = sc.parallelize(Seq(("a","b"),("c","d"),("e","f"))).toDF("one","two")

val myUDF = udf((input:Map[String,String]) => {
  // do something with the input
  input("one")=="a"
})

df
  .withColumn("udf_args",map(
    lit("one"),$"one",
    lit("two"),$"one"
  )
 )
 .withColumn("udf_result", myUDF($"udf_args"))
 .show()

+---+---+--------------------+----------+
|one|two|            udf_args|udf_result|
+---+---+--------------------+----------+
|  a|  b|Map(one -> a, two...|      true|
|  c|  d|Map(one -> c, two...|     false|
|  e|  f|Map(one -> e, two...|     false|
+---+---+--------------------+----------+

A: You can create a new column which is an array of the columns:
df.withColumns("arrCol", array("col1", "col2", "col3", ...)

Now you can do a UDF of an array
val testFunc(vals: Seq[String]): String = ...


text:
Q: Wpf RichTextBox change key to line break; I can use Enter key to start a new line but can I use Ctrl+Enter instead?
I want to use Enter key to do other thing.
The KeyDown event I tried not work.
it is always start a new line when I press Enter.

A: You can set the value for property AcceptsReturn to false and handle the ctrl + enter key by creating an event handler for PreviewKeyDown event like this:
(rtb is name of the RichTextBox)
private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter && Keyboard.IsKeyDown(Key.LeftCtrl))
    {
        // do whatever you want
        // if u want to add a new line just uncomment the next lines
        // rtb.AppendText(Environment.NewLine);
        // rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
        e.Handled = true;
    }
}

A: i feel like for this requirement you should use only enter key it will work according to me
 private void richTextBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode==Keys.Enter  )
            {
                  //Enter key is down
                //Capture the text in next line  if you press enter only this event will
            }
            }


text:
Q: file_get_contents on other port I must contact services rest on different ports by 80, but the function file_get_contents () returns an error: failed to open stream: Connection refused
$url = "http://nexusdigital.agency:81/API/....";

$result = file_get_contents($url, false);

How can I configure the reading on other ports?

A: Use CURL :
<?php
$curl = curl_init('http://nexusdigital.agency/API/....');
curl_setopt($curl, CURLOPT_PORT, 81);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 81);
$result = curl_exec($curl);
?>

A: Well, if it doesn't work for you (whatever the reason) you can try using CURL http://php.net/curl
<?php
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "http://nexusdigital.agency/API/....");
curl_setopt($tuCurl, CURLOPT_PORT , 81);
curl_setopt($tuCurl, CURLOPT_VERBOSE, 0);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_CONNECTTIMEOUT, 5); // 5 seconds timeout

$tuData = curl_exec($tuCurl);
curl_close($tuCurl);


text:
Q: Linq wild card search mvc c# i am trying to implement wild card search using linq in mvc application. but its not working.  please see my code, what i am missing here, everytime i click the search button it returns the same number of rows. means search is not working. please help
IEnumerable<ProductList> listProducts = null;
listProducts = IProductRep.GetAllProducts();

if (listProducts != null)
{
    if ((!String.IsNullOrEmpty(strName)) || (!String.IsNullOrEmpty(strCategory))|| (!String.IsNullOrEmpty(strBrand)))
    {
        listProducts = listProducts.Where(s => s.pro_name.StartsWith(strName, StringComparison.OrdinalIgnoreCase)
                        || s.CategoryName.StartsWith(strCategory,StringComparison.OrdinalIgnoreCase)
                        || s.BrandName.StartsWith(strBrand, StringComparison.OrdinalIgnoreCase)  );
    }
    ViewBag.totalRecords = listProducts.Count();
}

A: Your problem seems to be that not all of strName, strCategory, strBrand has a value.
I assume that the vars that you did not assign are empty strings since if they were nulls you would get ArgumentNullException on:
s.field.StartsWith(null, StringComparison.OrdinalIgnoreCase)

If indeed the vars that were not been assigned with a value from the UI (or wherever it is getting assigned in) are an empty string, then s.field.StartsWith(string.Empty, StringComparison.OrdinalIgnoreCase) would always be true (cause every string starts with an empty string).
It means that you get all the records.
you can add the checks to the linq like so:
listProducts = listProducts
   .Where(s => !string.IsNullOrEmpty(strName) && s.pro_name.StartsWith(strName, StringComparison.OrdinalIgnoreCase) ||
...


text:
Q: to be to remember I was wondering if I could say "Something is to remember"
For example:

This trip is to remember

Is it grammatically correct? If it is, which part of the sentence is stressed?

A: To signify that an event is particularly remarkable, the usual construct is:

*

*"A night to remember"

*"This is a trip to remember"

*"It was a party to remember"