text:
Q: query to return single field from spring data mongo I have multiple datasource in my application (mysql and mongodb) and i am using JpaRepository (spring data jpa) and MongoRepository (spring data mongo ) respectively.
The below code works for getting all the imei numbers from the vehicle table(mysql)
@Repository
public interface VehicleRepo extends JpaRepository<Vehicle, Long>{
    @Query(value = "SELECT imei FROM vehicle", nativeQuery = true)
    public List<Object[]> findImei();
}

I have another mongo repo like below.
@Repository
public interface DeviceRepo extends MongoRepository<Device, String>{
    // looking for a method which returns all the distinct imei
}

I want to know what what would be the query in mongodb.
(My requirement is to select all the only distinct imei field from the Device and only single field selection like VehicleRepo)
I have tried multiple combinations but none worked.

A: May be a little bit late but i am doing the same thing:
If your collection just have a String (datatype) Field in it and you want to get this field only, you can try:
    @Query(value = "{ 'groupId' :  ?0 }", fields = "{ '_id': 0, 'user.$id':1 }")
    List<String> findAllUserIdByGroupId(String groupId);

the value mean query and the fields type is what you want to get / ignore
In mongo db you can check with this site (https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/)
or an answer in Stackoverflow (Spring Data Mongo Query Field parameters)

A: I could not find any solution using the @Query so i had to use MongoTemplate to achieve the same.
DistinctIterable<String> iterableObject= mongoTemplate.getCollection("collectionName").distinct("fieldName",String.class);
Iterator<String> iter = iterableObject.iterator();
while(iter.hasNext()){
    System.out.println(iter.next());
}

A: You can also use the mongoTemplate in a custom repository method to achieve same thing (similar to Alien's) response above:
 List<String> imeiList = mongoTemplate.query(Device.class)
.distinct("imei")
.as(String.class)
.all();

More info in latest spring-data-mongo docs: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.query.distinct


text:
Q: How to query connected coordinates? I have a table where I map values based on X and Y coordinates (XY are primary keys)
+---+---+--------+--------+
| X | Y | Data 1 | Data 2 |
+---+---+--------+--------+

Let's say that I have that values stored there:
    X →
    1234567
Y 1|XXXX  X|
↓ 2| XX   X|
  3|    X X|
  4| X   XX|
  5| X XXXX|

How do I build a SQL query to fetch all connected values as result? The fetch order is not important.
For example, if I query for:

*

*X=3 and Y=2 it fetches: (1,1),(2,1),(3,1),(4,1),(2,2),(3,2)

*X=5 and Y=3 it fetches: (5,3)

*X=2 and Y=4 it fetches: (2,4),(2,5)

*X=7 and Y=3 it fetches: (4,5),(5,5),(6,4),(6,5),(7,1),(7,2),(7,3),(7,4),(7,5)
The example table as SQL:
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
  `x` int(11) NOT NULL,
  `y` int(11) NOT NULL,
  PRIMARY KEY (`x`,`y`)
);
INSERT INTO `test` VALUES
(1, 0),(1, 1),(2, 2),(2, 4),(2, 5),(3, 1),(3, 2),(4, 1),(4, 5),
(5, 0),(5, 5),(6, 4),(6, 5),(7, 1),(7, 2),(7, 3),(7, 4),(7, 5);

A: What you asked can be achieved through a common table expression.
I am using TSQL in this example, but similar queries can be built using other SQL dialects.
Lets first start with a view that lists all the adjacent cells:
create view [dbo].[fromto] as
select
t1.x as x_from,
t1.y as y_from,
t2.x as x_to,
t2.y as y_to
from test t1
join test t2 on t2.x = t1.x and t2.y = t1.y + 1
union
select
t1.x as x_from,
t1.y as y_from,
t2.x as x_to,
t2.y as y_to
from test t1
join test t2 on t2.x = t1.x and t2.y = t1.y - 1
union
select
t1.x as x_from,
t1.y as y_from,
t2.x as x_to,
t2.y as y_to
from test t1
join test t2 on t2.x = t1.x + 1 and t2.y = t1.y
union
select
t1.x as x_from,
t1.y as y_from,
t2.x as x_to,
t2.y as y_to
from test t1
join test t2 on t2.x = t1.x - 1 and t2.y = t1.y

Now we have to recursively iterate through this view:
with walk (x_col_from, y_col_from, x_col_to, y_col_to, stack ) as(
select
x_from,
y_from,
x_to,
y_to,
cast(concat('|',x_from ,',',y_from, '|', x_to, ',', y_to) as varchar)
from fromto
union all
select
walk.x_col_from,
walk.y_col_from,
fromto.x_to,
fromto.y_to,
cast(concat(walk.stack,'|',fromto.x_to,',',fromto.y_to) as varchar)
from fromto
join walk on walk.x_col_to = fromto.x_from and walk.y_col_to = fromto.y_from
where CHARINDEX(cast(concat('|',fromto.x_to,',',fromto.y_to) as varchar), walk.stack) = 0
)
select * from walk

The stack field is used to memoize the cells we have already visited. It also gives the path through the grid.

A: I don't think this is possible with SQL. You need to load the data into a 2D boolean matrix and implement a search algorithm. You start with a point and recursively search in all 8 directions and add items with an X to a Set. Stop when an empty spot is found.
This is somewhat similar to an area filling algorithm in a paint program.
You could search in the database directly by issuing individual SQLs to each coordinate, but it wouldn't be very effective.

A: This can be done with some recursive** SQL path search in 4 directions, but I feel you can't do it in a single query.. from any X'd point, you can use a query step around in 4 directions and if X'es are found, use a recursive invoke of the same query to investigate the context of that target.. but you will want to avoid circular loops and flipping between neighbours. In every WHERE, a filter of "covered positions sofar" is needed. And you will find only one of the groups on each go. To find all groups, you would need to run more queries.
To avoid too many tests, I'd put a band of empty cells along the border of the square field and iterate over 1..N-2 instead of 0..N-1.
Platform: the work can be done with queries in a stored procedure. But rather I would consider not to use SQL for this. It might be more convenient to use a CLR-call, with large part of the problem coded in c#. You can implement a function referring to your classlib DLL, from a stored procedure.
****** did not look at the tags ! in MySql there is no recursive select.. so the answer is "no" anyway

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to spread one variables into columns in r my df
A   B    C  D
a 2015   1  2
d 2016   2  3
k 2016   2  4
k 2018   3  6

what I need is to do this kind of reshape
A value 2015 2016 2018
a   C    1
a   D    2
d   C    2
d   D    3
k   C         2
k   D         4
k   C               3
k   D               6

Thank you for your help

