问:
How to disambiguate a plpgsql variable name in a ON CONFLICT clause?
Given this table:

```<code>create table test (
    name text primary key
);
</code>```

I need to write a plpgsql function with a variable name that collides with the primary key name, which I must use in a on conflict clause:

```<code>create or replace function func(
    name text                               -- this variable name...
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict (name) do update            -- ...conflicts with this line
    set name = func.name;
end;
$$;
</code>```

This compiles, but then throws an ambiguous column reference:

```<code>select * from func('one');
ERROR:  column reference "name" is ambiguous
LINE 2:     on conflict (name) do update
                        ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  insert into test (name) values (name)
    on conflict (name) do update
    set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement
</code>```

I tried specifying the full column name as on conflict (test.name) which does not compile, or ((test.name)) which compiles:

```<code>create or replace function func(
    name text
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict ((test.name)) do            -- this fails too
    update set name = func.name;
end;
$$;
</code>```

But it fails as well:

```<code>select * from func('two');
ERROR:  invalid reference to FROM-clause entry for table "test"
LINE 2:     on conflict ((test.name)) do
                          ^
HINT:  There is an entry for table "test", but it cannot be referenced from this part of the query.
QUERY:  insert into test (name) values (name)
    on conflict ((test.name)) do
    update set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement
</code>```

Is there a solution?

Edit: I found a workaround:

```<code>on conflict on constraint test_pkey do update
</code>```

where test_pkey is the table name plus _pkey. I don't know how reliable this is though. I'd still like to specify the column name instead.

答:
to start with, name is a bad name for both variable and attribute. When you have both, code won't look good. with that in mind, you can "prefix" variable with labeled block (in example below <<fn>>``), and setvariable_conflict` to give preference to column name, see code below:

```<code>t=# create or replace function func(
    name text
) returns void language plpgsql as
$$
#variable_conflict use_column
<<fn>>
declare name text :='blah';
begin
    insert into test (name) values (name)
    on conflict (name) do            -- this no longer fails
    update set name = fn.name;
end;
$$;
t=# insert into test select 'b';
INSERT 0 1
Time: 8.076 ms
t=# select func('b');
 func
------

(1 row)

Time: 6.117 ms
t=# select * from test;
 name
------
 b
 blah
(2 rows)
</code>```

https://www.postgresql.org/docs/current/static/plpgsql-implementation.html#PLPGSQL-VAR-SUBST

By default, PL/pgSQL will report an error if a name in a SQL statement
  could refer to either a variable or a table column. You can fix such a
  problem by renaming the variable or column, or by qualifying the
  ambiguous reference, or by telling PL/pgSQL which interpretation to
  prefer.

and further - basically the whole link is about it.

And yet - after demonstrating how particular task this can be easily done with plpgsql, I still quote namual:

The simplest solution is to rename the variable or column. A common
  coding rule is to use a different naming convention for PL/pgSQL
  variables than you use for column names. For example, if you
  consistently name function variables v_something while none of your
  column names start with v_, no conflicts will occur.

Body:
Given this table:

create table test (
    name text primary key
);

I need to write a plpgsql function with a variable name that collides with the primary key name, which I must use in a on conflict clause:

create or replace function func(
    name text                               -- this variable name...
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict (name) do update            -- ...conflicts with this line
    set name = func.name;
end;
$$;

This compiles, but then throws an ambiguous column reference:

select * from func('one');
ERROR:  column reference "name" is ambiguous
LINE 2:     on conflict (name) do update
                        ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  insert into test (name) values (name)
    on conflict (name) do update
    set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement

I tried specifying the full column name as on conflict (test.name) which does not compile, or ((test.name)) which compiles:

create or replace function func(
    name text
) returns void language plpgsql as
$$
begin
    insert into test (name) values (name)
    on conflict ((test.name)) do            -- this fails too
    update set name = func.name;
end;
$$;

But it fails as well:

select * from func('two');
ERROR:  invalid reference to FROM-clause entry for table "test"
LINE 2:     on conflict ((test.name)) do
                          ^
HINT:  There is an entry for table "test", but it cannot be referenced from this part of the query.
QUERY:  insert into test (name) values (name)
    on conflict ((test.name)) do
    update set name = func.name
CONTEXT:  PL/pgSQL function func(text) line 3 at SQL statement

Is there a solution?

Edit: I found a workaround:

on conflict on constraint test_pkey do update

where test_pkey is the table name plus _pkey. I don't know how reliable this is though. I'd still like to specify the column name instead.

Body:
to start with, name is a bad name for both variable and attribute. When you have both, code won't look good. with that in mind, you can "prefix" variable with labeled block (in example below <<fn>>``), and setvariable_conflict` to give preference to column name, see code below:

t=# create or replace function func(
    name text
) returns void language plpgsql as
$$
#variable_conflict use_column
<<fn>>
declare name text :='blah';
begin
    insert into test (name) values (name)
    on conflict (name) do            -- this no longer fails
    update set name = fn.name;
end;
$$;
t=# insert into test select 'b';
INSERT 0 1
Time: 8.076 ms
t=# select func('b');
 func
------

(1 row)

Time: 6.117 ms
t=# select * from test;
 name
------
 b
 blah
(2 rows)

https://www.postgresql.org/docs/current/static/plpgsql-implementation.html#PLPGSQL-VAR-SUBST

By default, PL/pgSQL will report an error if a name in a SQL statement
  could refer to either a variable or a table column. You can fix such a
  problem by renaming the variable or column, or by qualifying the
  ambiguous reference, or by telling PL/pgSQL which interpretation to
  prefer.

and further - basically the whole link is about it.

And yet - after demonstrating how particular task this can be easily done with plpgsql, I still quote namual:

The simplest solution is to rename the variable or column. A common
  coding rule is to use a different naming convention for PL/pgSQL
  variables than you use for column names. For example, if you
  consistently name function variables v_something while none of your
  column names start with v_, no conflicts will occur.


来源: stackexchange

问:
cant change array elements globally
currently im working on a ethereum dapp. i have a solidity file as below

```<code>pragma solidity ^0.4.11;
contract ArrayOfBytes32 {
    address creator;
    bytes32[10] bytesArray; // size must be fixed

    function getArray() constant returns (bytes32[10])
    {uint8 x = 0;
        while(x < bytesArray.length)
        {
            bytesArray[x] = "myString";
            x++;
        }
        return bytesArray;
    }

    function getValue(uint8 x) constant returns (bytes32)
    {
        return bytesArray[x];
    }
}
</code>```

in this function getArray() returns correctly. But function getValue() always returning default value ie 0000000.
changes made in getArray() are not reflected !! any solutions

答: Remove the constant modifier from getArray(). constant functions do not write state to the blockchain.

ContentLicense: CC BY-SA 3.0

Title: cant change array elements globally

Body:
currently im working on a ethereum dapp. i have a solidity file as below

pragma solidity ^0.4.11;
contract ArrayOfBytes32 {
    address creator;
    bytes32[10] bytesArray; // size must be fixed

    function getArray() constant returns (bytes32[10])
    {uint8 x = 0;
        while(x < bytesArray.length)
        {
            bytesArray[x] = "myString";
            x++;
        }
        return bytesArray;
    }

    function getValue(uint8 x) constant returns (bytes32)
    {
        return bytesArray[x];
    }
}

in this function getArray() returns correctly. But function getValue() always returning default value ie 0000000.
changes made in getArray() are not reflected !! any solutions


问:
How to open a .img/.rrd satellite image in Matlab?
I have a couple of multispectral satellite images which are in .img/.rrd format and I want to oopen them in Matlab for further processing.</p>

答: I'm not sure Matlab can recognise .img /.rdd files directly, but you could try using ImageJ or Fiji to convert your .img files to one of the image formats that is accepted. e.g. tiff, png, bmp, jpeg. The list of accepted formats can be found by typing 'imformats' in the command line.</p>


问:
why i am not able to view with classbased (list view )but for function based view it is working fine?

My question: why i am not able to view search only ayan rand's book with classbased list view?

this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine.

But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted .

Views.py:

```<code>from django.shortcuts import render, get_object_or_404
from django.http import  HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView

def store_listView(request,):
      queryset=Book.objects.all()

      context={
           "objects_list":queryset
      }
      return render(request,'bookstores/store.html',context)

class SearchBookDetail(ListView):
    template_name = "bookstores/store.html"
    queryset = Book.objects.filter(author__icontains='Ayan Rand')
    print("Ayan Rand query set", queryset)
</code>```