A: Though not completely sure, I think you want this! (because there is no reason why k & C and K & D combination be repeated in two rows!
library(tidyverse)
df %>% pivot_longer(!c(A, B)) %>% pivot_wider(id_cols = c(A, name), names_from = B, values_from = value, names_sort = T)
# A tibble: 6 x 5
  A     name  `2015` `2016` `2018`
  <chr> <chr>  <int>  <int>  <int>
1 a     C          1     NA     NA
2 a     D          2     NA     NA
3 d     C         NA      2     NA
4 d     D         NA      3     NA
5 k     C         NA      2      3
6 k     D         NA      4      6


text:
Q: Chow's lemma for non reduced schemes? Recall Chow's lemma:

Chow's Lemma: If $X$ is a scheme that is proper over a noetherian base $S$ then
  there exists a projective $S$-scheme $X'$ and a surjective
  $S$-morphism $f : X'\to X$ that induces an isomorphism $f^{{-1}}(U)
 \simeq U$ for some dense open $ U\subset X$.

I just looked at the proof on wikipedia (which presumably the one from EGA II) and found a slightly bothering detail. It starts by reducing to the irreducible case with the following argument:

Argument: Let $U_i \subset X_i$ be the open dense subsets in each irreducible component which satisfy the lemma. Then $U := \coprod_i (U_i -\bigcup_{j \ne i} X_j)$ is open dense in $X$ and satisfies the lemma.

If we interpret dense as dense in the zariski topology then everything works fine throughout. But if we want it to mean scheme theoretically dense there's a problem with the argument as their might be an embedded point in $U_i \cap X_j$ (consider two lines intersecting at a double point).
Is there a way to "fix" the argument so that Chow's lemma will be true for dense = scheme theoretically dense?
If not is there a simple example of a non-reduced scheme for which this "strong" Chow's lemma fails?

A: It is time to carefully put together what was said in the comments and to fill in the gaps. We will show that the 'strong' version of Chow's Lemma does not hold. More precisely: there exists $X$ such that any morphism $f\colon X'\to X$ from a projective scheme $X'$ fails to be an isomorphism over a scheme-theoretically dense open of $X$, even for proper irreducible (non-reduced, of course) schemes over an algebraically closed field. Of course, there will still be a Zariski-dense open. The good news is, inspection of the Stacks Project's proof (tag 0200) shows that the strong version holds as soon as $X$ has enough scheme-theoretically dense affine opens to constitute an open cover.
We work over some algebraically closed field $k$.
Observation: To get a counter-example, it suffices to construct a proper $k$-scheme which does not admit an affine scheme-theoretically dense open.
In fact, if a proper $k$-scheme $X$ satisfies the strong lemma of Chow, i.e., if there exists a morphism $f\colon X'\to X$ where $X'$ is projective and which is an isomorphism over a scheme-theoretically dense open $U\subset X$, then $U\cong f^{-1}U\subset X'$ is quasi-projective and contains all the associated points of $X$.
By Stacks' tag 01ZY, the finite subset $\mathrm{Ass}(X) =: T\subset U$ is contained in an affine open $V\subset U$; any such $V$ is then a scheme-theoretically dense affine open in $X$.
The strategy is to start with a proper variety $X$ which contains a finite subset $T\subset X$ of points which is not contained in any affine open and then pass to another proper scheme $Y$ where the points of $T$ are thickened to become associated points.
Let me now explain one way to accomplish the thickening. (You can jump to the lemma below if you don't care how it's done.) The approach indicated in the comments also seems to work, after appropriate modifications.
Assume that $X$ is a locally noetherian scheme and let $T\subset X$ be a closed sub-scheme with ideal sheaf $\mathscr{I}\subset \mathcal{O}_X$.
Consider the sub-scheme $Y\subset \mathbb{A}^1_{X} = \mathrm{Spec}(\mathcal{O}_X[t])$ defined by the ideal $\mathscr{J} := t^2+t\mathscr{I}$ with its natural morphism $\varphi\colon Y = \mathrm{Spec}(\mathcal{O}_X[t]/\mathscr{J})\to X$. (I hope everyone can deal with this abuse of notation?) The projection $\mathcal{O}_X[t]\to \mathcal{O}_X$ onto degree zero descends to $\mathcal{O}_Y$ and this gives rise to a section $\iota\colon X\to Y$ of $\varphi\colon Y\to X$; thus, $X$ is in a natural way a sub-scheme of $Y$ and it is easy to see that if $X$ is reduced, this gives rise to a canonical isomorphism $X\cong Y_{red.}\subset Y$. More importantly, in any case, it shows that $\mathcal{O}_Y = \mathcal{O}_X\oplus t\mathcal{O}_X$ and $t\mathcal{O}_Y = t\mathcal{O}_X$.
In particular, $$\mathrm{ann}_{\mathcal{O}_Y}(t) = \mathscr{I}+t\mathcal{O}_Y = \mathscr{I}+t\mathcal{O}_X$$ and, therefore, if $\eta\in X$ is the generic point of an irreducible component of $T$, so that $\mathscr{I}_\eta\supset\mathfrak{m}_{X,\eta}^n$ for some $n$, then $\mathrm{ann}_{\mathcal{O}_Y}(t)_\eta = \mathscr{I}_\eta+t\mathcal{O}_{X,\eta}\supset \mathfrak{m}_{X,\eta}^n+t\mathcal{O}_{X,\eta}\supset \mathfrak{m}_{Y,\eta}^n$. Thus, $\mathfrak{m}_{Y,\eta}$ is an associated prime of $\mathcal{O}_{Y,\eta}$.
This shows:
Lemma — Let $X$ be a locally noetherian scheme and $T\subset X$ a closed sub-scheme. Then there exists a bijective closed immersion $\iota\colon X\to Y$ which is an isomorphism outside $T$, and which maps the generic points of $T$ to associated points of $Y$. Furthermore, $\iota$ has a retraction $Y\to X$ which is a finite morphism.
Finally, let $X$ be a proper, integral $k$-variety with a finite set of closed points $T\subset X$ which is not contained in an affine open of $X$. For example, we can take $X$ to be any non-projective, proper, normal, integral surface and $T$ the set of non-factorial points (cf. Kleiman, Toward a numerical criterion of ampleness, IV Cor. 4). Alternatively, as Takumi Murayama has pointed out in the comments, we could take Hironaka's non-projective three-fold and two points, one on each of the two curves involved in the construction except the intersection points.
Let $Y\supset X$ be the thickening of $T$ as described in the lemma. By finiteness of the morphism $Y\to X$, $Y$ is proper too.
Then $Y$ admits no scheme-theoretically dense affine open since $\iota\colon X\to Y$ is affine and so any such would give rise to an affine open in $X$ containing all of $T$.
By the above observation, this is all we need to get a counter-example.


text:
Q: How to find the control that binds to a specific property in Silverlight I would like to get the control that binds to a specific (Observable) property.
I found an SO answer similar to exactly what I want but the solution is for WPF:
WPF. Find control that binds to specific property
Unfortunately, I cannot reference the WindowsBase.dll assembly that defines the MarkupObject and the MarkupWriter.
It results in the following error:

You can't add a reference to WindowsBase.dll as it was not built
  against the Silverlight runtime. Silverlight projects will only work
  with Silvelight assemblies.

Is there an equivalent way I can do the same for Silverlight?


text:
Q: Why getting different Specificity results on ConfusionMatrix for same ranger model on same train datain R caret? I am new in R and using caret to implement ml. I am trying a binary classification - yes/no problem of Bank Marketing Response  from UCI.
Issue: on training model on train data, the model displays max Specificity as 0.4974 but when I plot a ConfusionMatrix on same train data I get 0.9684 Specificity. Such high difference of Specificity in model summary & confusion matrix looks strange and not able to understand. (As this is imbalanced data so considering Specificity for yes class over the accuracy).
Appreciate any help or cause explanation for same

Code below for reference:
Downloading data from UCI
(unable to to download by R code but manually it gets downloaded from link)
url <- "https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip"

temp <- tempfile()
download.file(url,temp)

data <- read.table(unz(temp, "bank-additional.csv"))
unlink(temp)

Train/Test
library(tidyverse)
library(caret)

set.seed(123)

data_split_index <- createDataPartition(data$y, p = 0.7, list = FALSE)

train <- data[data_split_index,]
test <- data[-data_split_index,]

y_train = subset(train, select = y)
X_train = subset(train, select = -y)

# Data imbalance
table(y_train)
table(y_test)

Outlier Treatment
# Outlier capping function
outlier_cap <- function(x, na.rm = TRUE){

  upper_cap = quantile(x, 0.99, na.rm = T)
  lower_cap = quantile(x, 0.01, na.rm = T)

  x[x > upper_cap] = upper_cap
  x[x < lower_cap] = lower_cap

  x <- x
}

# capping outliers
train <- train %>% mutate_if(is.numeric, outlier_cap)

One Hot Encoding
pp_dummy <- dummyVars(y ~ ., data = train)

train <- predict(pp_dummy, newdata = train)
train <- data.frame(train)

test <- predict(pp_dummy, newdata = test)
test <- data.frame(test)

Data Pre Processing
pp_standardize <- preProcess(train, method = c("center","scale"))

train <- predict(pp_standardize, newdata = train)

pp_range <- preProcess(train, method = c("range"))

train <- predict(pp_range, newdata = train)

append y to train
train$y <- Y_train # as.factor(Y)

tuning
fitCtrl <- trainControl(
  method = "cv",
  # repeats = 5,
  number = 10,
  savePredictions = "final",
  classProbs = TRUE,
  summaryFunction = twoClassSummary
)

Model Ranger py
set.seed(123)

system.time(
  model_ranger_py <-  train(pull(y) ~ cons.conf.idx+contact.telephone+duration+emp.var.rate+job.self.employed+month.jun+month.mar+month.may+month.nov+poutcome.success+previous,
                            data = train,
                            metric = "Spec",
                            method = "ranger",
                            trControl = fitCtrl)
)

Issue in results of below two lines of Codes
model_ranger_py

confusionMatrix(predict(model_ranger_py, newdata = train), pull(train$y))

(UPDATE)
Getting even weird results between train & test data comparison
CM train
confusionMatrix(predict(model_ranger_py, newdata = train), pull(train$y))

################################ output ################################
Confusion Matrix and Statistics

          Reference
Prediction   no  yes
       no  2562   10
       yes    6  306

               Accuracy : 0.9945
                 95% CI : (0.991, 0.9968)
    No Information Rate : 0.8904
    P-Value [Acc > NIR] : <0.0000000000000002

                  Kappa : 0.9714

 Mcnemar's Test P-Value : 0.4533

            Sensitivity : 0.9977
            Specificity : 0.9684

plot_pred_type_distribution(df_train)

CM test
confusionMatrix(predict(model_ranger_py, newdata = test), pull(y_test))

################################ output ################################
Confusion Matrix and Statistics

          Reference
Prediction  no yes
       no  166   8
       yes 934 127

               Accuracy : 0.2372
                 95% CI : (0.2138, 0.262)
    No Information Rate : 0.8907
    P-Value [Acc > NIR] : 1

                  Kappa : 0.0229

 Mcnemar's Test P-Value : <0.0000000000000002

            Sensitivity : 0.1509
            Specificity : 0.9407

plot_pred_type_distribution(df_test)


text:
Q: TabBar is not aligned properly in UISplitViewController I dragged a SplitViewController onto the main storyboard and changed the root view to use a custom class: SplitViewController

Inside SplitViewController:

class SplitViewController: UIViewController {
  let tbc = UITabBarController()

  override func viewDidLoad() {

    [..]

    // I thought this would work
    tbc.tabBar.itemPositioning = .centered

    let vc1 = UIViewController()
    vc1.title = "Home"
    let vc2 = UIViewController()
    let vc3 = UIViewController()

    tbc.setViewControllers([vc1, vc2, vc3], animated: false)

    // I was experimenting here
    // self.splitViewController!.maximumPrimaryColumnWidth = 50000

    // One view controller is hidden for demo purposes:
    self.splitViewController!.viewControllers = [
      UINavigationController(rootViewController: tbc),
      UINavigationController(rootViewController: [..])
    ]
  }
}

I got this on iPad:

Should I drag from far left to right, the sidebar extends a bit and I can see the "hidden" tabBarItem (Home). How to get all tabBarItems to be in view?


text:
Q: How to add custom encryption/decryption in asp.net core middleware? I want to have a custom middleware in my asp.net core application where I decrypt the request that is coming and after processing or doing some work encrypt the response.
For example: if a client sends a msg "Hello server" and it is encrypted from the client side itself and when receiving on the server, the custom middleware decrypts it and further pass on to the controller for processing the data. The server replies with "hello client" and the custom middleware encrypts the data.
What I know is how the middleware works but I couldn't find any reference how to use it on my application. I have RSA encryption working with public and private key but I don't know how to implement this in the middleware. In the middleware there is httpcontext passed in Invoke function while implementing IMiddleware interface.
All I'm finding is on the internet is  Response.WriteAsync() examples. This much I have understood that there is something to do with the HttpContext class.
For simplicity take Encrypt() and Decrypt() which can take needed argument(s) to use in the middleware. General middleware invoke function is as below. Any help would be appreciated.
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
   //do decryption
   await next(context);
   //do encryption
}

A: I write a demo to achieve the "filter"
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace CustomActionFilter.Filter
{
    public class MySampleActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var secret = context.HttpContext.Request.Form["secret"].ToString();

            string privateKey = "MIICxxxxxxxxxxxxxxxxZg==";
            var privateKeyBits = Convert.FromBase64String(privateKey);
            RSA rsa = RSA.Create();
            var rsaParameters = new RSAParameters();
            BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits));
            byte bt = 0;
            ushort twobytes = 0;
            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130)
                binr.ReadByte();
            else if (twobytes == 0x8230)
                binr.ReadInt16();
            else
                throw new Exception("Unexpected value read binr.ReadUInt16()");

            twobytes = binr.ReadUInt16();
            if (twobytes != 0x0102)
                throw new Exception("Unexpected version");

            bt = binr.ReadByte();
            if (bt != 0x00)
                throw new Exception("Unexpected value read binr.ReadByte()");
            rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
            rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));

            rsa.ImportParameters(rsaParameters);
            var temp = Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(secret), RSAEncryptionPadding.Pkcs1));
            //JObject json = JObject.Parse(temp);
            context.ActionArguments["secret"] = temp;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            var res = context.Result;
            //encrypt code
        }

        private int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else
            if (bt == 0x82)
            {
                var highbyte = binr.ReadByte();
                var lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;
            }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

    }
}

and set DI in startup.cs
public void ConfigureServices(IServiceCollection services)
        {
            //services.AddScoped<MySampleActionFilter>();
            services.AddControllersWithViews();
            services.AddControllers(config =>
            {
                config.Filters.Add<MySampleActionFilter>();
            });
        }

my view :
@{
    ViewData["Title"] = "Home Page";
}

<button id="test">send</button>
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.2.1/jsencrypt.min.js"></script>
<script>

    var user = {
        "age": 18,
        "name": "tiny"
    };

    var public_key = "MIGfMA0GCxxxxxxxxxDAQAB";
    var private_key = "MIICWwIxxxxxxxxxlRbEbsDVZg==";

    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(public_key);
    var encrypted = encrypt.encrypt(JSON.stringify(user));
    console.log(encrypted);

    var decrypt = new JSEncrypt();
    decrypt.setPrivateKey(private_key);
    var uncrypted = decrypt.decrypt(encrypted);
    console.log(uncrypted);

    $('#test').click(function () {
        var user = {
            "age": 18,
            "name": "tiny"
        };
        $.ajax({
            url: "https://localhost:44369/hello",
            type: "post",
            data: {
                secret: encrypted
            },
            success: function (data) {
                alert(data);
            }
        })
    });
</script>

My controller action:
[HttpPost]
[ServiceFilter(typeof(MySampleActionFilter))]
public JsonResult Index(string secret)
{
    User json12 = JsonConvert.DeserializeObject<User>(secret);
    User res = new User
    {
        age = 0,
        name = "zero"
    };
    return Json(res);
}

Test result:


text:
Q: Matlab: Apply a function to a vector I've had this annoying problem-
What I want to do is  create a line vector that will house in every element a result of a function inside a function WITHOUT USING LOOPS
Instead of using the following code
function [ vec_L ] = VecL( N )
%%this function receives an integer number N and returns a vector of N CalcL results

vec_L = ones(1,N);
for i=1:N
vec_L(i) = CalcL( FairDice(5000) );
end

I need a vectorized version to give the same result
where CalcL( FairDice(5000) ) is the function inside a function, and I need to apply the results every time to each element of vec_L
Thanks!

A: You can use arrayfun to call the function for each input but this isn't really vectorization, it just removes the for loop.
vec_L = arrayfun(@()CalcL(FairDice(5000)), 1:N)

Keep in mind that there is no expected performance benefit of this over a for loop.
You should instead try to vectorize FairDice itself so that you can call it once and pass it an array rather than calling FairDice N times.
Based on the context of your question, all of this seems like it could be replaced with
vec_L = randi([1 6], 1, N)

A: From your comments above, you're trying to find out how many throws it takes to get the same die roll twice.
For a single run of FairDice, our chance of our first repeat occurring on each throw is:

*

*0 [No repeats possible in one throw]

*1/6 [1/6 chance that first and second rolls are the same]

*5/18 [5/6 chance that first roll and second roll are different, 2/6 chance that third roll is one of these]

*5/18 [4/6 * 5/6 chance that first 3 rolls are different, 3/6 chance that fourth roll matches]

*5/27 [3/6 * 4/6 * 5/6 chance that first 4 rolls are different, 4/6 chance that fifth roll matches]

*25/324 [2/6 * 3/6 * 4/6 * 5/6 chance that first 5 rolls are different, 5/6 chance that sixth roll matches] 25/324

*5/324 [1/6 * 2/6 * 3/6 * 4/6 * 5/6 chance that first 6 rolls are different, 1/1 chance that seventh roll matches]

So, we have a probability matrix:
probMat = [0 1/6 5/18 5/18 5/27 25/324 5/324];

And so we can do the exact same simulation that you're doing by simply testing a random number against the sum of probabilities:
randMat = rand(N,1);
[junk, vec_L] = max((cumsumprobMat>randMat),[],2);

EDIT: One more way you could use the weighted probabilities is the randSample function:
vec_L = randSample(7, N, true, probMat);


text:
Q: Need to close a jframe while showing another one I am building a desktop student management app in java. So I need to close the current JFRAME while  an another JFRAME  is visible(after closing the new jframe old jframe  should be visible ). Could  you please help me ?

A: Your basic idea is generally not recommended. You can have a look at The Use of Multiple JFrames: Good or Bad Practice? for the long winded discussion.
Generally it's recommended to use a CardLayout for these type of operations, see How to use CardLayout for more details
What you want to try and do is decouple of the navigation decision making from the views themselves - there's no reason why the first and second view should ever care about each other OR be backing decisions about how the user should navigate.

A: You can use JFrame#dispose to close just one frame, this ofcourse requires a reference to the JFrame you want to dispose


text:
Q: DB scripts automation from GIT to AWS SQL server using Jenkins? Hi Is there any one who can help me out with this....
I was trying to automate some DB scripts migration using Jenkins. All I am doing is Using a Jenkins job trying to migrate DB scripts which are in GIT repository to AWS server (SQL server 2008-R2) and execute those scripts...
What all the server and access credentials I need to have from DB server end(like access key, secret key, DNS name..etc) in order to configure a Jenkins job.

A: SQL access to the DB
For SQL access to the DB you need the following:

*

*Hostname or RDS endpoint

*TCP port number

*DB name

*DB user

*DB password

The Jenkins machine needs network access to the DB host, which means you need to allow this in the Security Groups and have VPC connectivity.
AWS API access
For API access to AWS, the best practice is to have an IAM role assigned to the Jenkins machine. The role should have necessary permissions in the IAM policies attached to it.
In addition, you need to have internet access from the Jenkins machine or configure VPC endpoints so that Jenkins can reach the AWS API.
NOTE: You can't assign an IAM role to an existing EC2 machine. IAM roles can only be assigned during instance creation.


text:
Q: Pulling files down from a web address using powershell I am having an issue where I am trying to pull all the files down from a web link.  I need to pull all the files down and place them on a local directory on my computer.  This is what I have so far, and any help would be appreciated.
$storageDir = "C:\Proj_Vader"
$webclient = New-Object System.Net.WebClient
$url = "http://Branches/Proj/Source/DB/"
$file = "$storageDir\*"
$webclient.DownloadFile($url,$file)

Seems like it is working to the point of accessing the acutal web link, and then transfering the data down.  Getting "An exception occurred during a WebClient request" error message when trying to execute.  Also, I am basically trying to copy all of the files from the URL to a local folder.

A: Not all the code is here, but this would be the framework for you to flesh out...
$SiteData = Invoke-WebRequest $url

foreach ($weblink in $SiteData.links)
{
        $weblink.href
        #  create full local path and filename
        $file = ''  # do your stuff here

        $clnt = new-object System.Net.WebClient  #  $clnt | gm
        $clnt.DownloadFile($weblink.href, $file)

}


text:
Q: How to export static plots from Plotly in R using Orca? I have successfully installed Orca using Method 4 on the github page. However, I am unsure how best to proceed to export a static plot I have made in Plotly.
I have tried calling Orca in my R script using the syntax shown on the github page, but it returns "Error: The orca command-line utility is required to use the 'orca()' function".
I would appreciate if someone is able to explain the best way to proceed. I am inexperienced with the command-line, and do not understand the syntax shown for the command-line on the previously linked github page.


text:
Q: In Presto how to query a cloumn which no value I have a integer column which is empty. How to query that I tried
select * from table where target_status_code = null

but it did not return anything

A: Probably you should use is null to check the integer column which is empty:
select * from table where target_status_code is null


text:
Q: Comparing two binary numbers with a limited set of operators in assembly I'm currently writing code in assembly for a simple computer and I've got to find a compare two binary number two each other and check whether the second number is smaller or equal to the first number.
I've got the following instruction set available:
Halt, Stop : stops machine.
ldacc <variable/constant>: loads something into the ACC
Stac <variable> : save data from ACC into a variable
Movacc : moves data from ACC into R
Jmp <label>: jpm to label
jmpz <label>: conditional jump, jumps when z=1, (z=1 when acc = 0)
out : outputs ACC data to OUTR register
Sub: acc-r stores in acc
Add: acc-r stores in acc
inc: increment acc value by 1
clacc: clears acc
and: binary and operation on acc and r, stores in acc
or : binary or operation on acc and r, stores in acc
ashr: bit shift right on data in acc (0010->0001) == div2
not: not operation on acc

So I'm trying to create a do while loop and at the end of every iteration I want to check wether number2 =< number 1, if so acc=0 and z=1 and we jump to another label.

A: This answer applies to relational comparison for data interpreted as signed:

*

*Subtract them

*If they are equal, you'll have zero for the subtraction result, so you know they are equal

*Otherwise

*

*If they are both positive1, or, if they are both negative2 then

*

*If the subtraction result is negative, then

*

*The former (minuend) was less than the latter (subtrahend)

*Otherwise

*

*The former was greater than the latter

*Otherwise: one is positive and one is negative, so

*

*The negative number is smaller than the positive number

1 extract their signs each with ashr, add their extracted signs, test the addition for zero ⇔ they are both positive
2 and them together, extract the result's sign, test the extracted sign for non-zero ⇔ they are both negative
An xor operation would have been a simpler way to test both signs being the same, but your RSC (Relatively Simple CPU) doesn't have it.

ashr in the above to be used in sufficient shift quantity to make the number entirely 0 for positive numbers or -1 for negative numbers, as per @PeterCordes comment.

If you know that they are both positive signed numbers, this is much simpler, as you can eliminate most of the cases.

A: 3 bit math works just as well as 30 bit as well as 32 bit as well as 96 bit...
operand a - operand b = result.
Z (zero flag)
C (carry out/unsigned overflow)
V (signed overflow)
N (negative)

011 - 000 = 1011 Z0 C1 V0 N1 0
011 - 001 = 1010 Z0 C1 V0 N1 0
011 - 010 = 1001 Z0 C1 V0 N1 0
011 - 011 = 1000 Z1 C1 V0 N1 0
011 - 100 = 0111 Z0 C0 V1 N0 0
011 - 101 = 0110 Z0 C0 V1 N0 0
011 - 110 = 0101 Z0 C0 V1 N0 0
011 - 111 = 0100 Z0 C0 V1 N0 0

Addition and subtraction logic that uses twos complement for signed numbers only requires one adder to do those operations, there isn't a special signed addition/subtraction nor unsigned addition/subtraction, the beauty of twos complement (that is the RESULT works with that logic in either case).  But for unsigned vs signed comparisons then the other typical flags are needed.  Your logic doesn't have these but when I post the ad-hoc program used to print the above, you will see I synthesized these things using only and and equal or not equal.
011 - 000 = 1011 Z0 C1 V0 N1 0
011 - 001 = 1010 Z0 C1 V0 N1 0
011 - 010 = 1001 Z0 C1 V0 N1 0
011 - 011 = 1000 Z1 C1 V0 N1 0
011 - 100 = 0111 Z0 C0 V1 N0 0
011 - 101 = 0110 Z0 C0 V1 N0 0
011 - 110 = 0101 Z0 C0 V1 N0 0
011 - 111 = 0100 Z0 C0 V1 N0 0

so if we view this first as unsigned 3 - 0, 3 - 1, 3 - 2 and so on to 3 - 7.
If you think through what you were taught from grade school to the present
a - b = a + (-b).
twos complement a number invert and add one so
a - b = a + (~b) + 1
we use an adder to subtract and invert the second operand and the carry in (of the lsbit).
 1000
- 999
=====

we have to "borrow" from the next column over.
The carry flag plays a big role in our lives, from the first years of grade school to the present, it is also known as the unsigned overflow flag and the borrow flag.
When we treat the adder as a sub tractor the carry out is the inverse of a borrow, if a borrow happened meaning say for example 000 - 999 in decimal which we didn't do that way in school but if we did for the hundreds digits we would be borrowing from the thousands digit and there would be this borrow hanging out there in the wind but 456 - 123 wouldn't have a borrow hanging out there in the wind.
011 - 000 = 1011 Z0 C1 V0 N1 0
011 - 001 = 1010 Z0 C1 V0 N1 0
011 - 010 = 1001 Z0 C1 V0 N1 0
011 - 011 = 1000 Z1 C1 V0 N1 0
011 - 100 = 0111 Z0 C0 V1 N0 0
011 - 101 = 0110 Z0 C0 V1 N0 0
011 - 110 = 0101 Z0 C0 V1 N0 0
011 - 111 = 0100 Z0 C0 V1 N0 0