Urls.py:

```<code> from django.conf.urls import url
 from django.contrib import admin
 from django.views.generic import TemplateView
 from store.views import (Home,ContactView,LoginView,
                     store_listView,
                     SearchBookDetail,
                     book_createview,
                     QuoteslistView,
                    AyanRandBookDetail,
                     quotesFunctionView)

 urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'^$',Home.as_view()),
   url(r'^contact/$',ContactView.as_view()),
   url(r'^login/$',LoginView.as_view()),
   url(r'^store/$',store_listView),
   url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()),
   url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()),
   url(r'^quotes/$',quotesFunctionView)]
</code>```

store.html:

```<code> {% extends "home.html" %}
 {% block head_title %}Store || {{ block.super }} {% endblock head_title %}
 {% block content %}
 <head>
   <meta charset="UTF-8">
   <title>Store</title>
 </head>

 <h6>Books available</h6>
 <ul>
   {% for obj in objects_list %}
   <li>{{obj}}<br>
    {{obj.book_image}} <br>
    {{obj.description}} <br>
    {{obj.author}}<br>
    {{obj.genre}}<br>
    {{obj.price}}<br>
    </li>

   {% endfor %}
</ul>

{% endblock content %}
</code>```

答: ListView sends its data to the template as object_list, not objects_list.

Body:
My question: why i am not able to view search only ayan rand's book with classbased list view?

this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine.

But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted .

Views.py:

from django.shortcuts import render, get_object_or_404
from django.http import  HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView

def store_listView(request,):
      queryset=Book.objects.all()

      context={
           "objects_list":queryset
      }
      return render(request,'bookstores/store.html',context)

class SearchBookDetail(ListView):
    template_name = "bookstores/store.html"
    queryset = Book.objects.filter(author__icontains='Ayan Rand')
    print("Ayan Rand query set", queryset)

Urls.py:

 from django.conf.urls import url
 from django.contrib import admin
 from django.views.generic import TemplateView
 from store.views import (Home,ContactView,LoginView,
                     store_listView,
                     SearchBookDetail,
                     book_createview,
                     QuoteslistView,
                    AyanRandBookDetail,
                     quotesFunctionView)

 urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'^$',Home.as_view()),
   url(r'^contact/$',ContactView.as_view()),
   url(r'^login/$',LoginView.as_view()),
   url(r'^store/$',store_listView),
   url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()),
   url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()),
   url(r'^quotes/$',quotesFunctionView)]

store.html:

 {% extends "home.html" %}
 {% block head_title %}Store || {{ block.super }} {% endblock head_title %}
 {% block content %}

   <meta charset="UTF-8">
   <title>Store</title>

Books available

   {% for obj in objects_list %}

{{obj}}

    {{obj.book_image}}

    {{obj.description}}

    {{obj.author}}

    {{obj.genre}}

    {{obj.price}}

   {% endfor %}

{% endblock content %}


问:
How to do str_extract with base R?
I am balancing several versions of R and want to change my R libraries loaded depending on which R and which operating system I'm using. As such, I want to stick with base R functions.

I was reading this page to see what the base R equivalent to stringr::str_extract was:

http://stat545.com/block022_regular-expression.html

It suggested I could replicate this functionality with grep. However, I haven't been able to get grep to do more than return the whole string if there is a match. Is this possible with grep alone, or do I need to combine it with another function? In my case I'm trying to distinguish between CentOS versions 6 and 7.

```<code>grep(pattern = "release ([0-9]+)", x = readLines("/etc/system-release"), value = TRUE)
</code>```

答:
1) strcapture If you want to extract a string of digits and dots from "release 1.2.3" using base then

```<code>x <- "release 1.2.3"
strcapture("([0-9.]+)", x, data.frame(version = character(0)))
##   version
## 1   1.2.3
</code>```

2) regexec/regmatches There is also regmatches and regexec but that has already been covered in another answer.

3) sub Also it is often possible to use sub:

```<code>sub(".* ([0-9.]+).*", "\\1", x)
## [1] "1.2.3"
</code>```

3a) If you know the match is at the beginning or end then delete everything after  or before it:

```<code>sub(".* ", "", x)
## [1] "1.2.3"
</code>```

4) gsub Sometimes we know that the field to be extracted has certain characters and they do not appear elsewhere.  In that case simply delete every occurrence of every character that cannot be in the string:

```<code>gsub("[^0-9.]", "", x)
## [1] "1.2.3"
</code>```

5) read.table One can often decompose the input into fields and then pick off the desired one by number or via grep.  strsplit, read.table or scan can be used:

```<code>read.table(text = x, as.is = TRUE)[[2]]
## [1] "1.2.3"
</code>```

5a) grep/scan

```<code>grep("^[0-9.]+$", scan(textConnection(x), what = "", quiet = TRUE), value = TRUE)
## [1] "1.2.3"
</code>```

5b) grep/strsplit

```<code>grep("^[0-9.]+$", strsplit(x, " ")[[1]], value = TRUE)
## [1] "1.2.3"
</code>```

6) substring If we know the character position of the field we can use substring like this:

```<code>substring(x, 9)
## [1] "1.2.3"
</code>```

6a) substring/regexpr or we may be able to use regexpr to locate the character position for us:

```<code>substring(x, regexpr("\\d", x))
## [1] "1.2.3"
</code>```

7) read.dcf Sometimes it is possible to convert the input to dcf form in which case it can be read with read.dcf.  Such data is of the form name: value

```<code> read.dcf(textConnection(sub(" ", ": ", x)))
 ##      release
 ## [1,] "1.2.3"
</code>```

Title: How to do str_extract with base R?

Body:
I am balancing several versions of R and want to change my R libraries loaded depending on which R and which operating system I'm using. As such, I want to stick with base R functions.

I was reading this page to see what the base R equivalent to stringr::str_extract was:

http://stat545.com/block022_regular-expression.html

It suggested I could replicate this functionality with grep. However, I haven't been able to get grep to do more than return the whole string if there is a match. Is this possible with grep alone, or do I need to combine it with another function? In my case I'm trying to distinguish between CentOS versions 6 and 7.

grep(pattern = "release ([0-9]+)", x = readLines("/etc/system-release"), value = TRUE)

Body:
1) strcapture If you want to extract a string of digits and dots from "release 1.2.3" using base then

x <- "release 1.2.3"
strcapture("([0-9.]+)", x, data.frame(version = character(0)))
##   version
## 1   1.2.3

2) regexec/regmatches There is also regmatches and regexec but that has already been covered in another answer.

3) sub Also it is often possible to use sub:

sub(".* ([0-9.]+).*", "\\1", x)
## [1] "1.2.3"

3a) If you know the match is at the beginning or end then delete everything after  or before it:

sub(".* ", "", x)
## [1] "1.2.3"

4) gsub Sometimes we know that the field to be extracted has certain characters and they do not appear elsewhere.  In that case simply delete every occurrence of every character that cannot be in the string:

gsub("[^0-9.]", "", x)
## [1] "1.2.3"

5) read.table One can often decompose the input into fields and then pick off the desired one by number or via grep.  strsplit, read.table or scan can be used:

read.table(text = x, as.is = TRUE)[[2]]
## [1] "1.2.3"

5a) grep/scan

grep("^[0-9.]+$", scan(textConnection(x), what = "", quiet = TRUE), value = TRUE)
## [1] "1.2.3"

5b) grep/strsplit

grep("^[0-9.]+$", strsplit(x, " ")[[1]], value = TRUE)
## [1] "1.2.3"

6) substring If we know the character position of the field we can use substring like this:

substring(x, 9)
## [1] "1.2.3"

6a) substring/regexpr or we may be able to use regexpr to locate the character position for us:

substring(x, regexpr("\\d", x))
## [1] "1.2.3"

7) read.dcf Sometimes it is possible to convert the input to dcf form in which case it can be read with read.dcf.  Such data is of the form name: value

 read.dcf(textConnection(sub(" ", ": ", x)))
 ##      release
 ## [1,] "1.2.3"


问:
How create client in whmcs when a new client is created in freshbooks?
I want to make a client in WHMCS when a new client is added to FreshBooks. The reverse I have done successfully. Basically I want to sync clients from FreshBooks to WHMCS. Where is the webhook topic in new FreshBooks API?</p>

答:
I'm currently working at FreshBooks - we recently added Webhooks to the new FreshBooks API, and you can see the documentation for this here.

You should be able to register for client create, update, etc, no problem!


问:
Undoable sets of changes
I'm looking for a way to manage consistent sets of changes across several data sources, including, but not limited to, a database, some network control tools, and probably other SOAP-based services.

If one change fails for some reason (e.g. real-world app says "no", or a database insert fails), I want the whole set to be undone. So that's like transactions, just not limited to a DB.

I came up with a module that stacks up "change" objects which in turn have their init, commit, and rollback methods. When the set is DESTROYed, it rolls uncommitted changes back. This kinda works.

Still I can't overcome the feeling of a wheel being invented. Is there a standard CPAN module, or a well described common method to perform such a task? (At least GoF's "command" pattern and RAII principle come to mind...)

答:
There are a couple of approaches to executing a Distributed transaction (which is what you're describing):

The standard pattern is called "Two-phase commit protocol".

At the moment I'm not aware of any Perl module which implements Two-phase commit, which is kind of surprising and may likely be due to a lapse in my Googling. The only thing I found was Env::Transaction but I have no clue how stable/good/functional it is.

For certain cases, a solution involving rollback via "Compensating transactions" is possible.

This is basically a special case of general rollback where, when generating task list A designed to change the target system state from S1 to S2, you at the same time generate a "compensating" task list A-neg designed to change the target system state from S2 back to S1. This is obviously only possible for certain systems, and moreover only a small subset of those are commutative (meaning that your can execute both transaction and its compensating transaction non-contiguously, e.g. the result of A + B + A-neg + B-neg is an invariant state.

Please notice that the compensating transactions does NOT always have to be engineered to be a "transaction" - one clever approach (again, only possible on certain subject domains) involves storing your data with a special "finalized" flag; then periodically harvest and destroy data with a false "finalized" flag if the data's "originating transaction timestamp" is older than some sort of threshold.

ContentLicense: CC BY-SA 2.5

Title: Undoable sets of changes


问:
Is there any algorithm for covering a concave polygon(contains holes) with convex polygons
This can be approached in two ways :

i)  by partitioning the given polygon into convex polygons such that there is no
    overlap between the convex polygons

ii) by covering the given polygon using convex polygons such that their union
    gives the original polygon. In this case there can be overlap between
    the convex polygons

Although partitioning covers the entire polygon, number of convex polygons can be reduced by second approach. It is also known that covering a concave polygon(second approach) with minimal number of convex polygons is NP-Hard.

I'm specifically looking for algorithms based on second approach mentioned above,but number of convex polygons may not be minimal.

答:
As already mentioned by MBo and Yves Daoust in the comments to your questions. Polygon decomposition into convex polygons can be done by triangulation (or trapezoidal decomposition). This will result for an n vertex simple polygon P with n-2 (interior) triangles, i.e., is linear in the number of vertices.

Another way to construct a convex decomposition would be to use a generalized motorcycle graph. I would assume there must be a simpler way though!
The main idea is to start a motorcycle m for every reflex vertex r in P. Every motorcycle m drives with a given speed in a given direction and leaves a trace behind. If another motorcycle meets such a trace it crashes, i.e., stops but leaves the trace.
Generalized refers to the embedding in P and that the polygon boundaries function as walls where the motorcycles also crash. Furthermore if two motorcycles meet at the same point we have to start another one, or in this case just continue with one and stop the other. After all motorcycles have crashed there is the graph of the traces which in fact is a convex tessellation of P. There are several papers (one here) on this but implementation would be tough. This results in O(r) convex polygons that cover the interior of P.

I think the easiest way is to go with the triangulation or trapezoidal decomposition. These are well studied and available as implementation in many libraries.

Also mentioned in the comments: Input can be produced that will force O(n) polygons. Just think of a star shaped polygon that has n/2 reflex vertices (interior angle > pi).


问:
How to get total result set size on a group_by count query?
I have the following query within my model:

```<code>Post.where("created_utc > ? AND lower(category) = ?", 0, 'videos').group(:domain).order('count_all desc').page(1).per(25).count
</code>```

I'm using the kaminari gem for pagination but the problem is this: this query returns what appears to be a sorted hash. However I have no way of knowing what the total result count is.

If you prefer not to take kaminari into consideration, you can reference the following query:

```<code>Post.where("created_utc > ? AND lower(category) = ?", min_time, subreddit.downcase).group(:domain).order('count_all desc').limit(limit).offset(start).count
</code>```

Regardless, I have no way of figuring out what the total number of results is. How can I go about resolving this? Is there some way to figure out what the total result set size would be without the limit?

答:
What you want is .length instead of .count, like this:

```<code>Post.where("created_utc > ? AND lower(category) = ?", 0, 'videos').group(:domain).order('count_all desc').page(1).per(25).length
</code>```

.count performs a SQL COUNT

.length calculates the length of the resultant array

courtesy of @BenHawker at https://stackoverflow.com/a/34541020/380607

Body:
I have the following query within my model:

Post.where("created_utc > ? AND lower(category) = ?", 0, 'videos').group(:domain).order('count_all desc').page(1).per(25).count

I'm using the kaminari gem for pagination but the problem is this: this query returns what appears to be a sorted hash. However I have no way of knowing what the total result count is.

If you prefer not to take kaminari into consideration, you can reference the following query:

Post.where("created_utc > ? AND lower(category) = ?", min_time, subreddit.downcase).group(:domain).order('count_all desc').limit(limit).offset(start).count

Regardless, I have no way of figuring out what the total number of results is. How can I go about resolving this? Is there some way to figure out what the total result set size would be without the limit?

Body:
What you want is .length instead of .count, like this:

Post.where("created_utc > ? AND lower(category) = ?", 0, 'videos').group(:domain).order('count_all desc').page(1).per(25).length

.count performs a SQL COUNT

.length calculates the length of the resultant array

courtesy of @BenHawker at https://stackoverflow.com/a/34541020/380607


问:
firebase dynamic link created programmatically in swift doesn't work, no domain
I have configured firebase project with dynamic link, I have domain for DL. But when I creating shroten link programmatically then I get an error. This error I receive for target test and debug of project, but same code is using for release app and for it dynamic link works. Each project target have own firebase project and domain. I don't know why works only release version ?</p>

```<code>Your project does not own Dynamic Links domain
</code>```

答:
Try this command line with your bundleID, app_code and API key:

curl -X POST --dump-header - -H "X-Ios-Bundle-Identifier:
  REPLACE_THIS_WITH_YOUR_BUNDLE_ID” -H "Accept: application/json" -H
  "Content-Type: application/json" -d
  "{\"longDynamicLink\":\"https://REPLACE_THIS_WITH_YOUR_APP_CODE.app.goo.gl/?link=https%3A%2F%2Fwww%2Egoogle%2Ecom%3Fq%3Djump\",\"suffix\":{\"option\":\"UNGUESSABLE\"}}"
  "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=REPLACE_THIS_WITH_YOUR_API_KEY”

Let me know how it worked.

If this line was able to create short link, than  error in iOS code.

Body:
I have configured firebase project with dynamic link, I have domain for DL. But when I creating shroten link programmatically then I get an error. This error I receive for target test and debug of project, but same code is using for release app and for it dynamic link works. Each project target have own firebase project and domain. I don't know why works only release version ?

Your project does not own Dynamic Links domain


问:
Is this code drawing at the point or pixel level? How to draw retina pixels?
Consider this admirable script which draws a (circular) gradient,

https://github.com/paiv/AngleGradientLayer/blob/master/AngleGradient/AngleGradientLayer.m

```<code>int w = CGRectGetWidth(rect);
int h = CGRectGetHeight(rect);
</code>```

and then

```<code>angleGradient(data, w, h ..
</code>```

and the it loops over all those

```<code>for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
</code>```

basically setting the color

```<code>    *p++ = color;
</code>```

But wait - wouldn't this be working by points, not pixels?

How, really, would you draw to the physical pixels on dense screens?

Is it a matter of:

Let's say the density is 4 on the device. Draw just as in the above code, but, on a bitmap four times as big, and then put it in the rect?