The carry flag changes from 0 to one at the point where unsigned b is greater than unsigned a.  4>3 but 3 = 3 and less carry is 0 so
a - b, c = 0 unsigned less than or equal   a <= b
a - b, c = 1 unsigned greater than         a > b
So you can do a C and Z test to check for the or equal or just reverse operands, which reverses the equation at the end of the line
b - a, c = 0 unsigned greater than or equal   a >= b
b - a, c = 1 unsigned less than               a < b
You don't need to use the z flag just order your operands right depending on whether you want the or equal or not and which size direction you want.
The C flag which is also the inverse borrow indicated that we either didn't borrow or did for those subtractions and whether we did or not indicated the second operand was greater than or not.
That is for UNSIGNED!
For signed...
010 - 000 = 1010 Z0 C1 V0 N1 0
010 - 001 = 1001 Z0 C1 V0 N1 0
010 - 010 = 1000 Z1 C1 V0 N1 0
010 - 011 = 0111 Z0 C0 V0 N0 1

001 - 000 = 1001 Z0 C1 V0 N1 0
001 - 001 = 1000 Z1 C1 V0 N1 0
001 - 010 = 0111 Z0 C0 V0 N0 1
001 - 011 = 0110 Z0 C0 V0 N0 1

no doubt the signed overflow flag matters, but also signed has to do with positive or negative so does the nflag matter too?
Knowing the answer that big hanging out at the end is an N == V comparison.
Notice as a - b changes from b going less than a we get n == v. when a < b
110 - 100 = 1010 Z0 C1 V0 N1 0
110 - 101 = 1001 Z0 C1 V0 N1 0
110 - 110 = 1000 Z1 C1 V0 N1 0
110 - 111 = 0111 Z0 C0 V0 N0 1

Yes for the positive numbers the C flag works too but in general for signed we want one rule.  And for negative numbers   -2 compared to -4,-3,-2,-1 n == v indicates a < b.
So n!=v would indicate a>=b.  if you reverse the operands on the subtraction then b-a n==v would indicate a > b and so on.
#include <stdio.h>
void doit ( unsigned int ra, unsigned int rb )
{
    unsigned int rc,rd,re;
    unsigned int cflag,vflag,zflag,nflag,vxflag;

    rc = ra + ((~rb)&7) + 1;
    re = (ra&3) + ((~rb)&3) + 1;
    cflag = (rc>>3)&1;
    vflag=0;
    if(((ra&4)==((~rb)&4))&&(((~rb)&4)!=(rc&4))) vflag=1;
    vxflag=0;
    if(((re>>2)&1)!=cflag) vxflag=1;
    zflag=0;
    if((rc&7)==0) zflag=1;
    nflag=0;
    if((rc&4)==0) nflag=1;
    for(rd=4;rd;rd>>=1) if(ra&rd) printf("1"); else printf("0");
    printf(" - ");
    for(rd=4;rd;rd>>=1) if(rb&rd) printf("1"); else printf("0");
    printf(" = ");
    for(rd=8;rd;rd>>=1) if(rc&rd) printf("1"); else printf("0");
    printf(" Z%u",zflag);
    printf(" C%u",cflag);
//    printf(" V%u%u",vflag,vxflag);
    printf(" V%u",vflag);
    if(vflag!=vxflag) printf("!!");
    printf(" N%u",nflag);
    if(nflag==vflag) printf(" 1"); else printf(" 0");
    printf("\n");
}
int main ( void )
{
    doit(3,0);
    doit(3,1);
    doit(3,2);
    doit(3,3);
    doit(3,4);
    doit(3,5);
    doit(3,6);
    doit(3,7);

    doit(2,0);
    doit(2,1);
    doit(2,2);
    doit(2,3);

    doit(1,0);
    doit(1,1);
    doit(1,2);
    doit(1,3);

    doit(6,0);
    doit(6,1);
    doit(6,2);
    doit(6,3);
    doit(6,4);
    doit(6,5);
    doit(6,6);
    doit(6,7);
    return(0);
}

So the quick and dirty program to create the 3 bit output.
Your homework would be to know how the flags are generated and how to use them.
From grade school we know
 89
+11
====

can also be done as result, carry = 9+1 = 0,1 and 8+1+carry = 8+1+1 = 10 overall result 100 decimal  but done in parts.
Why do it in parts, so that I can see the carry.  If I wanted to do an 8 bit addition (which subtraction is addition in binary) I could do that as two 4 bit additions and the fifth bit in the low order bits is my carry out.
  z   w
   xxxx xxxx
   yyyy yyyy
=============

So why would I do that? if I only had 8 bit registers, I would cut it up in some way so that the upper bit operation done with 8 bit registers gives me 4 bits of result and I can "see" the msbit carry out, the carry flag.  As I did in the c code, did 3 bit math with much greater than 3 bit variables, so I can see the carry bit.
All of this is doable with the instructions you have available.  Nothing shown here is secret or magic, can be found at Wikipedia or elsewhere, other processor documentation, etc. elementary alu stuff, but not necessarily presented in this way (other than the several other times I did this here and other folks).


text:
Q: SQL refer Primary Key in same Table and Query I am maintaining a table of Items (Id is Primary Key). Some Items have Parent Item ( Which is also an Item, the colum Parent holds the Id of the parent Item, which is also in the same table. Some Items does not have parent so the value is set to null.
Is there any method or proper design pattern to maintain such an information. (like: The foreign key is also from the same table)
If an Id of an Item is given, What is the recommended way to write a query which loop until the parent of item is null.

eg: Given value is 5, the query should return 2.
Parent of 5 is 4, parent of 4 is 3, parent of 3 is 2 and 2's parent is null

|---------------------|------------------|
|          Id         |       Parent     |
|---------------------|------------------|
|           1         |          4       |
|---------------------|------------------|
|           2         |       null       |
|---------------------|------------------|
|           3         |          2       |
|---------------------|------------------|
|           4         |          3       |
|---------------------|------------------|
|           5         |          4       |
|---------------------|------------------|
|           6         |       null       |

I am working on a PostgreSQL database, but I beleive the solution is
  generic and may support SQL Server, MySQL, SQLite or Oracle

A: You query hierarchic tables with recursive queries:
with cte(id, parent) as
(
    select id, parent from mytable where id = :id -- <== the starting ID here
    union all
    select m.id, m.parent from cte join mytable m on m.id = cte.parent
)
select id from cte where parent is null;

A: mysql 8.0.26 ,  you can query like this:
ps. the table Name is Employees
  select     id,
             parent
  from       Employees
  where      parent = :id
  union all
  select     p.id,
             p.parent
  from       Employees p
  inner join cte
          on p.parent = cte.id
)
select * from cte;


text:
Q: How to visualize a project structure in MATLAB? I've come into ownership of several thousand lines of Matlab code, some as >900 line functions and a few directories full of function_name.m files.  It's hard to figure out what everything is doing (or relating to) or figure out the dependencies.  What would you suggest to visualize the functions structure, such as what functions are called from which, and in what sequence?

A: MATLAB Programming Style Guidelines by Richard Johnson is a good resource.

A: some suggestions on Matlab coding convention:

*

*use addpath to avert file cluttering and assist in functions taxnomony

*break up section_ for functional scripts or set for conditional runs, this can also help in plug-in/ out modules and re-use or code referencing.

*use a config file to turn on and off the options

*have an overview of the architectural set up of the constructs, as well as the modus operandi