That seems messy - but is that it?

答:
What it sounds like you are looking for is the scale property on UIScreen:

https://developer.apple.com/documentation/uikit/uiscreen/1617836-scale

This allows you to control the number of pixels the coordinate system gives you per virtual pixel. iOS devices basically work at non retina coordinates. Old link explaining what is going on here:

http://www.daveoncode.com/2011/10/22/right-uiimage-and-cgimage-pixel-size-retina-display/

Don't use his macros, as some devices are now scale of 3.0, but the post explains what is going on.

Body:
Consider this admirable script which draws a (circular) gradient,

https://github.com/paiv/AngleGradientLayer/blob/master/AngleGradient/AngleGradientLayer.m

int w = CGRectGetWidth(rect);
int h = CGRectGetHeight(rect);

and then

angleGradient(data, w, h ..

and the it loops over all those

for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {

basically setting the color

    *p++ = color;

But wait - wouldn't this be working by points, not pixels?

How, really, would you draw to the physical pixels on dense screens?

Is it a matter of:

Let's say the density is 4 on the device. Draw just as in the above code, but, on a bitmap four times as big, and then put it in the rect?

That seems messy - but is that it?


问:
Jumping between object code with different (and unknown) calling convention in C
I have (mapped in memory) two object files, "A.o" and "B.o", with the same CPU Instruction Set (not necessarily Intel --it can be x86, x86_64, MIPS(32/64), ARM(32/64), PowerPC(32/64),..., but always the same in both object files).

Also, both object files are compiled with the same endianness (both little endian, or both big endian).

However (you knew there was a however, otherwise there wouldn't be any question), "A.o" and "B.o" can have a different function calling convention and, to make things worse, unknown to each other ("A.o" has not even the slightest idea about the calling convention for functions in "B.o", and vice versa).

"A.o" and "B.o" are obviously designed to call functions within their same object file, but there must be a (very) limited interface for communicating between them (otherwise, if execution starts at some function in "A.o", no function from "B.o" would ever be executed if there was no such interface).

The file where execution started (let's suppose it's "A.o") knows the addresses of all static symbols from "B.o" (the addresses of all functions and all global variables). But the opposite is not true (well, the limited interface I'm trying to write would overcome that, but "B.o" doesn't know any address from "A.o" before such interface is established).

Finally the question: How can execution jump from a function in "A.o" to a function in "B.o", and back, while also communicating some data?

I need it to:

Be done in standard C (no assembly).

Be portable C (not compiler-dependent, nor CPU-dependent).

Be thread safe.

Don't make any assumption about the calling conventions involved.

Be able to communicate data between the two object files.

My best idea, for the moment, seems that can meet all these requirements, except thread safety. For example, if I define an struct like this:

```<code>struct data_interface {
   int value_in;
   int value_out; };
</code>```

I could write a pointer to an struct like this from "A.o" into a global variable of "B.o" (knowing in advance that such global variable in "B.o" has space enough for storing a pointer).

Then, the interface function would be a void interface(void) (I'm assuming that calling void(void) functions is safe across different calling conventions... if this is not true, then my idea wouldn't work). Calling such a function from "A.o" to "B.o" would communicate the data to the code in "B.o". And, fingers crossed, when the called function in "B.o" returns, it would travel back nicely (supposing the different calling convention doesn't change the behaviour when returning from void(void) functions).

However, this is not thread safe, of course.

For it to be thread safe, I guess my only option is to access the stack.

But... can the stack be accessed in a portable way in standard C?

答:
Here are two suggestions.

Data interface

This elaborates on the struct you defined yourself. From what I've seen in the past, compilers typically use a single register (e.g. eax) for their return value (provided the return type fits in a register). My guess is, the following function prototype is likely to be unaffected by differing calling conventions.

```<code>struct data_interface *get_empty_data_interface(void);
</code>```

If so, then you could use that in a way that is similar to the idea you already had about using arrays. Define the following struct and functions in B:

```<code>struct data_interface {
    int ready;
    int the_real_data;
};

struct data_interface *get_empty_data_interface(void)
{
    struct data_interface *ptr = malloc(sizeof(struct data_interface));
    add_to_list_of_data_block_pointers(ptr);
    ptr->ready = 0;
    return ptr;
}

void the_function(void)
{
    execute_functionality_for_every_data_block_in_my_list_that_is_flagged_ready_and_remove_from_list();
}
</code>```

To call the function, do this in A:

```<code>struct data_interface *ptr = get_empty_data_interface();
ptr->the_real_data = 12345;
ptr->ready = 1;
the_function();
</code>```

For thread-safety, make sure the list of data blocks maintained by B is thread-safe.

Simultaneous calls to get_empty_data_interface should not overwrite each other's slot in the list.

Simultaneous calls to the_function should not both pick up the same list element.

Wrapper functions

You could try to expose wrapper functions with a well-known calling convention (e.g. cdecl); if necessary defined in a separate object file that is aware of the calling convention of the functions it wraps.

Unfortunately you will probably need non-portable function attributes for this.

You may be able to cheat your way out of it by declaring variadic wrapper functions (with an ellipsis parameter, like printf has); compilers are likely to fall back on cdecl for those. This eliminates non-portable function attributes, but it may be unreliable; you would have to verify my assumption for every compiler you'd like to support. When testing this, keep in mind that compiler options (in particular optimizations) may well play a role. All in all, quite a dirty approach.

Body:
I have (mapped in memory) two object files, "A.o" and "B.o", with the same CPU Instruction Set (not necessarily Intel --it can be x86, x86_64, MIPS(32/64), ARM(32/64), PowerPC(32/64),..., but always the same in both object files).

Also, both object files are compiled with the same endianness (both little endian, or both big endian).

However (you knew there was a however, otherwise there wouldn't be any question), "A.o" and "B.o" can have a different function calling convention and, to make things worse, unknown to each other ("A.o" has not even the slightest idea about the calling convention for functions in "B.o", and vice versa).

"A.o" and "B.o" are obviously designed to call functions within their same object file, but there must be a (very) limited interface for communicating between them (otherwise, if execution starts at some function in "A.o", no function from "B.o" would ever be executed if there was no such interface).

The file where execution started (let's suppose it's "A.o") knows the addresses of all static symbols from "B.o" (the addresses of all functions and all global variables). But the opposite is not true (well, the limited interface I'm trying to write would overcome that, but "B.o" doesn't know any address from "A.o" before such interface is established).

Finally the question: How can execution jump from a function in "A.o" to a function in "B.o", and back, while also communicating some data?

I need it to:

Be done in standard C (no assembly).

Be portable C (not compiler-dependent, nor CPU-dependent).

Be thread safe.

Don't make any assumption about the calling conventions involved.

Be able to communicate data between the two object files.

My best idea, for the moment, seems that can meet all these requirements, except thread safety. For example, if I define an struct like this:

struct data_interface {
   int value_in;
   int value_out; };

I could write a pointer to an struct like this from "A.o" into a global variable of "B.o" (knowing in advance that such global variable in "B.o" has space enough for storing a pointer).

Then, the interface function would be a void interface(void) (I'm assuming that calling void(void) functions is safe across different calling conventions... if this is not true, then my idea wouldn't work). Calling such a function from "A.o" to "B.o" would communicate the data to the code in "B.o". And, fingers crossed, when the called function in "B.o" returns, it would travel back nicely (supposing the different calling convention doesn't change the behaviour when returning from void(void) functions).

However, this is not thread safe, of course.

For it to be thread safe, I guess my only option is to access the stack.

But... can the stack be accessed in a portable way in standard C?

Body:
Here are two suggestions.

Data interface

This elaborates on the struct you defined yourself. From what I've seen in the past, compilers typically use a single register (e.g. eax) for their return value (provided the return type fits in a register). My guess is, the following function prototype is likely to be unaffected by differing calling conventions.

struct data_interface *get_empty_data_interface(void);

If so, then you could use that in a way that is similar to the idea you already had about using arrays. Define the following struct and functions in B:

struct data_interface {
    int ready;
    int the_real_data;
};

struct data_interface *get_empty_data_interface(void)
{
    struct data_interface *ptr = malloc(sizeof(struct data_interface));
    add_to_list_of_data_block_pointers(ptr);
    ptr->ready = 0;
    return ptr;
}

void the_function(void)
{
    execute_functionality_for_every_data_block_in_my_list_that_is_flagged_ready_and_remove_from_list();
}

To call the function, do this in A:

struct data_interface *ptr = get_empty_data_interface();
ptr->the_real_data = 12345;
ptr->ready = 1;
the_function();

For thread-safety, make sure the list of data blocks maintained by B is thread-safe.

Simultaneous calls to get_empty_data_interface should not overwrite each other's slot in the list.

Simultaneous calls to the_function should not both pick up the same list element.

Wrapper functions

You could try to expose wrapper functions with a well-known calling convention (e.g. cdecl); if necessary defined in a separate object file that is aware of the calling convention of the functions it wraps.

Unfortunately you will probably need non-portable function attributes for this.

You may be able to cheat your way out of it by declaring variadic wrapper functions (with an ellipsis parameter, like printf has); compilers are likely to fall back on cdecl for those. This eliminates non-portable function attributes, but it may be unreliable; you would have to verify my assumption for every compiler you'd like to support. When testing this, keep in mind that compiler options (in particular optimizations) may well play a role. All in all, quite a dirty approach.


问:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined on jQuery function
I have this jQuery script in a page

```<code>$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "/notification/unread",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
      $("#notification_badge").html(data).removeClass("hidden");
    }
  });
</code>```

However I'm getting an error on the subject when calling the $.ajax function:

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined on jQuery function

This is what i find in the console

```<code>Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
    at Object.setRequestHeader (jquery.min.js:4)
    at HTMLDocument.<anonymous> (badge.js:5)
    at HTMLDocument.dispatch (jquery.min.js:3)
    at HTMLDocument.r.handle (jquery.min.js:3)
    at Object.trigger (jquery.min.js:3)
    at Function.ajax (jquery.min.js:4)
    at badge.js:10
    at dispatch (jquery.min.js:3)
    at r.handle (jquery.min.js:3)
</code>```

The POST call is not made. Where is the error?

答:
Try changing the function definition to ES6 standard. From this

```<code>$(document).ready(function() {});
</code>```

to this

```<code>$(document).ready(() =>{});
</code>```

Body:
I have this jQuery script in a page

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "/notification/unread",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
      $("#notification_badge").html(data).removeClass("hidden");
    }
  });

However I'm getting an error on the subject when calling the $.ajax function:

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined on jQuery function

This is what i find in the console

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
    at Object.setRequestHeader (jquery.min.js:4)
    at HTMLDocument.<anonymous> (badge.js:5)
    at HTMLDocument.dispatch (jquery.min.js:3)
    at HTMLDocument.r.handle (jquery.min.js:3)
    at Object.trigger (jquery.min.js:3)
    at Function.ajax (jquery.min.js:4)
    at badge.js:10
    at dispatch (jquery.min.js:3)
    at r.handle (jquery.min.js:3)

The POST call is not made. Where is the error?

Body:
Try changing the function definition to ES6 standard. From this

$(document).ready(function() {});

to this

$(document).ready(() =>{});


问:
TCPDF email error
I use TCPDF to send pdf as an attachment. I do receive the email, so the email works, but there is no attachment.

In the email I receive a very long scrambled message. If I remove $data (as in code below) the content of the message is much less, but still no attachment.

```<code><?php
//This file create a pd contract agreement based on the client's detail.
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
require_once('connect.php');

//Connect and get information

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$findaccount = $conn->prepare("SELECT * from Table'");

$findaccount->execute();

//Variable list here and working

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Me');
$pdf->SetTitle('My Title');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' ', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}

 // ---------------------------------------------------------

/*
 NOTES:
 - To create self-signed signature: openssl req -x509 -nodes -days 365000       -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
- To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
 - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
 */

// set certificate file
$certificate = 'file://data/cert/tcpdf.crt';

// set additional information
$info = array(
'Name' => 'My Site',
'Location' => 'Address',
'Reason' => 'Because',
'ContactInfo' => 'https://www.example.com',
);

// set document signature
$pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2,    $info);

// set font
$pdf->SetFont('helvetica', '', 7);

// add a page
$pdf->AddPage();

// print a line of text
$text = "<html><head></head><body>
<b>HTML DISPLAY HERE</b>
<br>
<br>

</body></html>
";

$pdf->writeHTML($text, true, 0, true, 0);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// *** set signature appearance ***

// create content for signature (image and/or text)

// define active area for signature appearance
$pdf->setSignatureAppearance(180, 60, 15, 15);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// *** set an empty signature appearance ***
$pdf->addEmptySignatureAppearance(180, 80, 15, 15);

// ---------------------------------------------------------

//Close and output PDF document
$fileatt = $pdf->Output('file_name.pdf', 'E');

//define the receiver of the email
$name = "Name";
$email = "email@email.com";

$to = "email@email.com";

$from = "From Name ";

$subject = "Subject text";

//$fileatt = "./test.pdf";

$fileatttype = "application/pdf";

$fileattname = "newname.pdf";

$headers = "From: $from";

$file = fopen($fileatt, 'rb');

fclose($file);

$semi_rand = md5(time());

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";

$data = chunk_split(base64_encode($data));

$message .= "–{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";

if (mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
} else {
echo "There was an error sending the mail.";
}
//============================================================+
// END OF FILE
//============================================================+
</code>```

Update

I made some changed and can now receive an attachment, but the attachment doesnt open due to error

and there is no content in the email apart from the attachment.

```<code>// Settings
$name        = "Name goes here";
$email       = "email@gmail.com";
$to          = "$name <$email>";
$from        = "From";
$subject     = "Subject";
$mainMessage = "Hi, here's the file.";
$fileatt     = "mypdf.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "mypdf.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";

// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);

// This attaches the file
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers      .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage  . "\n\n";

$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";

// Send the email
if(mail($to, $subject, $message, $headers)) {

echo "The email was sent.";

}
else {

echo "There was an error sending the mail.";
}
</code>```

答:
Solved the problem. </p>

```<code>//define the receiver of the email
$to = 'email@gmail.com';
$subject = 'Subject';
$repEmail = 'me@email.com  ';

$fileName = 'output.pdf';
$fileatt = $pdf->Output($fileName, 'E');
$attachment = chunk_split($fileatt);
$eol = PHP_EOL;
$separator = md5(time());

$headers = 'From: From <'.$repEmail.'>'.$eol;
$headers .= 'MIME-Version: 1.0' .$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

$message = "--".$separator.$eol;
$message .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$message .= "This is a MIME encoded message.".$eol;

$message .= "--".$separator.$eol;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;

$message .= "--".$separator.$eol;
$message .= "Content-Type: application/pdf; name=\"".$fileName."\"".$eol;
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $attachment.$eol;
$message .= "--".$separator."--";

// Send the email
if(mail($to, $subject, $message, $headers)) {

echo "The email was sent.";

}
else {

echo "There was an error sending the mail.";
}
</code>```

Title: TCPDF email error

Body:
I use TCPDF to send pdf as an attachment. I do receive the email, so the email works, but there is no attachment.

In the email I receive a very long scrambled message. If I remove $data (as in code below) the content of the message is much less, but still no attachment.

<?php
//This file create a pd contract agreement based on the client's detail.
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
require_once('connect.php');

//Connect and get information

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$findaccount = $conn->prepare("SELECT * from Table'");

$findaccount->execute();

//Variable list here and working

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Me');
$pdf->SetTitle('My Title');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' ', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}

 // ---------------------------------------------------------

/*
 NOTES:
 - To create self-signed signature: openssl req -x509 -nodes -days 365000       -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
- To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
 - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
 */

// set certificate file
$certificate = 'file://data/cert/tcpdf.crt';

// set additional information
$info = array(
'Name' => 'My Site',
'Location' => 'Address',
'Reason' => 'Because',
'ContactInfo' => 'https://www.example.com',
);

// set document signature
$pdf->setSignature($certificate, $certificate, 'tcpdfdemo', '', 2,    $info);

// set font
$pdf->SetFont('helvetica', '', 7);

// add a page
$pdf->AddPage();

// print a line of text
$text = "
HTML DISPLAY HERE

";

$pdf->writeHTML($text, true, 0, true, 0);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// *** set signature appearance ***

// create content for signature (image and/or text)

// define active area for signature appearance
$pdf->setSignatureAppearance(180, 60, 15, 15);

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// *** set an empty signature appearance ***
$pdf->addEmptySignatureAppearance(180, 80, 15, 15);

// ---------------------------------------------------------

//Close and output PDF document
$fileatt = $pdf->Output('file_name.pdf', 'E');

//define the receiver of the email
$name = "Name";
$email = "email@email.com";

$to = "email@email.com";

$from = "From Name ";

$subject = "Subject text";

//$fileatt = "./test.pdf";

$fileatttype = "application/pdf";

$fileattname = "newname.pdf";

$headers = "From: $from";

$file = fopen($fileatt, 'rb');

fclose($file);

$semi_rand = md5(time());

$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message .= "\n\n";

$data = chunk_split(base64_encode($data));

$message .= "–{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";

if (mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
} else {
echo "There was an error sending the mail.";
}
//============================================================+
// END OF FILE
//============================================================+

Update

I made some changed and can now receive an attachment, but the attachment doesnt open due to error

and there is no content in the email apart from the attachment.

// Settings
$name        = "Name goes here";
$email       = "email@gmail.com";
$to          = "$name <$email>";
$from        = "From";
$subject     = "Subject";
$mainMessage = "Hi, here's the file.";
$fileatt     = "mypdf.pdf"; //file location
$fileatttype = "application/pdf";
$fileattname = "mypdf.pdf"; //name that you want to use to send or you can use the same name
$headers = "From: $from";

// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);

// This attaches the file
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers      .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage  . "\n\n";

$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";

// Send the email
if(mail($to, $subject, $message, $headers)) {

echo "The email was sent.";

}
else {

echo "There was an error sending the mail.";
}

Body:
Solved the problem.

//define the receiver of the email
$to = 'email@gmail.com';
$subject = 'Subject';
$repEmail = 'me@email.com  ';

$fileName = 'output.pdf';
$fileatt = $pdf->Output($fileName, 'E');
$attachment = chunk_split($fileatt);
$eol = PHP_EOL;
$separator = md5(time());

$headers = 'From: From <'.$repEmail.'>'.$eol;
$headers .= 'MIME-Version: 1.0' .$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";

$message = "--".$separator.$eol;
$message .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$message .= "This is a MIME encoded message.".$eol;

$message .= "--".$separator.$eol;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;

$message .= "--".$separator.$eol;
$message .= "Content-Type: application/pdf; name=\"".$fileName."\"".$eol;
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $attachment.$eol;
$message .= "--".$separator."--";

// Send the email
if(mail($to, $subject, $message, $headers)) {

echo "The email was sent.";

}
else {

echo "There was an error sending the mail.";
}


问:
Readable key value pair data-structure in java
I have a key value arrays

```<code>String[] fields      = {"firstName", "middleName", "id"};
String[] fieldValues = {"first name", "middle name", "student id"};
</code>```

I have a method that compares two beans and returns a array of String with different field values.

```<code> public static String[] beanCompare(Object A, Object B,
                                          String[] fields, String[] fieldValue);
</code>```

Example If I pass a Studentbean with different firstName and id.
It will return

["first name", "student id"].

I need to compare 100's of beans.

The return value updates an activity log table. Let say, the firstName field is updated. We display

the first name has been updated

in the UI. It's for auditing.
 Is there a readable and maintainable way to represent such key-value pair?

答:
So, enum worked for me.

```<code>    public enum FieldEnum {

    firstName("first name"), middleName("middle name"), id("student id");

    String value;

    FieldEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
    }
</code>```

Its more readable and maintainable.

ContentLicense: CC BY-SA 4.0

Body:
I have a key value arrays

String[] fields      = {"firstName", "middleName", "id"};
String[] fieldValues = {"first name", "middle name", "student id"};

I have a method that compares two beans and returns a array of String with different field values.

 public static String[] beanCompare(Object A, Object B,
                                          String[] fields, String[] fieldValue);

Example If I pass a Studentbean with different firstName and id.
It will return

["first name", "student id"].

I need to compare 100's of beans.

The return value updates an activity log table. Let say, the firstName field is updated. We display

the first name has been updated

in the UI. It's for auditing.
 Is there a readable and maintainable way to represent such key-value pair?

Body:
So, enum worked for me.

    public enum FieldEnum {

    firstName("first name"), middleName("middle name"), id("student id");

    String value;

    FieldEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
    }

Its more readable and maintainable.


问:
Newly added methods are not being generated in WSDL in WCF Service
I have a WCF Service which exposes couple methods and for every method an entry was being generated in .wsdl file .

It was working fine but recently, someone added new methods in different branch and It was still working fine( an entry for respective methods were being generated) But When I merged the same code to different branch, then No .wsdl description is being generated for those newly added methods Or Even though If I add new methods in the service contract.

Any hint or clue would be appreciated.

答: The problem, I have found that in one branch the output path of .csproj file was changed to output instead of Bin. After changing the path back to bin from output directory it worked.</p>


问:
Java library for calling exteral programs
I am looking for a JAVA library that facilitates running external programs. Now I run them "manually" in a separate thread and capture I/O.

I have several different external tools to run and what I need is a uniform approach to do that. The tasks I have to handle includes:
- preparing input files according to predefined templates
- running the commands
- waiting for the results and parsing output files
- maintaining the pipeline

The whole pipeline can be considered as a graph with external tools as nodes and data flow as edges. It would be great if the software could run some of the commands in parallel threads, if the data flow permits.

Is there an existing solution of such problems?

Based on the answers I got I feel I have to clarify: I don't need pipes. Data flow can be solved with files, which I need anyway. Moreover, pipes have to be linear (1 output -> 1 input) but I need a graph

I already have a kind of a prototype in python - a bunch of scripts. It is good but as for me - not scalable. Moreover some of the programs I call are in java, so making the whole thing in java would be handy.
Best,
Tim

答:
If you're on Unix, have you thought about building a Unix shell command line dynamically (using pipes, redirection, tee etc.) and then spawning this one command off using ProcessBuilder or similar, and (say) /bin/sh -c ?

It means you're making use of an existing working infrastructure that handles pipes, buffering, error collection and managing resources.


问:
Cordova App's localStorage wiped after AppStore update
I need to save few datas on my App so i used localStorage. Actually LocalStorage is very useful: Free, fast and offline database.

But when I update my app from AppStore, all of my old datas gone. Localstorage wiped. Also when I search in stackoverflow, I learned that localStorage is reset when the memory of the device is full.

I'm looking for an easy to use, offline supported and permanent solution. I found pouchdb, but it's a bit complicated.

I'm curious about your suggestions.

Best.

答:
Yes, LocalStorage will wipeout automatically, when you reinstall / update / memory full.

Possible Solutions

You can use SQLite Plugin, If you want to store SQL based data

Use Native Storage (https://github.com/TheCocoaProject/cordova-plugin-nativestorage)

Use Secure Storage (https://github.com/Crypho/cordova-plugin-secure-storage)


问:
How can I translate printf("%c",M); from C to Java for my DES implementation?
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)

So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:

```<code>printf("%c",M);
</code>```

Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.

My Code:

```<code>import java.util.Scanner;

public class DES {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner eingabe = new Scanner(System.in);

        int p, q, key2, fn, encryption_key, temp1 , temp2 ,
            t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
        int[] Cipher = new int [100];
        String passwort;

        System.out.println("Enter the value of p and q");

        p = eingabe.nextInt();
        q = eingabe.nextInt();

        System.out.println(p);
        System.out.println(q);

        key2= p*q;

        fn=(p-1)*(q-1);
        System.out.println("Enter Enryption key e: ");
        encryption_key = eingabe.nextInt();

        do {

            s=(privatekey1*encryption_key)%fn;
            privatekey1++;

        } while (s!=1);

        privatekey1=privatekey1-1;

        System.out.println("Public Key : "+ encryption_key + ","+ key2 );
        System.out.println("Private Key: "+ privatekey1 + "," +key2 );
        System.out.println("Enter Message: ");
        passwort= eingabe.next();
        for ( temp2 = 0; temp2 < passwort.length(); temp2++)
        {
            t = passwort.charAt(temp2);
            passwort_s=1;
            for(temp1 =0 ; temp1< encryption_key ; temp1++){
                passwort_s= passwort_s*t%key2;
            }
            passwort_s= passwort_s%key2;
            System.out.println(passwort_s);
        }

        System.out.println("Enter cipher Text: ");
        for(temp1=0;temp1< passwort.length(); temp1++ )
        {
            Cipher[temp1]= eingabe.nextInt();
        }

        System.out.println("Plainttext: ");
        for(temp2 =0; temp2 < passwort.length(); temp2++);
        {
            klartext=1;

            for(temp1 =0; temp1 < privatekey1; temp1 ++){
                klartext=klartext*Cipher[temp2]%key2;
            }
            klartext=klartext%key2;
            System.out.println(klartext);
        }
    }
}
</code>```

How can I convert the

```<code>printf("%c",M);
</code>```

to Java, and is this then a full DES implementation?

答:
Its late and I'm tired but this isn't a DES implementation, is it?

It looks more like RSA.

Yeah the link on your post is an asymmetrical cryptosystem. DES is symmetrical.

Body:
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)

So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:

printf("%c",M);

Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.

My Code:

import java.util.Scanner;

public class DES {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Scanner eingabe = new Scanner(System.in);

        int p, q, key2, fn, encryption_key, temp1 , temp2 ,
            t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
        int[] Cipher = new int [100];
        String passwort;

        System.out.println("Enter the value of p and q");

        p = eingabe.nextInt();
        q = eingabe.nextInt();

        System.out.println(p);
        System.out.println(q);

        key2= p*q;

        fn=(p-1)*(q-1);
        System.out.println("Enter Enryption key e: ");
        encryption_key = eingabe.nextInt();

        do {

            s=(privatekey1*encryption_key)%fn;
            privatekey1++;

        } while (s!=1);

        privatekey1=privatekey1-1;

        System.out.println("Public Key : "+ encryption_key + ","+ key2 );
        System.out.println("Private Key: "+ privatekey1 + "," +key2 );
        System.out.println("Enter Message: ");
        passwort= eingabe.next();
        for ( temp2 = 0; temp2 < passwort.length(); temp2++)
        {
            t = passwort.charAt(temp2);
            passwort_s=1;
            for(temp1 =0 ; temp1< encryption_key ; temp1++){
                passwort_s= passwort_s*t%key2;
            }
            passwort_s= passwort_s%key2;
            System.out.println(passwort_s);
        }

        System.out.println("Enter cipher Text: ");
        for(temp1=0;temp1< passwort.length(); temp1++ )
        {
            Cipher[temp1]= eingabe.nextInt();
        }

        System.out.println("Plainttext: ");
        for(temp2 =0; temp2 < passwort.length(); temp2++);
        {
            klartext=1;

            for(temp1 =0; temp1 < privatekey1; temp1 ++){
                klartext=klartext*Cipher[temp2]%key2;
            }
            klartext=klartext%key2;
            System.out.println(klartext);
        }
    }
}

How can I convert the

printf("%c",M);

to Java, and is this then a full DES implementation?

LastEditorDisplayName: John Nolan

OwnerDisplayName: John Nolan


问:
Making the size of text-box the same as image
I'm trying to fix 2 issues:

The images on the left (sideImage) won't vertically align with the text box when I scale the window down horizontally. I've tried using margin-top auto and margin-bottom auto but that doesn't seem to work to well.

The top div would disappear on top when I scale down the window vertically. (I have no idea why that happened)

I'm using Bootstrap btw, so pls do keep that in mind.

/*-- CSS --*/

* {
  background-color: rgba(0, 0, 0, 0.1);
}

html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
}