*keep a status/ readme file ( treat yourself as a new-user, how would you assist in making it assimilable as part of a new-user's own module or part of the solutions seamlessly? if you come back to the code 3 months later feeling lost or unable to trace - something is wrong.) My suggestion: keep a journal to refine your thoughts on maintaining artful projects. Keep perfecting your art!

*for equations, use latex for documentations (and keep it in a nearby folder titled eg. documents, ensure they are easily accessible and traceable - if you have to use 'search' over your drive, something is wrong with the project management)

*break up codes into short modules for localization and shorter codes, with less scrolling, the codes will be easier to trace.

*use meaningful variables and function names (java style seems nice, eg. 'backedupDataForVerification'), do not stint to shorten the words, you will suffer later

*in designing, re-think if you should use function, scripting, or OO (object oriented)

*do not haste on premature optimatization, for speed matlab is not the best choice. If you really must, keep a none optimized version for side-to-side readibility comparison, troubleshooting and debug will not be less of a curse.

*Always, always, always comment your codes. Never use the excuse of having no time, you'll waste more time later.

*for differentiation, consider setting a new node for code modifications, eg. set a tree to differentiate the versions.

*use a separate folder for inputs/ outputs, images, intermediate results, etc.

*use timestamp to trace your versions

*share your codes with someone else, if they find it difficult to maintain, use or modify, rethink on how to refine your builds.

A: Port to NumPy.
(Joke.)
Usually in Matlab you have some files written as functions, and some as scripts. Scripts do things like load the data you want to process, and feed it to the functions, and graph it.
To organize things I would start at the top level script and find out which functions do the loading, graphing, processing, etc. Keep the scripts in a top level directory and try to separate the functions out into subdirectories, according to the purpose of the function. Put dependencies of a function into the same subdirectory. Try to make it so that no code in a directory depends on anything in a parent directory (or cousin directory).
Whenever you figure out what a function does and what its arguments are, write a doc comment.
This assumes the person who wrote the code was reasonable. If not, Matlab makes it easy to plunk everything down into one directory and have everything depend on everything else in a rickety tower of code, so you may end up doing a lot of refactoring.

A: I agree with most of the comments about Matlab not being terribly supportive of modern software source code structuring but I don't believe it's too difficult to impose some of your own structure with a little discipline.
Organise your source files into a hierarchy of directories, as you would the source files for any program written in another programming language.  You don't need to stick to a hierarchy, choose your own structure if you wish. Use the setpath command (or whatever the heck it is called) to tell Matlab where to look for your m files when you are working.
Acquaint yourself with the Matlab profiler tool which can give you call graphs (not terribly graphically, more like gprof's call graphs) which is some help in deciphering spaghetti code.
Of course, all our m files are in the repository and we serve them out of that.  We keep a private toolbox on one of our networked drives and all users can call the 'released' code in that toolbox directly.

A: Back everything up is right. Create a pristine tarball of the original source tree, and then throw it all in source control so you can track and roll back your changes.
Have a look at Matlab's depfun() and depdir(), which detect static dependencies. It could help you see dependencies between Matlab functions. With "depfun -toponly" on all the files and a little string munging, you could build a list of immediate dependencies and throw that in a GraphViz file to produce a big directed graph of your codebase's call connections. Clusters in the graph could be a good place to divide the code around. (EDIT: See Jonas's solution; looks like m2html does this for you.)
If you have a lot of latitude to rewrite the code, consider rewriting some of the code as objects, using stateless utility classes with class methods and private functions as ways of packaging related functions together and providing some encapsulation. I've worked with largish Matlab codebases organized this way, and it works all right. In classic Matlab, classes are your only way of doing some sort of packages. I believe Matlab's newer OO system has namespace support, too.
If you don't want to convert the code to OO, you can organize related functions in subdirectories. That helps to organize it for source code browsing at least.
All the functions should have some doco in Matlab's standard helptext format, including an H1 line. If they don't, stick the comments on what you learn there. Then use the "contentsrpt" tool to automatically generate table of contents files for the classes or directories.
Good luck.

A: I have had to deal with this problem many times in my various roles at The MathWorks.  This is what I do for the big pieces of MATLAB code:

*

*Back it up, maybe twice!

*Select all, Ctrl-I to smart indent

*Select all, Ctrl-J to wrap comments

*If I am feeling paper-based- Print all the files out, and get a set of highlighters-  follow manually, highlighting long term variables and important function calls.
~~~ AND  / OR ~~~
5  If I am feeling lucky, start running the code in the debugger, stepping through
one line at a time (stepping into subfunctions that were user written)
At this point, I can go through and follow a typical flow through the control structure.  I may not have a great idea what everything does, but I have a decent idea of what is going on.
Normally, my goal is to find a bug, solve it and move on.  Your goals might be completely different.  This is the method that I have used to quickly comprehend hundereds of different pieces of MATLAB code that I have been sent over the years.

A: Does your code come with decent help text? In that case, m2html is going to be a great help, since it allows you to create linked html help for easy browsing.
Furthermore, it allows you to make dependency graphs, which help you understand a bit more how you may want to organize the code.


text:
Q: Browserify модульная подгрузка Как настроить browserify так, чтобы он при сборке не дублировал скрипты.
Пример: На странице подключаются два скрипта, один это основной bundle.js (точка входа в приложение), второй, module.js, может подрубиться в любой момент (динамически... когда возникнет необходимость). Оба файла используют одну библиотеку, допустим jquery. Как сделать чтобы module.js не содержал в себе всю библиотеку jquery? т.к. она уже есть в bundle.js.
index.html
<script src="bundle.js"></script>
<script src="module.js"></script>

bundle.js
var $ = require('jquery');

module.js
var $ = require('jquery');

UPD
gist.github.com - bundle.js который у меня получается. Видно jquery забиндин

A: Вы можете, например, вообще вынести jQuery за пределы сборок, и в ручную подключать jQuery к странице. Такой подход оказывается очень полезным, когда кроме собственного кода, нужно использовать какие-то сторонние jQuery плагины, которые не совместимы с CommonJS.
Для того, чтобы использовать глобальный объект jQuery через require вам нужно будет использовать плагин browserify-shim. Он конфигурируется через package.json и вам нужно будет добавить туда следующие строчки:
"browserify": {
    "transform": ["browserify-shim"]
},
"browserify-shim": {
    "jquery": "global:jQuery",
}

index.html будет иметь вид:
<!-- Здесь нужно использовать реальный путь для jQuery -->
<script src="jquery.js"></script>
<!-- А эти сборки не будут содержать jQuery -->
<script src="bundle.js"></script>
<script src="module.js"></script>

Файлы bundle.js и module.js остануться не изменными.


text:
Q: NullObjectReference for Admob in different activities I had read a few q&a in stackoverflow, but still not able to get it work.
Admob on Multiple Activities?
Similar to above solutions, I got the below error
android.content.res.Resources android.content.Context.getResources()' on a null object reference

in this line
 AdView adView = new AdView(this);

Can anyone find out why it happens?
CommonCode.java
public class CommonCode extends AppCompatActivity{
//private AdView mAdView;

public void createAdview(){
    AdView adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
}}

MainActivity.java
public class MainActivity extends AppCompatActivity {

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

    CommonCode cc = new CommonCode();
    cc.createAdview();}}

A: You extends AppCompatActivity in CommonCode that define CommonCode as an Activity.Activity context is null untill it start.
You need to remove extnds AppCompatActivity from CommonCode class and pass the context in a parameter as below :
public class CommonCode{

    public void createAdview(Context context){
        AdView adView = new AdView(context);
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
    }
}

Now in a MainActivity you need to call the method like this :
public class MainActivity extends AppCompatActivity {

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

        CommonCode cc = new CommonCode();
        cc.createAdview(this);
    }
}

A: You need to pass activity context in this line
AdView adView = new AdView(this);

Create common class like this
public class CommonCode {
public CommonCode (){
}
public void createAdview(Context context){
AdView adView = new AdView(context);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}}

And use it like this in your activity
CommonCode cc = new CommonCode();
cc.createAdview(this);


text:
Q: Thumbnail description in gallery partially covered - float:left problem? See http://jsfiddle.net/ZdjrT/  - The text under the first two thumbnails is partially obscured.
I can solve this if I set a height on the description, but obviously the description height is based on how much content is in there, so it's not a static value that I can set.
Is there another solution?
Thanks,
Wesley

A: The reason the text is covered up is because it's so long that it overruns the 120px of height you explicitly set for a.thumbnail. The solution would be to get rid of that height declaration, but that could result in staggered rows that don't line up.
The solution for that is to use display:inline-block instead of float:left. Because you're only doing this on a elements, which are naturally inline, it should work in IE6+.
Here's the fiddle to prove it (note the vertical-align:top)

A: Take a peek at this revision: http://jsfiddle.net/ZdjrT/5/
I made a.thumbnail display as an inline-block and removed the float. Changed the height to auto and then displayed the img as a block element. Seems to work in IE7/8, Chrome and FF.


text:
Q: Player and "laser" disappears when objects collide I'm making a game where I have a player that is suppost to shoot enemies falling down the screen. The issue is that the enemy objects dissapears before having collided and the player also dissapears before the collission happens. Instead the objects disapears when it's on the same tredjectory as the enemy object which is not what is intended.

var left_key = 37;
var up_key = 38;
var right_key = 39;
var down_key = 40;
var space_key = 32;
var player_movment = 4;

var lastLoopRun = 0;

var controller = new Object();
var enemies = new Array();

function createSprite(element, x, y, w, h) {
  var result = new Object();
  result.element = element;
  result.x = x;
  result.y = y;
  result.w = w;
  result.h = h;
  return result;
}

function toggleKey(keyCode, isPressed) {
  if (keyCode == left_key) {
    controller.left = isPressed;
  }
  if (keyCode == right_key) {
    controller.right = isPressed;
  }
  if (keyCode == up_key) {
    controller.up = isPressed;
  }
  if (keyCode == down_key) {
    controller.down = isPressed;
  }
  if (keyCode == space_key) {
    controller.space = isPressed;
  }
}

function intersects(a, b) {
  return a.x  b.x && b.y + b.h && a.y + a.h > b.y;
}

function ensureBounds(sprite, ignoreY) {
  if (sprite.x < 20) {
    sprite.x = 20;
  }
  if (!ignoreY && sprite.y < 20) {
    sprite.y = 20;
  }
  if (sprite.x + sprite.w > 480) {
    sprite.x = 480 - sprite.w;
  }
  if (!ignoreY && sprite.y + sprite.h > 480) {
    sprite.y = 480 - sprite.h;
  }
}

function setPosition(sprite) {
  var e = document.getElementById(sprite.element);
  e.style.left = sprite.x + "px";
  e.style.top = sprite.y + "px";
}

function handleControls() {
  if (controller.up) {
    player.y -= player_movment;
  }
  if (controller.down) {
    player.y += player_movment;
  }
  if (controller.left) {
    player.x -= player_movment;
  }
  if (controller.right) {
    player.x += player_movment;
  }
  if (controller.space && laser.y <= -120) {
    laser.x = player.x + 9;
    laser.y = player.y - laser.h;
  }
  ensureBounds(player);
}

function showSprites() {
  setPosition(player);
  setPosition(laser);
  for (var i = 0; i < enemies.length; i++) {
    setPosition(enemies[i]);
  }
}

function checkCollisions() {
  for (var i = 0; i < enemies.length; i++) {
    if (intersects(laser, enemies[i])) {
      var element = document.getElementById(enemies[i].element);
      element.style.visibility = "hidden";
      element.parentNode.removeChild(element);
      enemies.splice(i, 1);
      i--;
      laser.y = -laser.h;
    } else if (intersects(player, enemies[i])) {
      var element = document.getElementById(player.element);
      element.style.visibility = "hidden";
    } else if (enemies[i].y + enemies[i].h >= 500) {
      var element = document.getElementById(enemies[i].element);
      element.style.visibility = "hidden";
      element.parentNode.removeChild(element);
      enemies.splice(i, 1);
      i--;
    }
  }
}

function updatePositions() {
  for (var i = 0; i < enemies.length; i++) {
    enemies[i].y += 4;
    enemies[i].x += getRandom(7) - 3;
    ensureBounds(enemies[i], true);
  }
  laser.y -= 12;
}

function addEnemy() {
  if (getRandom(50) == 0) {
    var elementName = "enemy" + getRandom(10000000);
    var enemy = createSprite(elementName, getRandom(450), -40, 45, 45);

    var element = document.createElement("div");
    element.id = enemy.element;
    element.className = "enemy";
    document.children[0].appendChild(element);

    enemies[enemies.length] = enemy;
  }
}

function getRandom(maxSize) {
  return parseInt(Math.random() * maxSize);
}

function loop() {
  if (new Date().getTime() - lastLoopRun > 50) {
    updatePositions();
    handleControls();
    showSprites();
    checkCollisions();

    addEnemy();

    lastLoopRun = new Date().getTime();
  }
  setTimeout("loop();", 2); //6:10 episode 2 <-- forklaring:
}

document.onkeydown = function(evt) {
  toggleKey(evt.keyCode, true);
};

document.onkeyup = function(evt) {
  toggleKey(evt.keyCode, false);
};

var player = createSprite("player", 250, 460, 20, 20)
var laser = createSprite("laser", 0, -120, 2, 50);

loop();
#player {
  background: red;
  width: 20px;
  height: 20px;
  position: absolute;
}

#background {
  background: black;
  width: 500px;
  height: 500px;
  position: absolute;
  left: 0px;
  top: 0px;
}

#laser {
  background: green;
  width: 2px;
  height: 50px;
  position: absolute;
}

.enemy {
  background: blue;
  width: 35px;
  height: 35px;
  position: absolute;
}

A: The code for your collision detection isn't correct.
Try this:
function intersects(a, b) {
  return a.x > b.x - a.w && a.x  b.y - a.h && a.y < b.y + b.h;
}


text:
Q: Python subprocess can't find Pythonpath module I am trying to use subprocess.run(['python3.9', "scripts/example.py"], check=True).
example.py uses a module, that I have added to the PYTHONPATH.
However,
whenever I run the above line, the module is not found.
The confusing part for me is, that printing sys.path inside of example.py I do see the path to my module.
But when I am running os.system("which python") or os.system("echo $PYTHONPATH") inside example.py, it returns/prints nothing.