.page2Box {
  float: left;
  display: inline-block;
  clear: both;
}

.sideImage {
  margin-top: auto !important;
  margin-bottom: auto !important;
}

.mainImage {
  float: right;
  margin-top: auto !important;
  margin-bottom: auto !important;
}

p {
  height: 180px !important;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Page2_Bootstrap</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container-fluid bigBox col-md-8">
    <div class="container page2Box col-md-12" id="box1">
      <h2 class="col-md-5">Main Goal</h2>
      <p class="col-md-8">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultrices urna in dui laoreet rhoncus. Vestibulum posuere mollis velit. Morbi elementum placerat erat.</p>
    </div>
    <div class="container page2Box col-md-4" <div class="container page2Box col-md-12" id="box2">
      <img class="image-responsive sideImage col-md-4" src="placeholder.png">
      <h2 class="col-md-5">Who We Are</h2>
      <p class="col-md-8">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultrices urna in dui laoreet rhoncus. Vestibulum posuere mollis velit. Morbi elementum placerat erat.</p>
    </div>
    <div class="container page2Box col-md-12" id="box3">
      <img class="image-responsive sideImage col-md-4" src="placeholder.png">
      <h2 class="col-md-5">What We Do</h2>
      <p class="col-md-8">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultrices urna in dui laoreet rhoncus. Vestibulum posuere mollis velit. Morbi elementum placerat erat.</p>
    </div>
  </div>
  <image class="image-responsive col-md-4 mainImage" src="placeholder.png">
</body>

</html></code>```

This is how it looks like.

Here are the problems.

答:
I would suggest using the flex-box option while nesting the image and text in separate divs. I.E.

HTML:

```<code><div class="container">
    <div class="row equal">
        <div class="col-md-6 col-sm-6">
            <div class="box">
                <img class="image-responsive" src="http://via.placeholder.com/350x150" />
            </div>
        </div>
        <div class="col-md-6 col-sm-6">
            <div class="box">
                <h2>Main Goal</h2>
                <p>In iaculis elit id odio malesuada, vitae euismod dui viverra. Maecenas pulvinar quis magna in dapibus. Ut eget elit eget nibh eleifend ultricies a a orci. Aliquam tristique nulla eu sapien posuere egestas. </p>
            </div>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
  flex-wrap: wrap;
}
.row > [class*='col-'] {
  display: flex;
  flex-direction: column;
  border: 1px solid #333;
}
</code>```

JSFiddle: https://jsfiddle.net/Jabideau/rkzafmrb/

Body:
I'm trying to fix 2 issues:

The images on the left (sideImage) won't vertically align with the text box when I scale the window down horizontally. I've tried using margin-top auto and margin-bottom auto but that doesn't seem to work to well.

The top div would disappear on top when I scale down the window vertically. (I have no idea why that happened)

I'm using Bootstrap btw, so pls do keep that in mind.

/*-- CSS --*/

* {
  background-color: rgba(0, 0, 0, 0.1);
}

html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
}

.page2Box {
  float: left;
  display: inline-block;
  clear: both;
}

.sideImage {
  margin-top: auto !important;
  margin-bottom: auto !important;
}

.mainImage {
  float: right;
  margin-top: auto !important;
  margin-bottom: auto !important;
}

p {
  height: 180px !important;
  overflow: hidden;
}

<!DOCTYPE html>

  <title>Page2_Bootstrap</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Main Goal

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultrices urna in dui laoreet rhoncus. Vestibulum posuere mollis velit. Morbi elementum placerat erat.

    <div class="container page2Box col-md-4"

Who We Are

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultrices urna in dui laoreet rhoncus. Vestibulum posuere mollis velit. Morbi elementum placerat erat.

What We Do

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultrices urna in dui laoreet rhoncus. Vestibulum posuere mollis velit. Morbi elementum placerat erat.

  <image class="image-responsive col-md-4 mainImage" src="placeholder.png">

This is how it looks like.

Here are the problems.

Body:
I would suggest using the flex-box option while nesting the image and text in separate divs. I.E.

HTML:

<div class="container">
    <div class="row equal">
        <div class="col-md-6 col-sm-6">
            <div class="box">
                <img class="image-responsive" src="http://via.placeholder.com/350x150" />
            </div>
        </div>
        <div class="col-md-6 col-sm-6">
            <div class="box">
                <h2>Main Goal</h2>
                <p>In iaculis elit id odio malesuada, vitae euismod dui viverra. Maecenas pulvinar quis magna in dapibus. Ut eget elit eget nibh eleifend ultricies a a orci. Aliquam tristique nulla eu sapien posuere egestas. </p>
            </div>
        </div>
    </div>
</div>

CSS:

.row {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
  flex-wrap: wrap;
}
.row > [class*='col-'] {
  display: flex;
  flex-direction: column;
  border: 1px solid #333;
}

JSFiddle: https://jsfiddle.net/Jabideau/rkzafmrb/


问:
How to use this response in a single URL?
```<code>HttpResponse<String> response = Unirest.get("https://aadhaarnews-fuel-price-api-india-v1.p.mashape.com/GetPetrolDieselPriceWithState?state=hp")
.header("X-Mashape-Key", "my key")
.header("Accept", "text/plain")
.as String();
</code>```

答:
considering it is returning JSONArray,</p>

```<code>JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }){

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String>  params = new HashMap<String, String>();
        params.put("X-Mashape-Key", "my key");

        return params;
    };

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_arry);
</code>```

Body:
considering it is returning JSONArray,

JsonArrayRequest req = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.hide();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        pDialog.hide();
                    }
                }){

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String>  params = new HashMap<String, String>();
        params.put("X-Mashape-Key", "my key");

        return params;
    };

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req, tag_json_arry);


问:
Error Handling in LC-3?
I have this question on my review sheet that I cant seem to get but rather than ask you for the answer I would rather like to learn the difference between these specific concepts.

For reference the question is  An LC-3 instruction ADD R1,R2, #45 produces an error. It will be caught at a. assembly time b. link time c. run time d. compile time. Rather than just finding out the answer what  would rather like to know is what is the difference between these and how do they differ when it comes to error handling?

答:
Using the C programming language as an example the 4 steps to create an executable program Preprocessing, Compiling, Assembling, and Linking.

Compile time

These are generally common and are caused by a malformed user program that the compiler can't process, things such as forgetting a semicolon can cause a compiler error.

Assembly Time

Something went wrong with the assembler.  This includes using instructions incorrectly as above, not defining a LABEL but using it in an instruction etc.

Link Time

As part of the C compile process to form an executable many object files generated by the assemble step are linked together.  In C programming you can specify that some symbol is defined externally via the extern keyword, other things like function prototypes will tell the compiler a function is defined somewhere.

The linker will resolve where those variables/functions live.  If you haven't declared a function/variable and something references it then you will get a undefined reference error.  Same for if something is defined multiple times.

Run Time

An error occurred during running your program, this is something such as accessing a pointer that is null, or dividing by zero.

Title: Error Handling in LC-3?


问:
Generate random 16 digit HEX number using Groovy script
I am trying to Generate 16 digit random HEX number.

```<code>import org.apache.commons.lang.RandomStringUtils;
def randomhex = RandomStringUtils.randomNumeric(16);
log.info randomhex
def result = Integer.toHexString(randomhex);
log.info result
</code>```

Expected : The result should be random 16 digit HEX number.
e.g : 328A6D01F9FF12E0

Actual :
groovy.lang.MissingMethodException: No signature of method: static java.lang.Integer.toHexString() is applicable for argument types: (java.lang.String) values: [3912632387180714] Possible solutions: toHexString(int), toString(), toString(), toString(), toString(int), toString(int, int) error at line: 9

答:
64 bits are needed to store a 16-digit hex number, which is bigger than Integer supports. A Long could be used instead (the toUnsignedString method was added in Java 8):

```<code>def result = Long.toUnsignedString(new Random().nextLong(), 16).toUpperCase()
</code>```

Another potential approach is to generate 16 random integers from 0 to 16, and join the results into a String.

```<code>def r = new Random()
def result = (0..<16).collect { r.nextInt(16) }
                     .collect { Integer.toString(it, 16).toUpperCase() }
                     .join()
</code>```

Yet another approach is to leverage a random UUID and just grab the last 16 digits from that.

```<code>def result = UUID.randomUUID()
                 .toString()
                 .split('-')[-1..-2]
                 .join()
                 .toUpperCase()
</code>```

Body:
I am trying to Generate 16 digit random HEX number.

import org.apache.commons.lang.RandomStringUtils;
def randomhex = RandomStringUtils.randomNumeric(16);
log.info randomhex
def result = Integer.toHexString(randomhex);
log.info result

Expected : The result should be random 16 digit HEX number.
e.g : 328A6D01F9FF12E0

Actual :
groovy.lang.MissingMethodException: No signature of method: static java.lang.Integer.toHexString() is applicable for argument types: (java.lang.String) values: [3912632387180714] Possible solutions: toHexString(int), toString(), toString(), toString(), toString(int), toString(int, int) error at line: 9

Body:
64 bits are needed to store a 16-digit hex number, which is bigger than Integer supports. A Long could be used instead (the toUnsignedString method was added in Java 8):

def result = Long.toUnsignedString(new Random().nextLong(), 16).toUpperCase()

Another potential approach is to generate 16 random integers from 0 to 16, and join the results into a String.

def r = new Random()
def result = (0..<16).collect { r.nextInt(16) }
                     .collect { Integer.toString(it, 16).toUpperCase() }
                     .join()

Yet another approach is to leverage a random UUID and just grab the last 16 digits from that.

def result = UUID.randomUUID()
                 .toString()
                 .split('-')[-1..-2]
                 .join()
                 .toUpperCase()


问:
Testing against one of several values in XSLT?
Apologies I have no coding experience.

This line of code is resisting my report from exporting all product_types. Is it possible to change this to product_type="ALL" or product_type='configurable','other'?

```<code>    <xsl:if test="(product_type='configurable')">
</code>```

I've obviously tried to make the changes above but they don't work.

答:
Always:

```<code><xsl:if test="true()">
</code>```

Never:

```<code><xsl:if test="false()">
</code>```

Multiple cases (XSLT 1.0):

```<code><xsl:if test="(product_type = 'configurable') or (product_type = 'other')">
</code>```

Multiple cases (XSLT 2.0+):

```<code><xsl:if test="product_type = ('configurable', 'other')">
</code>```

Defined, regardless of value:

```<code><xsl:if test="product_type">
</code>```

Body:
Apologies I have no coding experience.

This line of code is resisting my report from exporting all product_types. Is it possible to change this to product_type="ALL" or product_type='configurable','other'?

    <xsl:if test="(product_type='configurable')">

I've obviously tried to make the changes above but they don't work.

Body:
Always:

<xsl:if test="true()">

Never:

<xsl:if test="false()">

Multiple cases (XSLT 1.0):

<xsl:if test="(product_type = 'configurable') or (product_type = 'other')">

Multiple cases (XSLT 2.0+):

<xsl:if test="product_type = ('configurable', 'other')">

Defined, regardless of value:

<xsl:if test="product_type">


问:
How to force gcc to link unreferenced, static C++ objects from a library
I'm using a C++ library that can be built as either a shared or a static library.
This library uses a factory technique, where static objects register themselves when the program starts and the static objects get created.

This works fine as long as the shared library is used. When the static version is used, none of the static objects get included into the final program (because they aren't referenced directly) and thus their functionality isn't available.

Is there a way to force gcc to include all static objects from a library when linking?

The library is Open Source and I could modify it, if that helps.

答:
You can use -Wl,--whole-archive -lyourlib , see the manpage for ld for more info.

Any static libraries mentioned after -Wl,--whole-archive on the command line gets fully included, you can turn this off again too if you need to , as in e.g. -Wl,--whole-archive -lyourlib -Wl,--no-whole-archive -lotherlib


问:
Does Spark dataset.write() result in the rows being collected at the driver node?
I am trying to fine tune the performance a spark job that writes the results of a processed data set (on cluster) to the HDFS and also to a relational database. I am using dataset.write().jdbc() and dataset.write().csv() methods respectively. I am wondering if these methods will result in all the rows being collected to the driver node, thus impacting the performance of the job ?</p>

答:
Does Spark dataset.write() result in the rows being collected at the driver node?

It does not. All DataFrameWriter methods work directly (each executor writes its own part of the data) without collecting.


问:
How to log unhandled exception in .net core
With ELMAH feature in web api 2.0 and Centralized logging and error handling , runtime calls logging module and decide if it can be handled then calls the handler else just logs it..
how can this feature be added in web api core. as we don't have inbuilt centralized unhandled logging feature..

One way I got is to use ExceptionHandler middleware and when it gets called, get the exception and log  it or send email.. but what if handler doesn't get called .. how to log those unhandled exceptions ?

答:
Middleware could be a way to go yes. I've written a guide here: Error Logging Middleware in ASP.NET Core.

I would probably look at Microsoft.Extensions.Logging in combination with a logging framework like Serilog, NLog or log4net.