A: Looks like you need to check the doc for the env parameter of subprocess.run and set it appropriately.
Side note: typically you would want to use the exact same Python interpreter for the sub-process call, so you would write: subprocess.run([sys.executable, 'scripts/example.py'], ...), unless of course you really do want 'python3.9' explicitly and nothing else (which would be surprising).


text:
Q: DataContractJsonSerializer class not found I want to serialize my class into JSON by using DataContractJsonSerializer class but when I try to access it in my Console application it is not found in the namespace "System.Runtime.Serialization.Json".

Please help me so that I can serialize the data using DataContractJsonSerializer class. Thanks.

A: Go to Tools >> NuGet Package Manager >> Manage NuGet Packages for Solution...
In the "Browse" tab, search for "System.Runtime.Serialization.Json" and install it in your project.
In your class file, add using System.Runtime.Serialization.Json or right-click the red squiggly and select "add using System.Runtime.Serialization.Json"


text:
Q: How do I insert QTabBar in Qt Designer? This might very well be very stupid question, but I can not find QTabBar in Qt Designer. There is QTabWidged in the "Containers" group, but it is not the same - I don't need different pages, I just need the tab bar.
(I am using 4.7.2 version of Qt Designer under KDE4 on debian.)

A: There is no item in the designer that is a QTabBar, the only way you could accomplish this is by creating a plain QWidget and promoting it to a tabbar, but you will then have to set up the whole thing in code.
As for the pages you do realize that you can also promote the content widgets of a QTabWidget in designer to any subclass of QWidget, builtin or something that you created.

A: In Qt Designer 4.8 you can add a Widget where you want the QTabBar to be, and then right-click and choose "Promote To ▸ QTabBar". (Note: "Promote To", not "Morph Into")


text:
Q: How cast a generic value:'T to an array<'R> on F# I'm building reflection for a JSON parser, and hit a road when serializing arrays:
let rec toJson (value:'T) =
    let t = typedefof<'T>

    match t with
    | _ when FSharpType.IsRecord(t) ->
        let fields = fieldsOf<'T>
        let values = seq {
            for field in fields do
                let x = field.GetValue value

                let result = toField field x
                yield field.Name.ToLower(), result
        }
        values |> Seq.filter(fun (_, x) -> x <> Null) |> List.ofSeq
        |> Chiron.JsonObject.ofPropertyList
        |> Chiron.JsonObject.toJson
        |> Chiron.Formatting.Json.format
    | _ when t.IsArray ->
        let te = t.GetElementType()

        let values = value :? seq<obj> <-- How turn value into a array/seq?
        let txt = value :?> IEnumerable |> Seq.map toJson |> String.concat ""
        txt
    | _ ->
        _toField t value
        |> Chiron.Formatting.Json.format

let rows:Log.LogSyncRow array = query...

rows |> toJson

The problem is (value:'T) is a record or a array of records, and can't see how enumerate them. I try with How to cast an object to a list of generic type in F# but not work:
let values = value :?> seq<obj>

Error FS0008: This runtime coercion or type test from type    'T     to     seq<obj>    involves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed. (FS0008) (Server)

or
value :?> IEnumerable

Error FS0033: The type 'System.Collections.Generic.IEnumerable<_>' expects 1 type argument(s) but is given 0 (FS0033) (Server)

A: The problem is that the compiler doesn't know what 'T is, and so doesn't know whether 'T is castable to IEnumerable<obj> at all. There are actually some types that can't be cast like this (which is what the compiler tells you: "Runtime type tests are not allowed on some types")
But you can still force the compiler to shut up about it - cast to an obj first, then cast to whatever you need:
value :> obj :?> seq<obj>

Or, alternatively, use the built-in function box, which is just the same cast to obj, only wrapped as a function:
box value :?> seq<obj>


text:
Q: to_bytes function returning odd value I am having trouble with the to_bytes function of integer type. The values bigger than 18200000 are giving me a weird byte array as an output.
I am using python 3.5 on raspberry pi. The value is not exactly 18200000 but close.
The way I call the function is like this:
frequency = 20000000

print(frequency.to_bytes(7,byteorder='big'))

The expected result would be b'\x01\x31\x2D\x00'
What I get is b'\x011-\x00'.

A: For bytes that are printable ASCII characters, python will display the corresponding character. \x31 is the character 1, and \x2D is -.


text:
Q: std::ignore explanation of compiler errors I used std::ignore(1,',') before the first getline(iss,name,',') and received the error 'ignore' is undeclared in this namespace 'std'.
        if (myfile.is_open()){
 98     while ( getline (myfile,line) ) {
 99         //parse line
100         string myText(line);
101         istringstream iss(myText);
102         if(!(iss>>id)) id=0;
103
104         std::ignore(iss,1,',');
105         std::getline(iss,name,',');
106         std::getline(iss,status,',');
107         std::getline(iss,email,',');
108         cout<<name<<endl;
109         Student newStudent(id,name,status,email);

Why is it the getline functions work but the ignore doesnt?

A: ignore is a member function.
iss.ignore(1, ',');


text:
Q: Issues printing the wrong char I've been playing around with ideas for a simple hangman program (new computer science major), and this code, while logically correct and working, prints a strange character (╠ to be exact) instead of printing an underscore(_) like it should. This only seems to happen when the "else if" statements are present. Anyone know what is causing this?
#include <stdlib.h>
#include <stdio.h>

int main(){

char w[13][3] = {
        { 'c', 'a', 't' }, //0
        { 'd', 'o', 'g' }, //1
        { 'r', 'a', 't' }, //2
        { 'e', 'e', 'l' }, //3
        { 'c', 'o', 'w' }, //4
        { 'o', 'w', 'l' }, //5
        { 'e', 'm', 'u' }, //6
        { 'b', 'a', 't' }, //7
        { 'e', 'l', 'k' }, //8
        { 'p', 'i', 'g' }, //9
        { 'b', 'e', 'e' }, //10
        { 'h', 'e', 'n' }, //11
        { 'f', 'o', 'x' }, //12
};

char u,
    dis[100];

int random;

srand(time(NULL));
random = rand() % 13;

printf("%d\n", random); //check random number
printf("Enter a letter: ");
u = getchar();

for (int i = 0; i < 3; i++){

    if (w[random][i] == u){
        dis[i] = u;
    }
    else if (w[random][i] == '_'){
        continue;
    }
    else if (w[random][i] != u && w[random][i] != '_'){
        continue;
    }
    else {
        dis[i] = '_';
    }

}

for (int i = 0; i < 3; i++){
    printf("%c", dis[i]);
}

printf("\n\n");
system("pause");
}

A: Your second else if statement,
else if (w[random][i] != u && w[random][i] != '_')
is going to be true most of the time (Whenever you don't guess the correct random letter). Since the only statement in that block is continue;, your dis[i] isn't set. Your output is printing a character which hasn't been initialized.
An alternative implementation would use (for example)
int hangman=0;
char u;
int maxGuesses=10;

// Seed random part

while (hangman < maxGuesses) {
  printf("%d\n", random); //check random number
  printf("Enter a letter: ");
  u = getchar();

  for (i=0; i<3; i++) {
    if (w[random][i] == u) {
      // You just guessed this letter
      dis[i] = u;
    }
    else if (dis[i] != '_') { // This requires you initialise dis[...] to '_'
      // You already know this letter
      continue;
    }
    else {
      // You don't know the letter, and you guessed wrong
      hangman++;
    }
  }

  for (int i = 0; i < 3; i++){
    printf("%c", dis[i]);
  }
  drawHangman(hangman);

  for (int i = 0; i < 3; i++) {
    if(dis[i] == '_') {
      break;
    }
    // If none are == '_', then finished?
    // Go to the end of the program
  }
}

Note: This will increment hangman 3 times if you guess none of the letters, and haven't managed any correct guesses yet! That might be harsher than intended, so probably a better increment system can be used - maybe a bool, initially false, set to true if you get it right? Then after your for(i...) loop, you can test and increment just once instead of within the loop.

A: The display of the random character is caused by:

*

*dis is not initialized.

*dis[i] is not set to _ in couple of the clauses in the for loop.
In the for loop,
for (int i = 0; i < 3; i++){

    if (w[random][i] == u){
        dis[i] = u;
    }
    else if (w[random][i] == '_'){
        // Missing code to set dis[i]
        continue;
    }
    else if (w[random][i] != u && w[random][i] != '_'){
        // Missing code to set dis[i]
        continue;
    }
    else {
        dis[i] = '_';
    }
}

Update
The code in the for loop is strange.
    else if (w[random][i] == '_'){

That conditional is never going to be true. None of the words you have in your test cases have '_' in them.
Based on your data, the conditional in
    if (w[random][i] == u){

or
    else if (w[random][i] != u && w[random][i] != '_'){

will be true. That means, the last clause,
    else {
        dis[i] = '_';
    }

will never be exercised.
I think your code can be simplified to:
for (int i = 0; i < 3; i++){

    if (w[random][i] == u){
        dis[i] = u;
    }
    else {
        dis[i] = '_';
    }
}


text:
Q: Building a file in Linux I am a Windows user but I need to use a Linux tool. I am using Ubuntu. The tool's website here provided a file named: build-x86-64.sh which I installed it. It then says all what you need is to run: % ./build-x86-64.sh. I tried sudo ./build-x86-64.sh. However, I get this error from Linux:
sudo: ./build-x86-64.sh: command not found

Note that I am in the right directory where I saved the .sh file. I also installed all the per-requisites:
autoconf
automake
libtool
pkg-config
gcc

Please, can you point to me what's wrong?

A: When using sudo to run a script using relative path syntax, it appears that many different error messages get hidden behind that "command not found" error message. I'd suggest re-running without the sudo to see what the actual error is.
Likely issues:

*

*My guess is the .sh file doesn't have the executable bit set (i.e., the OS hasn't been told it's a program). Try chmod a+x build-x86-64.sh from the same directory, to fix this. This should only need to be done once, and you may wish to look up "executable bit" at some point.

*Maybe the file isn't where you think it is? But, you say you're already in the same directory, so it should be fine...

A: *

*check your user running: whoami

*check if you can execute the bash script running: ls -la build-x86-64.sh

*check if your user can call sudo running: sudo -l -U <whoami-output>

*check if your shell is able to run sudo running: sudo whoami
So:

*

*If the output of the point 1 or 4 is root the problem is relative at the permission about execution of build-x86-64.sh file, change it running : sudo chmod 744 build-x86-64.sh and then run again sudo ./build-x86-64.sh

*If the output of point 3 say you are able to run sudo , you have to put the directory where the file build-x86-64.sh is in the sudoers secure_path editing the /etc/sudoers file by running : sudo visudo and adding the /path-where-is-your-file.sh as explained here. Be careful, editing that file can compromise the security of your device.

Hope it help ;)


text:
Q: Scan with WIA. Set the properties and the drawer ADF I need to use a scanner's ADF. I haven't found anything that works for me. I have tried this code (found on the net) but none of the settings are taking effect. The scanner window opens but the properties are not as set. Also I don't know the way, if the code worked, to set up the ADF.
I tried this too: Scanning with C# and WIA
private void button2_Click(object sender, EventArgs e)
{
   WIA.CommonDialog _dialog = new CommonDialog();
   WIA.Device _scanner = _dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, false);

        foreach (Property item in _scanner.Items[1].Properties)
        {
            switch (item.PropertyID)
            {
                case 6146: //4 is Black-white,gray is 2, color 1
                    SetProperty(item, 2);
                    break;
                case 6147: //dots per inch/horizontal
                    SetProperty(item, 100);
                    break;
                case 6148: //dots per inch/vertical
                    SetProperty(item, 100);
                    break;
                case 6149: //x point where to start scan
                    SetProperty(item, 0);
                    break;
                case 6150: //y-point where to start scan
                    SetProperty(item, 0);
                    break;
                case 6151: //horizontal exent
                    SetProperty(item, (int)(8.5 * 100));
                    break;
                case 6152: //vertical extent
                    SetProperty(item, 11 * 100);
                    break;
            }
        }

        CommonDialog oDialog = new CommonDialog();
        oDialog.ShowAcquisitionWizard(_scanner);
   }

    private void SetProperty(Property property, int value)
    {
        IProperty x = (IProperty)property;
        Object val = value;
        x.set_Value(ref val);
    }

A: WIA in C# is murky and most of the learning happens via Trial-and-Error.
I'll give you some sample code for my usual Setup.
using WIA;

CommonDialog dialog = new CommonDialog();
DeviceManager manager = new DeviceManager();

// selecting device via UI
Device device = dialog.ShowSelectDevice();

// usually, the first item is the feeder
// depending on the device, the feeder is the only item
Item item = device.Items[1];

Now that you have a WIA.Item, you can Scan like so:
ImageFile image = (ImageFile)item.Transfer(FormatID.wiaFormatTIFF)

You can save this file by doing:
image.SaveFile("imageName.tiff");

To scan all Documents in your Feeder, you could use a while(true)-Loop, though you have to catch the Exception of an empty Feeder.
This, of course, will Scan with the preconfigured settings, so what if you wanted to modify your scan?
Let's say you wanted to change the "Document Handling Select"-Property of your Device. First, you have to find out the possible values for your Property.
Every Property has a SubType, basically indicating a spectrum of possible values for your Property. E. g.
WiaSubType.RangeSubType (an enum) indicates that you can enter a Range of Ints as a Value, e. g. from 0-100.
To find the SubType of a Property:
WriteLine(device.Properties["Document Handling Select"].SubType);
// FlagSubType

Print out possible values:
foreach(var value in device.Properties["Document Handling Select"].SubTypeValues)
{
    WriteLine(value);
}

With my Device (Fujitsu), I got these possible flags:
1
4
8
32
256
512

What do these mean? I have no clue.
To get the current Setting:
device.Properties["Document Handling Select"].get_Value();

In my case, 1.
To change the Setting:
device.Properties["Document Handling Select"].set_Value(4);

Of course, this is only possible because "Document Handling Select" isn't ReadOnly. To check if a Property is ReadOnly:
device.Properties["Document Handling Select"].IsReadOnly;

You can do this with any Property, either from an Item, a Device or else.
What I advise against are ugly, long switch-cases. Look into switch-expressions.
Here are more Samples, unfortunately in VB, though you could easily translate them and learn some VB on the go! Some might not work as this is for Wiaaut.
A nice Example for Scanning inside a WPF-App. Includes MVVM.
I hope this wasn't too late, or at least gets someone else started with WIA.


text:
Q: Можно ли любой указатель рассматривать как массив из 1 элемента? Представим, что у нас есть нечто, например
char ch;

Мы берём адрес:
char *p = &ch;

Итак, у нас есть указатель на char. Мы точно знаем, что он валидный. Но можем ли мы рассматривать его как указатель на массив из одного элемента? Вроде бы логично, что да, но всплывает интересный момент:

If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P.

Если мы говорим, что этот указатель можно рассматривать как указатель на массив длины 1, то этот кусок стандарта означает, что мы имеем право рассчитывать на то, что
assert(p < p + 1);

Что по сути означает, что любой валидный указатель можно увеличить на 1 и получить число больше предыдущего (без переполнения). Гарантирует ли это стандарт?
Для char есть есть 2 интересных адреса 0x7FFFFFFF и 0xFFFFFFFF - первый из них переполнится если 4-байтовый (для 8-байтных есть аналогичные числа - суть не меняется) указатель представлен знаковым типом, а второй - если беззнаковым. Я бы ожидал, что указатели беззнаковые, а -1 - зарезервированный адрес, который не используется, но в стандарте скорее всего про это ничего нет. Но если подумать, для других типов данных инкремент увеличивает указатель на размер типа, а не на 1, так что там будут адреса чуть меньше. Но всё равно данные должны будут затрагивать один из этих адресов.

A: C++
basic.compound/3:

For purposes of pointer arithmetic ([expr.add]) and comparison ([expr.rel], [expr.eq]), a pointer past the end of the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical array element n of x and an object of type T that is not an array element is considered to belong to an array with one element of type T.
Для целей арифметики указателей ([expr.add]) и сравнений ([expr.rel], [expr.eq]), указатель на элемент, следующий непосредственно за последним элементом массива x из n элементов, считается эквивалентным указателю на гипотетический элемент n массива x. Также объект типа T, не являющийся элементом массива, считается принадлежащим массиву из одного элемента типа T.

В Expressions / Compound expressions / Unary expressions / Unary operators / 3 приведён пример:
int a;
int* p1 = &a;
int* p2 = p1 + 1;   // defined behavior
bool b = p2 > p1;   // defined behavior, with value true

В C используется аналогичный подход.
6.5.6 Additive operators / 7:

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
Для целей данных операторов (Additive operators), указатель на объект, не являющийся элементом массива, ведёт себя также как указатель на первый элемент массива единичной длины, с типом объекта в качестве типа элемента массива.

6.5.6 Additive operators / 8:

... if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object.
... если выражение P указывает на последний элемента массива, то выражение (P)+1 указывает на элемент, следующий непосредственно за последним элементом массива. Если выражение Q указывает на элемент, следующий непосредственно за последним элементом массива, то выражение (Q)-1 указывает на последний элемент массива.

6.5.8 Relational operators / 4:

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
Для целей данных операторвов (Relational operators), указатель на объект, не являющийся элементом массива, ведёт себя также как указатель на первый элемент массива единичной длины, с типом объекта в качестве типа элемента массива.

A: Дам пару отрывков отсюда

Standard (first)
The Standard only guarantees that 0 is a sentinel value as far as
pointers go. The underlying memory representation is no way
guaranteed; it's implementation defined.
Using a pointer set to that sentinel value for anything else than
reading the pointer state or writing a new state (which includes
dereferencing or pointer arithmetic) is undefined behavior.

Другой ответ

The C++ standard doesn't "reserve" any pointer addresses other than
zero (null). So it is not safe to use 1 or any other value as a
"magic" pointer value. Of course, in practice, some implementations of
c++ probably do not every use certain values. But you don't get any
guarantees from the language definition.

Если вкраце то стандарт не ограничивает вас инкрементирование вашего указателя, но и не гарантирует вам ничего, зависимостей не мало конкретная OS, конкретная реализация компилятора все это варьируется.
A ваш пример со сравнением проверяется просто. Задайте значение для p на границе и инкрементируйте не думаю что это запрещено. Другое дело получите ли вы такое значение p в реальности.


text:
Q: Passing URI Segments to your methods Im going through codeigniter-3 tutorial and I dont fully understand what they mean with this:
"If you are using the URI Routing feature, the segments passed to your method will be the re-routed ones."
Its under "Passing URI Segments to your methods"
code displayed:
<?php
class Products extends CI_Controller {

        public function shoes($sandals, $id)
        {
                echo $sandals;
                echo $id;
        }
}

http://www.codeigniter.com/user_guide/general/controllers.html
Are the segments the arguments passed in to the function and what do they mean with they will be re-routed?
I checked the URI Routing feature but still dont understand.
Can anyone can explain what they mean?

A: Well in your case, I would suggest you to read on URI Routing, to get more information regarding what's going on.
But as to answer your questions, if you are for example defining new URI's to change your URL as you like, then by calling shoes($sandals, $id), you will get the parameters that were manipulated in the re-routing process, and not the original ones.
In other words, if you have tried re-routing your URI's
from index.php/Product/shoes/blue/10 to index.php/Product/shoes/green/10
then by calling shoes($sandals, $id) you will get green and 10, as you mentioned, note the blue will not be displayed then.


text:
Q: How can I pass the name of `ObjectName` like `self.lineEdit_260` as a parameter in a method using python 3.4? How can I pass the name of ObjectName like self.lineEdit_260 as a parameter in a method using python 3.4?
self.Open_Fan_J104_A_stage_2(no=self.lineEdit_260.text()))

def Open_Fan_J104_A_stage_2(self,no):

    if no=='' and self.lineEdit_247.text()=='':
        print(type(self.lineEdit_260.text()))
        self.start_time=datetime.datetime.now()
        self.lineEdit_260.setText(str(self.start_time))
    elif self.lineEdit_247.text()=='':

        QMessageBox.information(self, 'x')

    else:
        self.lineEdit_260.setText('')
        self.start_time = datetime.datetime.now()
        self.lineEdit_260.setText(str(self.start_time))

    self.lineEdit_247.setText('')
    self.lineEdit_241.setText('')

When I run this code:
self.pushButton_123.clicked.connect( self.Open_Fan_J104_A_stage_2(no=self.lineEdit_260.text()))

TypeError: argument 1 has unexpected type 'NoneType'

A: I think, the Open_Fan_J104_A_stage_2 expects a callable and since there was a lack of information. So try,
self.Open_Fan_J104_A_stage_2(lambda: self.lineEdit_260.text()))


text:
Q: Resource embed through an http url 301 permanently redirected to an https one Now I have a website, running on ubuntu and nginx.
http://www.huangwenchao.com.cn
And I have just installed SSL certificate on it:
server {
    listen 80;
    server_name www.huangwenchao.com.cn huangwenchao.com.cn;
    rewrite ^/(.*)$ https://www.huangwenchao.com.cn/$1 permanent;
}

server {
    listen 443;
    root /var/www/huangwenchao;
    index index.php index.html index.htm;
    server_name www.huangwenchao.com.cn huangwenchao.com.cn;
    ssl on;
    ssl_certificate /home/ubuntu/ssl/mydomain.crt;
    ssl_certificate_key /home/ubuntu/ssl/mydomain.ssl.key;
}

That means when I request http from this domain, it was 301 pamanently redirected to https.
And In the beginning, the browser(chrome) told that the page has some insecure image, video and script, like below:
https://www.huangwenchao.com.cn/2013/11/427-3032.html
Some of the resource here is pointing to my own site, like some image with link:
http://www.huangwenchao.com.cn/wp-content/uploads/2015/01/tortoisegit-diff.jpg
in this page: https://www.huangwenchao.com.cn/2015/01/git-patch.html

Question
So I'm wondering:

*

*What would happen when I embed a 301 redirected http resource in the page?

*After redirected? Should the resource transferring under encryption?

*Is it safe in this case? Or may have some other risk?

Teachers, please tell, thank you!

A: There is an "insecure content" warning if there is one or more resources loaded with HTTP, even if the resources are redirected to HTTPS. This makes sense because, if the visitor is under a man-in-the-middle attack (an attacker modifies the unencrypted resources), the attacker can send arbitrary code by changing an unencrypted (HTTP) resource like a script.
To avoid this warning, you have to make sure every resource in your page is loaded with HTTPS: scripts, style sheets, images, fonts, etc. For Wordpress, be sure you have your website address beginning with "https://" and be sure all the images you add in your posts are loaded with HTTPS.
It is a good idea to redirect all the traffic to HTTPS with a 301 redirect as you did, because you are sure all your visitors browse with HTTPS (=with encryption). But you have to be sure of the quality of the HTTPS, else some visitors could be unable to access your website.
Some side notes: you can replace the rewrite rule by return 301 https://$host$request_uri; and I got a certificate error with your website, be sure you include the intermediary certificates. You can check the quality of the HTTPS on https://www.ssllabs.com/.


text:
Q: how to retrieve all the sns endpoints for a user? From an AWS Lambda function, I'm calling client.create_platform_endpoint() with a user's iOS device token.
Later I want to publish() push notifications for all the endpoints of a user. How can I retrieve all of a user's sns endpoints that have been created?
My approach is going to be a Dynamodb table mapping all the 'cognito_identity_id' values with all the endpoint values.
Is there a better approach I should consider?


text:
Q: Java Multidimensional array - how to create multi-dimensional array from regular array elements I have to write a code that will take each element of the one-dimensional array and based on the value of that element create multidimensional array. Every array in the multi-dimensional array will have the column numbers equal to the number on that index in one-dimensional array, and the result should be stored in multi-dimensional array resArray. This is the example of what I am looking for:
this is a start array: int[] arrayStart = new int[]{2, 5, 4, 2, 6, 3};
the result should be:
int[][] resArray = new int[][]{{2 ,2},{5, 5, 5 , 5, 5}, {4, 4, 4, 4}, {2, 2}, {6, 6, 6, 6, 6, 6}, {3, 3, 3}};
I built this so far, but the result is not what I am looking for.
int[] arrayStart = new int[]{2, 5, 4, 2, 6, 3};
    int[][] extendedArray;
    int lengthArray = 0;
    for (int i = 0; i < arrayStart.length; i++) {
        extendedArray = new int[arrayStart.length][arrayStart[i]];
        for (int j = 0; j < arrayStart[i]; j++) {
            lengthArray  = arrayStart[i];
        }
        for (int x = 0; x < lengthArray; x++) {
            extendedArray[i][x] = lengthArray;
        }
            for (int k = 0; k < arrayStart.length; k++) {
                for (int l = 0; l < extendedArray[k].length; l++) {
                    System.out.print(extendedArray[k][l] + "\t");
                }
                System.out.println();
            }
    }

And this is a result I receive when I try to print elements from multi-dimensional array at the end. Just need to figure out how to avoid saving arrays with "0's", and only save ones that have a elements that I am looking for.
2   2
0   0
0   0
0   0
0   0
0   0
0   0   0   0   0
5   5   5   5   5
0   0   0   0   0
0   0   0   0   0
0   0   0   0   0
0   0   0   0   0
0   0   0   0
0   0   0   0
4   4   4   4
0   0   0   0
0   0   0   0
0   0   0   0
0   0
0   0
0   0
2   2
0   0
0   0
0   0   0   0   0   0
0   0   0   0   0   0
0   0   0   0   0   0
0   0   0   0   0   0
6   6   6   6   6   6
0   0   0   0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
0   0   0
3   3   3

A: Be Simple. You have a pretty clear description. Just do it.
public static int[][] createLengthArray(int... arr) {
    // here no need to set row's length
    int[][] res = new int[arr.length][];

    for (int i = 0; i < arr.length; i++) {
        int length = arr[i];
        // 2D array is an 1D array where each element is 1D array
        res[i] = new int[length];
        // standard way to fill an empty array
        Arrays.fill(res[i], length);
    }

    return res;
}

P.S. Look at your code:
for (int i = 0; i < arrayStart.length; i++) {
    extendedArray = new int[arrayStart.length][arrayStart[i]];
    //...
}

Here you create a new 2D array extendedArray on each iteration. That's why you have so many 0s in the output. All you need is to create a result array only once and then fill it in the loop.


text:
Q: extract highest and lowest values for columns in R, as well as row identifiers Say I have some data of the following kind:
df<-as.data.frame(matrix(rnorm(10*10000, 1, .5), ncol=10))

I want a new dataframe that keeps the 10 original columns, but for every column retains only the highest 10 and lowest 10 values. Importantly, the rows have names corresponding to id values that need to be kept in the new data frame.
Thus, the end result data.frame is gonna be of dimensions m by 10, where m is very likely to be more than 20. But for every column, I want only 20 valid values.
The only way I can think of doing this is doing it manually per column, using dplyr and arrange, grabbing the top and bottom rows, and then creating a matrix from all the individual vectors. Clearly this is inefficient. Help?

A: Assuming you want to keep all the rows from the original dataset, where there is at least one value satisfying your condition (value among ten largest or ten smallest in the given column), you could do it like this:
# create a data frame
df<-as.data.frame(matrix(rnorm(10*10000, 1, .5), ncol=10))
# function to find lowes 10 and highest 10 values
lowHigh <- function(x)
{
        test <- x
        test[!(order(x) <= 10 | order(x) >= (length(x)- 10))] <- NA
        test
}
# apply the function defined above
test2 <- apply(df, 2, lowHigh)
# use the original rownames
rownames(test2) <- rownames(df)
# keep only rows where there is value of interest
finalData <- test2[apply(apply(test2, 2, is.na), 1, sum) < 10, ]

Please note that there is definitely some smarter way of doing it...

A: Here is the data matrix with 10 highest and 10 lowest in each column,
x<-apply(df,2,function(k) k[order(k,decreasing=T)[c(1:10,(length(k)-9):length(k))]])

x is your 20 by 10 matrix.
Your requirement of rownames is conflicting column by column, altogether you only have 20 rownames in this matrix and it can not be same for all 10 columns. Instead, here is your order matrix,
x_roworder<-apply(df,2,function(k) order(k,decreasing=T)[c(1:10,(length(k)-9):length(k))])

This will give you corresponding rows in original data matrix within each column.

A: I'm not entirely sure what you're expecting for your return / output. But this will get you the appropriate indices
# example data
set.seed(41234L)
N <- 1000
df<-data.frame(id= 1:N, matrix(rnorm(10*N, 1, .5), ncol=10))

# for each column, extract ID's for top 10 and bottom 10 values
l1 <- lapply(df[,2:11], function(x,y, n) {
  xy <- data.frame(x,y)
  xy <- xy[order(xy[,1]),]
  return(xy[c(1:10, (n-9):n),2])
}, y= df[,1], n = N)

# check:
xx <- sort(df[,2])
all.equal(sort(df[l1[[1]], 2]), xx[c(1:10, 991:1000)])
[1] TRUE

If you want an m * 10 matrix with these unique values, where m is the number of unique indices, you could do:
l2 <- do.call("c", l1)
l2 <- unique(l2)

df2 <- df[l2,] # in this case, m == 189

This doesn't 0 / NA the columns which you're not searching on for each row. But it's unclear what your question is trying to do.
Note
This isn't as efficient as using data.table since you're going to get a copy of the data in xy <- data.frame(x,y)
Benchmark
library(microbenchmark)
microbenchmark(ira= {
  test2 <- apply(df[,2:11], 2, lowHigh);
  rownames(test2) <- rownames(df);
  finalData <- test2[apply(apply(test2, 2, is.na), 1, sum) < 10, ]
},
alex= {
  l1 <- lapply(df[,2:11], function(x,y, n) {
    xy <- data.frame(x,y)
    xy <- xy[order(xy[,1]),]
    return(xy[c(1:10, (n-9):n),2])
  }, y= df[,1], n = N);

  l2 <- unique(do.call("c", l1));
  df2 <- df[l2,]
}, times= 50L)

Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval cld
  ira 4.360452 4.522082 5.328403 5.140874 5.560295 8.369525    50   b
 alex 3.771111 3.854477 4.054388 3.936716 4.158801 5.654280    50  a

A: I offer a couple of answers to this.
A base R implementation ( I have used %>% to make it easier to read)
ix = lapply(df, function(x) order(x)[-(1:(length(x)-20)+10)]) %>%
  unlist %>% unique %>% sort

df[ix,]

This abuses the fact that data frames are lists, finds the row id satisfying the condition for each column, then takes the unique ones in order as the row indices you want to keep. This should retain any row names attached to df
An alternative using dplyr (since you mentioned it) which if I remember correctly doesn't particular like row names
# add id as a variable
df$id = 1:nrow(df) # or row names
df %>%
    gather("col",value,-id) %>%
    group_by(col) %>%
    filter(min_rank(value) <= 10 | min_rank(desc(value)) <= 10) %>%
    ungroup %>%
    select(id) %>%
    left_join(df)

Edited: To fix code alignment and make a neater filter


text:
Q: Dygraph Output Disconnecting Between Adjacent Data Points I am graphing a Dygraph output in a Shiny App, and there are sections of my charts that are not connecting the points between data points.  Does anyone know why certain segments in between time steps in a Dygraph would disconnect?
Thanks!

A: I solved this problem by using the connectSeparatedPoints option for Dygraphs.  For example, here is the code I am using to show my dygraph:
dygraph(component, main = "Temperature Rise Data Plot") %>%
      dyAxis("y", label = "Temp (F)") %>%
      dyAxis("x", label = "Time (min)")%>%
      dyRangeSelector() %>%
      dyOptions(colors = RColorBrewer::brewer.pal(8, "Dark2"), connectSeparatedPoints = TRUE)


text:
Q: Trying to Implement here-map in ionic 6 but it gives `403` error and I couldn't able found any solution I have been trying to implement here-map in Ionic 6 and angular version 13.0.0 and I got a 403 error so please help me to solve it.
index.html
  <script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>

Home.page.ts
import { Component, ElementRef, ViewChild } from '@angular/core';
declare var H: any;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  @ViewChild("map", { static: true }) public mapElement: ElementRef;
  private platform: any;

  lat = 28.610001;
  lng = 77.230003;

  public width: any = '100vw';
  public height: any = '90vh';

  private map: any;

  private _apikey: string = "API_KEY";

  public query: string;

  public address: string = '';
  constructor() { }

  ngOnInit(): void {
    this.platform = new H.service.Platform({
      "apikey": this._apikey,
    });
  }

  ngAfterViewInit() {
    let defaultLayers = this.platform.createDefaultLayers();
    let map = new H.Map(
      this.mapElement.nativeElement,
      defaultLayers.vector.normal.map,
      {
        zoom: 5,
        center: { lat: this.lat, lng: this.lng },
      }
    );
  }
}

Home.page.html
<ion-content [fullscreen]="false">
  <div #map [style.width]="width" [style.height]="height"></div>
</ion-content>