text:
Q: cross-referencing acronyms not displayed in the text with I use glossaries and define besides standard acronyms also some acronyms like this:
\documentclass{scrreprt}

\usepackage{xcolor}

\definecolor{navy}{RGB}{0,0,128}

\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}

\usepackage[
    colorlinks=true,
    linkcolor=navy,
    anchorcolor=black,
    urlcolor=navy
]{hyperref}

\usepackage[acronym,toc]{glossaries}

\makeglossaries

\newglossaryentry{P2P}{
    type=\acronymtype,
    name={P2P},
    description={Peer-to-Peer},
    first={Peer-to-Peer (P2P)},
    see=[\glossaryname:]{Peer-to-Peer}
}
\newglossaryentry{Peer-to-Peer}{
    name={Peer-to-Peer},
    description={Eine direkte Kommunikation zwischen zwei Teilnehmern}
}

\newglossaryentry{Plug-in}{
    name={Plug-in},
    description={Ein Softwaremodul, das zur Laufzeit eingebunden werden kann und damit die Funktionalität eines Systems erweitert}
}

\newacronym{DIN}{DIN}{Deutsches Institut für Normung}

\newcommand*\acrshortlong[2][]{\glslink[#1]{#2}{\glsentryshort{#2} (\glsentrylong{#2})}}

\begin{document}

Works as expected:

gls: \gls{Plug-in}

gls: \gls{DIN}

acrshort: \acrshort{DIN}

acrshortlong: \acrshortlong{DIN}

gls: \gls{Peer-to-Peer}

Not as expected:

acrshort: \acrshort{P2P}

acrshortlong: \acrshortlong{P2P}

\glossarystyle{altlist}
\printglossary[type=\acronymtype]

\glossarystyle{altlist}
\printglossary

\end{document}

Unfortunately the \acr... commands dont work as expected with acronyms defined via \newglossaryentry with type=\acronymtype
Anyone an idea how to get these cross-referencing acronyms also working as expected?

A: (Converting comment into an answer.)
Commands like \glsentrylong and \glsentryshort access the long and short keys. These keys (and their plural versions) are set by \newacronym but have to be explicitly set, if required, when using \newglossaryentry. However in this case it's simpler to just use the optional argument of \newacronym to set the cross-referencing information:
\newacronym[see={[\glossaryname:]{Peer-to-Peer}}]{P2P}{P2P}{Peer-to-Peer}


text:
Q: How to search ID of object nvarchar value on SQL Server I have a table tableOne:
+------+---------+
|  ID  |  Pages  |
+------+---------+
|  1   |  1,2,3  |
|  2   |  2,3    |
|  3   |  2      |
+------+---------+

Now I want to get ID of tableOne where my Page exists.
Example query:
select * from tableOne where Pages = 3

Output should be:
+------+---------+
|  ID  |  Pages  |
+------+---------+
|  1   |  1,2,3  |
|  2   |  2,3    |
+------+---------+

A: Simple logic
SELECT * FROM tableone
WHERE Pages LIKE '%,3,%'
      OR Pages LIKE '3,%'
      OR Pages LIKE '%,3'

If you are using SQL Server 2016 and above then use STRING_SPLIT: (Not tested)
SELECT Id, Pages
FROM tableOne
    CROSS APPLY STRING_SPLIT(Pages, ',');
WHERE value  = '3'

Precise Answer:
You have to create SPLIT function to split strings (If you are not using SQL Server 2016 or above)
CREATE FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX) )
RETURNS
 @returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN

 DECLARE @name NVARCHAR(255)
 DECLARE @pos INT

 WHILE CHARINDEX(',', @stringToSplit) > 0
 BEGIN
  SELECT @pos  = CHARINDEX(',', @stringToSplit)
  SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

  INSERT INTO @returnList
  SELECT @name

  SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END

And to use it:
SELECT DISTINCT id
FROM tableone
CROSS APPLY dbo.splitstring(Pages)
WHERE name = '3'

A: If you're using MySQL, you can use FIND_IN_SET:
SELECT * FROM tableone WHERE FIND_IN_SET(3, Pages);

Output:
ID  Pages
1   1,2,3
2   2,3

A: You should consider changing your stored data, so each page will be stored in one row separately.
If you can't, then you could use this query:
SELECT *
FROM tableOne
WHERE ',' + Pages + ',' LIKE '%,3,%';

A: if you are using postgres sql
 SELECT * FROM (select id, unnest(string_to_array(pages,','))::integer AS ids from tableone) as a  where ids = 3

A: SELECT * FROM YourTbl
WHERE Yourcolumn LIKE '%word1%'

In your case:
SELECT * FROM tableone
WHERE Pages LIKE '%3%'

Finds any values that have "3" in any position

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vintage speaker capacitor ID I would appreciate any help on identifying these capacitors I have inside a pair of vintage speakers. The speakers in the cabinets are EV and University Loudspeaker Inc so I know these are old timers. I wanted to clean them up and replace some wiring and possibly the two capacitors in each cabinet. I am new to this so I do not know how to ID old vintage electrical parts.

Here are some of the marking on them. "TM CAPACITOR" / Max Temp 85 deg C / Made In USA /600067  -2 / 232  642 / 857009 / MFD 4  VOLT 25 / NON POLARIZED


text:
Q: Not able to connect django1.11 with oracle11g I am not able to migrate project in linux. Dependecy:cx-Oracle==7.2.0
Django==1.11,oracle11g and python3.I am trying to connect with a server database.
I removed a line self.cursor.numbersAsStrings = True from /work/sunlife_env/lib/python3.6/site-packages/django/db/backends/oracle/base.py to resolve this error:

AttributeError: 'cx_Oracle.Cursor' object has no attribute 'numbersAsStrings'

BUT now, after python manage.py migrate, I am getting the following error.
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 250, in apply_migration
    self.recorder.record_applied(migration.app_label, migration.name)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in record_applied
    self.migration_qs.create(app=app, name=name)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/query.py", line 393, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 806, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 836, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 922, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/base.py", line 961, in _do_insert
    using=using, raw=raw)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/query.py", line 1060, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1106, in execute_sql
    return self.connection.ops.fetch_returned_insert_id(cursor)
  File "/home/arima/work/sunlife_env/lib/python3.6/site-packages/django/db/backends/oracle/operations.py", line 245, in fetch_returned_insert_id
    return int(cursor._insert_id_var.getvalue())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

I need help to connect my db to django project.


text:
Q: need clarification about crontab on openshift scaleable application I have an openshift scaleable app comprised of JBOSS running with a MySql database. Suppose I schedule an hourly task, and when the time comes for that to run, I have 5 instances of my app running. Will all 5 instances run the crontab job, or only one? And if only one, will it always be the same one, or will I not know ahead of time which one?

A: If you have a cron job setup on a scaled application, it will run on every web gear that is running at that time.


text:
Q: angular: replace ' character from json I'm building a mobile app that pulls data from json. Some of the texts come with strange characters like & # 8217. How do I change it? Here is my code:
$http.jsonp( postsApi ).
success(function (data, status, headers, config) {

    $scope.posts = data;

   $scope.content = $sce.trustAsHtml(data.content);

  console.log( data );

A: This strange characters are html encoded characters, if you bind you content on your page, using ng-bind-html="content" it will display the corect html code on your page, you have no need to change them.
For example, &#8217 is the encoded version of the quote '.

A: It seems that you have strings containing html. I would recommend that you read up on html character references, for example at https://en.wikipedia.org/wiki/Character_encodings_in_HTML and then find a library to decode it.


text:
Q: window.resolveLocalFileSystemURL gives error code 1 after updating cordova to 10.0.0 and android to 9.0.0 The code works fine in android@8.0.0 but when I updated my cordova to 10.0.0 and cordova platform android to 9.0.0 it give error code:1.
Here is my code, I am using cordova-plugin-file-transfer
window.resolveLocalFileSystemURL(path, //my path is file:///storage/emulated/0/Download/
    function (fileSystem) {

    },function (err) {
      console.log(err); //gives error code 1
    }


text:
Q: If $f,g:(X,A)\to (Y,B)$ are homotopic functions under a homotopy $H:X\times [0,1]\to Y$ then $f_*=g_*:H_n(X,A)\to H_n(Y,B)$. If $f,g:(X,A)\to (Y,B)$ are homotopic functions under a homotopy $H:X\times [0,1]\to Y$ such that $H(a,t)\in B$ for all $a\in A$ and $t\in [0,1]$, then $f_*=g_*:H_n(X,A)\to H_n(Y,B)$.
This question has already been posted here Homotopic maps induce the same homomorphism for reduced homology groups and here Homotopic maps $(X, A) \to (Y, B)$ induce homotopic maps $X/A \to X/B$ but I still have many doubts, I would like to know where we are using that $f,g:(X,A)\to (Y,B)$ are homotopic in Homotopic maps $(X, A) \to (Y, B)$ induce homotopic maps $X/A \to X/B$.
I think it is enough to show that $f,g:X/A\to Y/B$ are homotopic, because in this case we already know that $f_*=g_*:H_n(X/A)\to H_n(Y/B)$ where $H_n(X/A)=H_n(X,A)$ and $H_n(Y/B)=H_n(Y,B)$. Now if $f,g:(X,A)\to (Y,B)$ are homotopic, how do I prove that $f,g:X/A\to Y/B$ are homotopic? Thank you.

A: Your main goal is to prove that if $f,g:(X,A)\to (Y,B)$ are homotopic functions under a homotopy $H:X\times [0,1]\to Y$ such that $H(a,t)\in B$ for all $a\in A$ and $t\in [0,1]$, then $f_*=g_*:H_n(X,A)\to H_n(Y,B)$.
This is usually done by working on the level of chain complexes. See any book treating singular homology.
Your idea was to reduce the proof for pairs to the "already known absolute case" by using that $H_n(X,A) = H_n(X/A)$. Unfortunately this is not true in general (see freakish's comments).
However, we can answer your final question: If $f,g:(X,A)\to (Y,B)$ are homotopic, how to show that $f,g:X/A\to Y/B$ are homotopic?
Let $H$ be a homotopy as above and let $p : X \to X/A, q : Y \to Y/B$ denote the quotient maps. Then also $p \times id : X \times I \to (X/A) \times I$ is a quotient map. This is a well-known fact from general toplogy. Now consider the map $H' = q \circ H : X \times I \to Y/B$. It has the property that $H'(a,t) = [B]$ for all $a \in A$, where $[B]$ denotes the common equivalence class of all points in $B$. Hence the function
$$H'' : (X/A) \times I \to Y/B, H''([x],t) = H'(x,t)$$
is well-defined and satisfies $H'' \circ (p \times id) = H'$. By the universal property of quotient maps this equation implies that $H''$ is continuous. But now you have $H''([x],0) = H'(x,0) = qf(x) = f''([x])$ where $f'' : X/A \to Y/B$ denotes the map induced by $f$. Similarly $H''([x],1) = g''([x])$. This proves $f'' \simeq g''$.


text:
Q: URL Encode With Curl PHP I made the change suggested and am still receiving a similar error:
{"error":"invalid_request","error_description":"invalid grant type"}
This error is likely to happen if the url-encoding is not set properly.  The updated code is below
Any help would be greatly appreciated!
<?php

$client_id = '...';
$redirect_uri = 'http://website.com/foursquare2.php';
$client_secret = '...';
$code = $_REQUEST['code'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, "https://id.shoeboxed.com/oauth/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
));

$response = curl_exec($ch);

$err = curl_error($ch);
curl_close($ch);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

A: your code is sending the data in multipart/form-data format. when you give CURLOPT_POST an array, curl will automatically encode the data in that array in the multipart/form-data format. then you tell the server, with your header, that this data is in application/x-www-form-urlencoded format, and the server will try to parse it as such, and fail, thus your received error.
first off, get rid of curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); altogether. if you're using application/x-www-form-urlencoded, php/curl will automatically add that header for you, and unlike you, php/curl won't make any typos (the devs got automated test suits to make sure this stuff is correct before every release), likewise, if you're using multipart/form-data format, php/curl will add that header for you, so don't add those 2 specific headers manually.
if you want to use the multipart/form-data format, just get rid of the header saying otherwise. but if you want to use application/x-www-form-urlencoded format, PHP has a built-in function to encode to this format, called http_build_query, so do
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
)));

(and also get rid of the content-type header, it will be added automatically.)


text:
Q: Mixed OIDC based SPA Client + OAuth Server Client scenario? I'm trying to plan the optimal way to allow for the following development:
Components:

*

*a SPA Client: which communicates with:

*an API based Server: developed by the same org

Both SPA and Server are in turn Clients of 3rd party APIs, such as:

*

*AAD Graph API

In the above case, is the following correct:

*

*the SPA signs in to AAD using OIDC Implicit Flow, and is returned two tokens: token + id_token

*the SPA persists the two tokens in isolated storage.

*the SPA communicates with the back end server's APIs.

*

*passing the token as a Bearer Token in the Authorisation header.

*Q: it it correct that in OAuth 2.0 Framework it states that the access token should not be shared beyond private clients -- but in OIDC we're taking this liberty because the SPA is considered as just a component of the same system, and that's moderately ok as long as we don't expose the client id?

*Q: passes the id_token back as well? Or is that better kept on SPA side, as server doesn't need more than sub to id of user, which it obtains from the access_token's JWT.

*Q: if it is sent, how?!? if the Authorisation header is already being used for the access token?

*Q: This has flummoxed me: how does the backend server know what scopes the user has? Neither the OAuth 20 Framework, nor the OIDC protocol does not specify that a scp property is part of the protocol. And Some OPs (eg: AAD) do not provide an introspect endpoint. There must be more than just accepting that the token is untamperable, no?

*Q: Could the backend server get its hands on the id_token (maybe to get the user's email address) if it needed to?

*

*Q: How? Is that done by doing a /token request, providing the token to get an id_token, as long as the token is not expired?

*the SPA which needs to connect to OAuth will request a separate OAuth access token for the calls to AAD. That too will be cached in isolated storage.

*Q: Is it correct that if the WebService is to proxy requests to AAD, on behalf of the SPA's user, the Client has to first ensure -- on the SPA side -- that its first token has been granted additional scopes -- adding the AAD scopes to the scopes it used to get to the API server's scopes.

*Q: If the API Webservice is to make calls to AAD on behalf of the service, with no reference to end users (eg: a webjob, or before the enduser has signed in) then the calls would have to use Client Credentials Flow?
In the above, no cookies would be used between SPA and API server. Is that an optimal approach?

The implicit flow means the token will expire...and will not be able to be refreshed, or "remember Me'ed".  Is there ever a case for the SPA to invoke a WebServer page which performs an Authorisation Code Grant Flow, and then returns the Auth Token to the server? That way both halves of the distributed client have the same tokens?
If so...any examples?! Leads??

*

*Q: One question I've always had trouble understanding: in windows, the claims show what scope the user has. How does it use that information to find the right token in the cache? Or is just not relevant -- it uses the audience attribute to find the only cache for that person on that target client, and attaches that?

Thank you very (very!*) much for any and all corrections/suggestions to the above.
* In 10 years I've never been as flummoxed by a protocol/Framework as the OIDC/OAuth RFCs.

A: Answering for AAD, other IdPs can handle things differently.

Q: it it correct that in OAuth 2.0 Framework it states that the access token should not be shared beyond private clients -- but in OIDC we're taking this liberty because the SPA is considered as just a component of the same system, and that's moderately ok as long as we don't expose the client id?

I'm not sure on the official spec but it is pretty typical to use access tokens to access back-end APIs from an SPA/native client.
The client id is pretty public info, anyone can find it from your authentication redirect URL.

Q: passes the id_token back as well? Or is that better kept on SPA side, as server doesn't need more than sub to id of user, which it obtains from the access_token's JWT.

Usually no, the id token is meant for your front-end.

This has flummoxed me: how does the backend server know what scopes the user has? Neither the OAuth 20 Framework, nor the OIDC protocol does not specify that a scp property is part of the protocol. And Some OPs (eg: AAD) do not provide an introspect endpoint. There must be more than just accepting that the token is untamperable, no?

You can implement custom roles in your API with AAD like this: https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2.
Those roles can then be assigned to users.
The access token will then have those roles.
Token validity is checked by validating the signature + audience + expiry time + issuer with AAD.

Could the backend server get its hands on the id_token (maybe to get the user's email address) if it needed to?

In the case of AAD, no. An id token is only given after user authentication.
With AAD you would call the Microsoft Graph API to get more info on the user.

Q: Is it correct that if the WebService is to proxy requests to AAD, on behalf of the SPA's user, the Client has to first ensure -- on the SPA side -- that its first token has been granted additional scopes -- adding the AAD scopes to the scopes it used to get to the API server's scopes.

Not sure I follow this one.
The token the client receives is not for AAD/MS Graph.
So it will not contain those scopes.
Your API can exchange the token it receives for a token for MS Graph, containing the granted scopes for that.

Q: If the API Webservice is to make calls to AAD on behalf of the service, with no reference to end users (eg: a webjob, or before the enduser has signed in) then the calls would have to use Client Credentials Flow? In the above, no cookies would be used between SPA and API server. Is that an optimal approach?

If you want to make calls purely as the service, then client credentials flow is the way to go.

The implicit flow means the token will expire...and will not be able to be refreshed, or "remember Me'ed". Is there ever a case for the SPA to invoke a WebServer page which performs an Authorisation Code Grant Flow, and then returns the Auth Token to the server? That way both halves of the distributed client have the same tokens?

ADAL.JS/MSAL.JS (the libraries used commonly for SPAs with AAD) use a hidden iframe to get new tokens with prompt=none.
It depends on the user having an active session with AAD.

Q: One question I've always had trouble understanding: in windows, the claims show what scope the user has. How does it use that information to find the right token in the cache? Or is just not relevant -- it uses the audience attribute to find the only cache for that person on that target client, and attaches that?

It uses the audience to know the service the token is meant for.
The subject claim will tell what principal the token was acquired for.
ADAL for example has APIs that allow you to tell it what resource (= audience) you want to call, and as what user (if applicable).
It then finds the right token in its token cache.

I hope this answers at least some of your questions :)


text:
Q: How to display Name in codeigniter Please help me, I want to display the name of the users from the table according to sender_id and recipient_id, how do the code model and view in my CodeIgniter
Tables schema
Data Table users
Data Table Messages
Model
function get_pesan_view(){
    $this->db->from('messages');
    $this->db->join('users', 'users.id = messages.sender_id', 'left');
    $this->db->join('users', 'users.id = messages.recipient_id', 'left');
    $q2 = $this->db->get();
    return $q2->result();
 }

Contoller
public function view_pesan()
{
    $data['get_pesan']=$this->Emp_model->get_pesan_view();
    $this->load->view('employee/top');
    $this->load->view('employee/nav', $data);
    $this->load->view('employee/slidbar', $data);
    $this->load->view('employee/pesan', $data);
    $this->load->view('employee/bottom');
}

View
<?php foreach ($get_pesan as $pesan) { ?>
 Sender : <?php echo $pesan->name ; ?>
 Recipient : <?php echo $pesan->name ; ?>
 <?php echo $pesan->body ; ?>
<?php } ?>

I want to display the name of the sender and recipient together in view

A: Controller
public function get_names(){

  $this->load->model('model_name'); //If not loaded in the autoload.php file
  $names = $this->model_name->all_names();
  $this->load->view('view_file_name', compact('names'));
}

The query in the model will be like this
public function all_names(){
  $this->db->select('name');
  $this->db->from('users');
  $this->db->join('messages', 'users.id = messages.sender_id');
  return $this->db->get()->result();
}

To join with recipient_id do like this
$this->db->join('messages', 'users.id = messages.recipient_id');

Then use foreach loop to show all names in the view
foreach($names as $row){
   echo $row->name;
}

A: model
    $this->db->select('messages.*,u1.{name of field for username} as sender_name,u2.{name of field for username} as recipient_name');
   $this->db->from('messages');
    $this->db->join('users u1', ' u1.id = messages.sender_id', 'left');
    $this->db->join('users u2', ' u2.id = messages.recipient_id', 'left');
    $q2 = $this->db->get();
    return $q2->result();

View
<?php foreach ($get_pesan as $pesan) { ?>
 Sender : <?php echo $pesan->sender_name; ?>
 Recipient : <?php echo $pesan->recipient_name; ?>
 <?php echo $pesan->body ; ?>
<?php } ?>

i have forgotten you cannot join one tale more than one time you need to use table aliases. it will work for you/ just place the name what ever fild name is in your data base.
it will work or else share me screen short of your table and error pages


text:
Q: no puedo eliminar elementos por cada fila con for loop Estoy creando un script en el que puedes añadir un evento y su fecha. Tal dia, el evento aparecerá en forma de notificación en el menu de Windows. He utilizado SQLite con Python 3.
Quiero que cada vez que se abre el script, se compruebe si hay algún evento con la fecha actual.
Para ello he utilizado un bucle for que por cada fila de la base de datos comprueba si la fecha de hoy y la de cada evento coinciden. Si es así, borrarían dicho evento de la base de datos.
Este es el código:
def delete_database(row):
    """
    Delete task by id
    """

    delete = row
    c.execute("""DELETE FROM notes
    WHERE message=?""",(delete,))
    conn.commit()

def remind(end_time, verbose = True):

    """
    Check if the date limit is equal to the actual date
    """

    sql = "SELECT * FROM notes"
    recs = c.execute(sql)
    if verbose:
        for row in recs:
            if row[1] == end_time:
                # toaster = ToastNotifier()
                # toaster.show_toast("You have a event today!",row[0],icon_path=vars.dirpath + '\\custom.ico',duration=10,threaded=True)
                delete_database(row[0])

Creo que el c.execute(...) no deja terminar bien el bucle (loop).
Este es el completo en Pastebin:
https://pastebin.com/1njeHT7r

A: connection.cursor.execute() retorna un None
Para obtener resultados, debes usar cursor.fetchall() o similares.
Lo que buscas tendría entonces esta forma:
c.execute(sql)
recs = c.fetchall()
    if verbose:
        [...]


text:
Q: Swift - Is it possible to move to the next cell in tableview with the click of a button? I have a tableview and custom cells which take up the fullscreen however I am wondering if upon click of a button in my cells I could move to the next cell automatically, kind of like how when you scroll more than half in TikTok it automatically goes to the next video. Aside from manually scrolling at a faster speed which is the only way I can think of, is there any other way to automatically move to the next cell, impersonating a full scroll?
Thanks for the help.

A: You can use that method:
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
Approach 1
Just delegate your tap event (IBAction of the button inside of your custom cell) back to your UIViewController that holds the UITableView reference and call scrollToRow(at:at:animated:).
Approach 2
You could also handle with tableView(_:didSelectRowAt:). Next cell would be the indexPath.row + 1 with scrollToRow(at:at:animated:)


text:
Q: Working with Zip and GZip files in Java It's been a while since I've done Java I/O, and I'm not aware of the latest "right" ways to work with Zip and GZip files. I don't necessarily need a full working demo - I'm primarily looking for the right interfaces and methods to be using. Yes, I could look up any random tutorial on this, but performance is an issue (these files can get pretty big) and I do care about using the best tool for the job.
The basic process I'll be implementing:

*

*Download a bunch of files (that might be zipped, gzipped, or both) to a temp folder.

*Add all the extracted files to a new zip file in a temp folder.

The input files might be compressed and archived more than once. For example, the "full extraction" should take any of the following inputs (I'm not in control of these), and leave behind foo.txt:

*

*foo.txt.gz

*foo.txt.zip

*foo.txt.gz.zip

*foo.txt.zip.gz

*...

*foo.txt.gz.gz.gz.zip.gz.zip.zip.gz.gz

*...

Then, I might be left with foo.txt, bar.mp3, baz.exe - so I would just add them all to a new zip file with some generic name.
Questions:

*

*With file size being a potential concern, which (interfaces/classes/methods) should I use to quickly:

*

*extract zip files?

*extract gzip files?

*write zip files?

*Am I better off keeping the individual extracted files in memory before writing back to the disk? Or,

*Do potentially large files make that a bad idea?

A: Note that TrueZip, the library suggested below, has been superseded by TrueVFS.

I've found the TrueZIP library useful.  It allows you to treat archive files as if they're just another file system and use the familiar Java I/O APIs.
Unlike the java.util.zip API, TrueZIP provides random access to the contents of the archive, so file size should not be a concern. If I remember correctly, it will detect archive files and not try to redundantly compress them when you put them into an archive.
Quoting the TrueZIP page:

The TrueZIP API provides drop-in replacements for the well-known classes File, FileInputStream and FileOutputStream. This design makes TrueZIP very simple to use: All that is required to archive-enable most client applications is to add a few import statements for the package de.schlichtherle.io and add some type casts where required.
Now you can simply address archive files like directories in a path name. For example, the path name "archive.zip/readme" addresses the archive entry readme within the ZIP file archive.zip. Note that file name suffixes are fully configurable and TrueZIP automatically detects false positives and reverts back to treat them like ordinary files or directories. This works recursively, so an archive file may even be enclosed in another archive file, like in outer.zip/inner.zip/readme.

A: There may be a library somewhere to make this easy.
However, if there isn't, you can still do it the hard way with the java.util.zip classes... using  ZipFile or ZipInputStream, along with ZipEntry for zip.
GZIPInputStream can wrap a FileInputStream for gzip, keeping in mind that gzip only works on single files.
Both types of InputStreams also have their respective OutputStreams.
Unfortunately, although I know of these classes, I've never actually used them, so I can't advise you any more than that.
Edit: The Zip functions do not appear to have any method for adding new files to a zip file without recreating the entire thing.

A: Don't hold all this uncompressed data in memory, or you might run out of heap space. You need to stream the data out to file when uncompressing and then stream it back in from file when you want to create your final zip file.
I haven't done zipped files before, but here is an example which shows how to uncompress a gzipped file:
import java.io.*;
import java.util.zip.*;

//unzipping a gzipped file
GZIPInputStream in = null;
OutputStream out = null;
try {
   in = new GZIPInputStream(new FileInputStream("file.txt.gz"));
   out = new FileOutputStream("file.txt");
   byte[] buf = new byte[1024 * 4];
   int len;
   while ((len = in.read(buf)) > 0) {
       out.write(buf, 0, len);
   }
}
catch (IOException e) {
   e.printStackTrace();
}
finally {
   if (in != null)
       try {
           in.close();
       }
       catch (IOException ignore) {
       }
   if (out != null)
       try {
           out.close();
       }
       catch (IOException ignore) {
       }
}


text:
Q: Getting unspecified value parameter scala Kafka Hi I am getting this compilation error -
Unspecified Value parameters: aggregator: (String, String, NotInferedVR) => NotInferedVR

But I clearly have an aggregator there already.  Does anyone know what's going on?
 val stream = builder
    .stream(inputTopic)(Consumed.`with`(Serdes.String(), Serdes.ByteArray()))
    .map{ (key: String, value: Array[Byte]) =>
      println(s"key = ${key}")
      val lv = GroupByAction.convertByteArrayToJsonObject(value)
      val lst = List.empty[String]
      val newKey = GroupByAction
        .reKey(lv
          , groupByColumnList
            .asScala
            .toList
          ,lst)
      val newValue = getValFromJSONMessage(lv, aggregateColumnList.asScala.toList.head)
      println(s"newKey = ${newKey}")
      (newKey, newValue)}
    .groupByKey(Serialized.`with`(Serdes.String(), Serdes.String()))
    .aggregate{ () => 0.toString, (k,v,vr: Long) => (v.toString.toLong + vr.toString.toLong).toString }

A: You can only use the {} form of method call to pass a single parameter, which is treated as a block. You need to pass two parameters, so use () instead:
aggregate( () => 0.toString, (k,v,vr: Long) => (v.toString.toLong + vr.toString.toLong).toString )


text:
Q: rc.local can't launch my program (raspbian linux) I have a c++ program that is running perfectly fine if I run it by executing,
sudo /Morreels/./launcher

Sadly the same line (without sudo) won't work in the rc.local file on startup...
When trying to execute rc.local on startup it gives me the following error:

failed to start rc.local see compatibility 'systemctl-daemon'

When I try to start the rc.local service by executing :
service rc.local start

Then it gives me the following error

Unit file of rc.local service changed on disk, 'system daemon-reload' recommended. Job for rc-local.service failed. See 'systemctl status rc-local.service' and 'journalctl -xn' for details

Below (picture) I have what I get when typing :
'systemctl status rc-local.service'
My program (launcher) relies on MySQL & A connection between arduino and ModBusMaster(485), I have been thinking that maybe these services haven't been started and thats why it fails, but I cant seem to find how to include those services into the startup list (as in msconfig for windows)

A: Simply adding my sudo /Morreels/./launcher line to the .bashrc file in
/home/pi folder ran everything and fixed it !


text:
Q: Two line charts as fill delimiter? Do you have any idea of how to achieve this?

Thanks in advance

A: Just in case someone is looking for the same approach... As @Wingzero said, his solution requieres a pretty advanced knowledge on CoreGraphics. What I did is modified the framework and make the lines render in front of the content. With that, Added 2 lines: the first one with a fill color green with an alpha of 0.5 and the second one with a fill color of the same color of the background color and a alpha of 1 :)


text:
Q: SSH, run process and then ignore the output I have a command that will SSH and run a script after SSH'ing. The script runs a binary file.
Once the script is done, I can type any key and my local terminal goes back to its normal state. However, since the process is still running in the machine I SSH'ed into, any time it logs to stdout I see it in my local terminal.
How can I ignore this output without monkey patching it on my local machine by passing it to /dev/null? I want to keep the output inside the machine I am SSH'ing to and I want to just leave the SSH altogether after the process starts. I can pass it to /dev/null in the machine, however.
This is an example of what I'm running:
cat ./sh/script.sh | ssh -i ~/.aws/example.pem ec2-user@11.111.11.111

The contents of script.sh looks something like this:
# Some stuff...

# Run binary file
./bin/binary &

A: Solved it with ./bin/binary &>/dev/null &

A: Copy the script to the remote machine and then run it remotely. Following commands are executed on your local machine.
 $ scp -i /path/to/sshkey /some/script.sh user@remote_machine:/path/to/some/script.sh

 # Run the script in the background on the remote machine and pipe the output to a logfile. This will also exit from the SSH session right away.
 $ ssh -i /path/to/sshkey \
    user@remote_machine "/path/to/some/script.sh &> /path/to/some/logfile &"

Note, logfile will be created on the remote machine.
 # View the log file while the process is executing
 $ ssh -i /path/to/sshkey user@remote_machine "tail -f /path/to/some/logfile"


text:
Q: Input type file as prop I have a page with a browse button, I'm trying to pass to a child component ( <attachment /> component) the browsed file but for some reason the <AttachedFile /> component always gets the props as {}, what am I missing?
Attachment page:
export default class Attachment extends React.Component {
  state = {
    attachment: {},
  };

  handleAddAttachment = file => {
    this.setState({ attachment: file });
    this.props.handleChange('attachment', file);
  };

  render() {
    const { attachment } = this.state;

    return (
      <Fragment>

            Do you have

            something to <LineBreak />
            show me?

Upload attachments here

          <AttachmentButton  handleAddAttachment={this.handleAddAttachment} />
          <AttachedFile attachment={attachment} />

      </Fragment>
    );
  }
}

AttachmentButton Component:
export default function AttachmentButton({ styles, handleAddAttachment }) {
  const handleUpload = file => {
    handleAddAttachment(file);
  };
  return (

          <input type="file" css={selectButton} onChange={e => handleUpload(e.target.files[0])} />
          Select file

  );
}

AttachedFile Component:
export default function AttachedFile({ attachment }) {
  console.log(attachment);
  return (
      <NavLink to="./" css={text}>
        {attachment.name}
      </NavLink>
  );
}

A: It seems that you are not calling handleAddAttachment. So the attachment is always {}.


text:
Q: comboboxes in Windows API programming I am trying to display  a combobox window as you can see I  set hWndComboBox as my second window and I am using ShowWindow() function and it does not really show anything when I compile and run the code? What should I add more?
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstace, LPSTR lpCommand, int nCmdLine)
{
    HWND window;
    int xpos = 100;            // Horizontal position of the window.
    int ypos = 100;            // Vertical position of the window.
    int nwidth = 200;          // Width of the window
    int nheight = 200;         // Height of the window
    HWND hwndParent =  window; // Handle to the parent window

    MSG message;
    WNDCLASSEX wndClass;

    wndClass.cbSize = sizeof(WNDCLASSEX);
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.style = 0;
    wndClass.hInstance = hInstance;
    wndClass.lpfnWndProc = wndCll;
    wndClass.lpszClassName = classNoOne;
    wndClass.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU);
    wndClass.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PENGUIN_ICON));
    wndClass.hIconSm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PENGUIN_ICON), IMAGE_ICON, LR_DEFAULTSIZE, LR_DEFAULTSIZE, 0);
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW-1);

    if(!RegisterClassEx(&wndClass)){
        printf("No wndclass");
    }
    window = CreateWindowEx(WS_EX_CLIENTEDGE, classNoOne, "Start Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1000, 500, NULL, NULL, hInstance, NULL);
        //create the window
    HWND hWndComboBox = CreateWindow(WC_COMBOBOX, "name of the combobox",  CBS_DROPDOWN | CBS_HASSTRINGS | WS_CHILD | WS_OVERLAPPED | WS_VISIBLE , xpos, ypos, nwidth, nheight, hwndParent, NULL, hInstance, NULL);
    TCHAR Planets[9][10] = {
        TEXT("MERCURY"), TEXT("VENUS"), TEXT("Terra"), TEXT("MARS"), TEXT("JUPITER"), TEXT("SATURN"), TEXT("URANUS"), TEXT("NEPTUNE"), TEXT("PLUTO")
    };
    //these are the list elements
    TCHAR A[16];
    int k = 0;
    memset(&A, 0, sizeof(A));
    //allocate memory
    for(k = 0; k<=8; k+=1){
    strcpy(A, (TCHAR *)Planets[k]);
      SendMessage(hWndComboBox,(UINT) CB_ADDSTRING,(WPARAM) 0,(LPARAM) A);
    }
    SendMessage(hWndComboBox, CB_SETCURSEL, (WPARAM)2, (LPARAM)0);
    ShowWindow(hWndComboBox, nCmdLine);
   //ShowWindow(window, nCmdLine);
    if(window == NULL){
        printf("window is NULL");
    }

    while(GetMessage(&message, NULL, 0, 0) > 0){
            if(!IsDialogMessage(dialogSmall, &message)){
                TranslateMessage(&message);
                DispatchMessage(&message);
            }
    }
    return message.wParam;
}

A: Programming languages do not work like mathematics.  In mathematics you can say x = y;  and then say y = 5;  and then you can infer that x must be 5.
In programming languages however, when you say HWND hwndParent =  window; then hwndParent takes the value that window had at the moment of the assignment, so if you later actually initialize window with window = ... you cannot expect the value of hwndParent to suddenly become meaningful.  It will stay uninitialized, since window was uninitialized at the time of the assignment.
Hint: if you have been able to do HWND hwndParent =  window; when window was uninitialized, this means that you received no warning about it.  Which in turn means that you have not configured your compiler to issue warnings when you do things like that.  Do not try to program without warnings.  You will never accomplish much this way.


text:
Q: Powershell fastest way to merge two arrays using a common property? What's the fastest way to merge two arrays using a common property?
Users | Select *
Username : Joe.Doe
Office   : Chicago
Email    :

Username : Mike.Smith
Office   : New York
Email    :
...

UserEmails | Select *
AccountEmail  : Mike.Smith
EmailAddress  : mike-smith@example.com

AccountEmail  : Joe.Doe
EmailAddress  : jsmith12@example.com
...

The merge should result in:
UsersCompleteList | Select *
Username : Joe.Doe
Office   : Chicago
Email    : jsmith12@example.com

Username : Mike.Smith
Office   : New York
Email    : mike-smith@example.com
...

Something like for each ($user in $users) { ($user.Email = $userEmails | ? { $_.AccountEmail -eq $user.Username}).EmailAddress takes ages on large datasets.

A: Loop through one collection and store the values in a hash. Then loop through the other collection and pull the value back out of the hash. Something like:
$hash = @{}
$userEmails | %{ $hash[$_.AccountEmail] = $_.EmailAddress }
$users | %{ $_.Email = $hash[$_.Username] }

If you have other properties you can just store the original object:
$hash = @{}
$userEmails | %{ $hash[$_.AccountEmail] = $_ }
$users | %{
   $item = $hash[$_.Username]
   $_.Email = $item.EmailAddress
   $_.Other = $item.SomethingElse
}

Or with loops instead of ForEach-Object including:
$hash = @{}
foreach($e in $userEmails) {
  $hash[$e.AccountEmail] = $e
}
foreach($u in $users) {
  $item = $hash[$u.UserName]
  if ($item -ne $null) {
    $u.Email = $item.EmailAddress
  }
}


text:
Q: Configure microcontroller flash memory as ram? Is there anyway i can use micro-controllers flash memory as a RAM as i need 150kB of buffer but controller has 32kB of RAM and 512kB of Flash? Also can i use this ram as stack or heap?

A: No, flash is flash, RAM is RAM.
The micro can probably program its own flash if you needed to calculate a look up table or similar, but you can't use it as you would a RAM.
The RAM you do have can probably be configured as stack and heap, these sections will be defined in a linker script, the format for which is toolchain dependant so check your compiler and linker's manual.


text:
Q: Detect when orientation change has ended Is there a way to detect when a user has finished changing the orientation of their mobile device, I'm using this event to detect when orientation changes, but I'd like to detect when orientation change has ended. Thanks
$( window ).on( "orientationchange", function( event ) {
...

A: From orientationchange docs, emphasis mine

The orientationchange event is fired when the orientation of the device changed.


text:
Q: Not sure my delta time function in C++ has the right logic I've been working on making a basic game loop in C++ and I'm unsure my logic is completely right as my delta time isn't what I expect. I expect to get 1/60 seconds per frame as my cap is 60fps, but over the average I take I get a delta time of ~0.03 seconds per frame giving me 33fps. I know the program can run faster than this as if I raise the frame cap it has a smaller delta time, which is still inaccurate. Any help? (I've removed unimportant bits of code to focus on the logic)
using namespace std::chrono;

int main(void)
{
    //Init time - start and end, with delta time being the time between each run of the loop
    system_clock::time_point startTime = system_clock::now();
    system_clock::time_point endTime = system_clock::now();
    float deltaTime = 0.0f;

    //*Game made here*

    /* Loop until the user closes the window */
    while (window is not closed)
    {
        //Takes time at start of loop
        startTime = system_clock::now();
        deltaFrameCount++;

        //Handle game processes

        //Get time at end of game processes
        endTime = system_clock::now();

        //Take time during work period
        duration<double, std::milli> workTime = endTime - startTime;

        //Check if program took less time to work than the cap
        if (workTime.count() < (milliseconds per frame cap))
        {
            //Works out time to sleep for by casting to double
            duration<double, std::milli> sleepDurationMS((milliseconds per frame cap) - workTime.count());
            //Casts back to chrono type to get sleep time
            auto sleepDuration = duration_cast<milliseconds>(sleepDurationMS);
            //Sleeps this thread for calculated duration
            std::this_thread::sleep_for(milliseconds(sleepDuration.count()));
        }

        //get time at end of all processes - time for one whole cycle
        endTime = system_clock::now();
        duration<double, std::milli> totalTime = endTime - startTime;
        deltaTime = (totalTime / 1000.0f).count();
    }

    //cleans game
    return 0;
}


text:
Q: Find the number of 4 digit positive integers if the product of their digits is divisible by 3. Find the number of 4 digit positive integers if the product of their digits is divisible by 3.

Let $abcd$ be the required number.For the product of digits of this number is to be divisible by 3,atleast one digit has to be 3,6 or 9.
Total there are 9000 four digit numbers.
The possible combinations are 3 and three other digits,33 and two other digits,333 and one other digit,3333,6 and three other digits,66 and two other digits,666 and one other digit,6666,9 and three other digits,99 and two other digits,999 and one other digit,9999.
I dont know how to solve further.

A: How many have a digit product that is not divisble by $3$? You can then only use $6$ digits for all digits as also $0$ is forbidden for all digits. In total, as you said, there are $9000  =9\times 10^3$ $4$-digit numbers..

A: total numbers=9000.If a number has at least one of digit as 0,3,6,9 then the product can be divisible by 3.So left digits are 1,2,4,5,7,8 i.e 6 digits.total numbers by these 6 digits are 6^4=1296.
so total numbers divisible by 3 are:
9000-1296=7704.


text:
Q: crop image borders in wordpress post I have a lot of  images in many wordpress posts that have borders, 10px on each side.
How can I crop them away ?
I searched for plugins but couldn't find one that does the job
any help is appreciated
thanks in advance


text:
Q: \listoffigures does not display the caption of the figures I am currently writing my thesis and need to create a list of figures (and tables, but have not reached that point yet). I have successfully created the actual list, but it does not display the caption or label of the figures. Additionally, there are no spaces in the listings.
It looks like this (see attached picture):

And I would like it to be displayed in this format:
Figure number, the actual caption that I wrote OR the label I chose, Page number.
Ex: Fig 2.2, System Boundaries LCA, 18
The code used for the list of figures:
 % List of figures (add to table of contents)
\cleardoublepage
\addcontentsline{toc}{chapter}{\listfigurename}
\listoffigures

This is the code I have used to insert my figures: (in case I have made an error here and that is why it does not work.)
\begin{figure} [H]
    \centering
    \includegraphics[width=\textwidth] {figure/Images/System boundariesLCA.JPG}
    \caption{Life cycle stages for a building according to the standard SS-EN 15978 \citeyear{StandardLCA2011} }
    \label{fig:System Boundaries LCA}
\end{figure}

Thanks in advance!


text:
Q: Can't connect to internet Lubuntu 18.04 I can't connect to the internet with my Lubuntu 18.04. It shows the wifi adapter with the signal bars and says that it's connected, but Firefox says: can't connect to server and Sudo apt-get update says Failed to Fetch.

A: Take the following steps:

*

*open a terminal by pressing Ctrl+Alt+T

*In the terminal type:
ping www.google.com

*You will probably get time out as reply or not a reply at all

*Press Ctrl+C to stop the ping command.

*In the terminal now type:
ping 1.1.1.1

This will try to ping Cloudflare's DNS. If you get replies then the problem lies within your DNS server.
If you don't get a reply then you are not connected to the Internet through your router. (which is en issue outside of Ubuntu and off-topic here)


text:
Q: Get most frequent value(s) from a list of lists I am trying to convert an LDA prediction result, which is a list object containing hundred of list (of topics (in numeric) assigned to each token in a document), such as the following example
assignments <- list(
  as.integer(c(1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3)),
  as.integer(c(1, 1, 1, 2, 2, 2, 2, 2, 3, 3)),
  as.integer(c(1, 3, 3, 3, 3, 3, 3, 2, 2))
)

where each list of the list object has different length corresponding to the length of each tokenized document.
What I want to do are to 1) get the most frequent topic (1, 2, 3) out of each list, and 2) convert them into tbl or data.frame format like this
document  topic   freq
   1        1       6
   2        2       5
   3        3       6

such that I can use inner_join() to merge this "consensus" prediction with the topic assignment results generated by tm or topicmodels applications and compare their precision, etc. Since the assignments is in list format, I cannot apply top_n() function to get the most frequent topic for each list. I tried sing lapply(unlist(assignments), count), but it didn't give me what I want.

A: You can iterate over the list with sapply, get frequency with table and extract first value from sorted result:
result <- sapply(assignments, function(x) sort(table(x), decreasing = TRUE)[1])
data.frame(document = seq_along(assignments),
           topic = as.integer(names(result)),
           freq = result)

  document topic freq
1        1     1    6
2        2     2    5
3        3     3    6

A: We can loop through the list, get the frequency of elements with tabulate, find the index of maximum elements, extract those along with the frequency as a data.frame and rbind the list elements
do.call(rbind,  lapply(seq_along(assignments), function(i) {
        x <- assignments[[i]]
        ux <- unique(x)
        i1 <- tabulate(match(x, ux))
    data.frame(document = i, topic = ux[which.max(i1)], freq = max(i1))})
 )
#    document topic freq
#1        1     1    6
#2        2     2    5
#3        3     3    6

Or another option is to convert it to a two column dataset and then do group by to find the index of max values
library(data.table)
setDT(stack(setNames(assignments, seq_along(assignments))))[,
  .(freq = .N), .(document = ind, topic = values)][, .SD[freq == max(freq)], document]
#    document topic freq
#1:        1     1    6
#2:        2     2    5
#3:        3     3    6

Or we can use tidyverse
library(tidyverse)
map(assignments, as_tibble) %>%
    bind_rows(.id = 'document') %>%
    count(document, value) %>%
    group_by(document) %>%
    filter(n == max(n)) %>%
    ungroup %>%
    rename_at(2:3, ~c('topic', 'freq'))
# A tibble: 3 x 3
#  document topic  freq
#  <chr>    <int> <int>
#1 1            1     6
#2 2            2     5
#3 3            3     6

A: using purrr::imap_dfr :
library(tidyverse)
imap_dfr(assignments,~ tibble(
  document = .y,
  Topic = names(which.max(table(.x))),
  freq  = max(tabulate(.x))))

# # A tibble: 3 x 3
#   document Topic  freq
#      <int> <chr> <int>
# 1        1     1     6
# 2        2     2     5
# 3        3     3     6


text:
Q: Powershell can't execute binary file I recently installed RabbitMQ on my system and was trying to enable a plugin functionality. This is the command I used (as per their docs):
./rabbitmq-plugins enable rabbitmq_management

rabbitmq-plugins is a file in a folder:
C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.15\escript

On running the line a dialogue opens up asking "How do you want to open this file?"
I tried running it via Git Bash with no luck as well. After tinkering about and setting erlang in path and some RabbitMQ specific environment variables I got stuck at:
Error: :no_plugins_file

Powershell still exhibits the same behavior. I even used Set-ExecutionPolicy to give unrestricted access to the CurrentUser as well as the LocalMachine. No change.

A: rabbitmq should have a rabbitmq-plugins.bat file in \rabbitmq_server-x.x.x\sbin. Execute that file instead of the binary:
rabbitmq-plugins.bat enable rabbitmq_management

see: https://cmatskas.com/getting-started-with-rabbitmq-on-windows/


text:
Q: Use rsync with passthru() in a php program I have a very simple php program that I am running with a cron.
<?php
$cmd="rsync  --ignore-existing -raz --progress /home/account1/public_html/inventory/images home/account2/public_html/inventory/";
passthru($cmd);
exit(0);?>

Both account1 and account2 are on my dedicated server. The program is run on account2
That command runs perfectly when run manually. But when I run the program it fails. Do I need to include the username and password of account1? How would I do that?


text:
Q: Users access to subsite but no acces to root site In SP2013, I have AD users. I have :

*

*site1

*
*

*subsite1

*
*

*
*

*sub_subsite1

*
*

*
*

*sub_subsite2

I want the users to access to sub_subsite1, for example, but no access to subsite1 or site1.
I know this is possible, but I'm getting confused by googling that.
I'm sure this is pretty simple for you :)
Thanks in advance.

A: the sub sites by default inherit permission from the parent site.
you can go to --> Site Setting --> Site permissions of your sub site i.e sub_subsite1
and click on stop inheriting Permission and add your user to that site.also remove the user from the parent site.the user can access only the sub site.


text:
Q: Hot to use coqui-ai TTS to turn a text file to audio? I want to use coqui-ai TTS but it has problems dealing with short sentences so I've made a go script to only keep the sentences that don't give an error when converting and then merging all the audios.
The script works fine for the most part but on the small sentences it makes weird sounds and usually produces longer audios than it should.
I think the best thing to do is figure out what is the average audio length per character and if a sentence's audio length is above the expected length by a certain margin truncate the excess. How could I do this in go?
This is the code
package main

import (
    "log"
    "os"
    "os/exec"
    "strconv"

    "github.com/cheggaaa/pb/v3"
    "github.com/neurosnap/sentences/english"
)

func main() {
    if len(os.Args) != 2 {
        log.Fatalf("Usage: go run main.go <input>")
    }
    sentences := get_sentences()
    audio_files := convert_text_to_audio(sentences)
    concatenate_audio_files(audio_files)
}

func get_sentences() []string {
    tokenizer, err := english.NewSentenceTokenizer(nil)
    if err != nil {
        panic(err)
    }
    text, err := os.ReadFile(os.Args[1])
    if err != nil {
        log.Fatal(err)
    }
    tmp := tokenizer.Tokenize(string(text))
    var sentences []string
    for _, sentence := range tmp {
        sentences = append(sentences, sentence.Text)
    }
    return sentences
}

func convert_text_to_audio(sentences []string) []string {
    var audio_files []string
    bar := pb.StartNew(len(sentences))
    for i, sentence := range sentences {
        audio_file := "out_" + strconv.Itoa(i) + ".wav"
        cmd := exec.Command("tts", "--text", sentence, "--model_name", "tts_models/en/ljspeech/tacotron2-DDC", "--out_path", audio_file)
        err := cmd.Run()
        if err != nil {
            log.Println(cmd.String())
            log.Println("Failed to run coqui-ai tts")
        } else {
            audio_files = append(audio_files, audio_file)
        }
        bar.Increment()
    }
    bar.Finish()
    return audio_files
}

func concatenate_audio_files(audio_files []string) {
    audio_files = append(audio_files, "out.wav")
    cmd := exec.Command("sox", audio_files...)
    err := cmd.Run()
    if err != nil {
        log.Fatalf("Failed to run sox")
    }
}


text:
Q: share samba drive with windows without having to allow guest access I am trying to set up a simple samba share between my raspberry pi and my windows 10. This is my config:
[global]
   min protocol = SMB2
   workgroup = WORKGROUP
   wins support = no
   dns proxy = no
   guest account = nobody
   interfaces = 127.0.0.1, 192.168.2.0/24
   bind interfaces only = yes
   hosts allow = 127.0.0.1 192.168.2.0/24
   hosts deny = 0.0.0.0/0
   log file = /var/log/samba/log.%m
   log level = 1
   max log size = 1000
   panic action = /usr/share/samba/panic-action %d
   security = user
   server role = standalone server
   passdb backend = tdbsam
   obey pam restrictions = yes
   unix password sync = yes
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
   pam password change = yes
   encrypt passwords = yes
   map to guest = never
   usershare allow guests = no
   auto services = pi

#======================= Share Definitions =======================

[homes]
   comment = Home Directories
   browseable = no
   read only = yes
   create mask = 0700
   directory mask = 0700
   valid users = %S
[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700
[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
[pi]
   comment = pi samba share
   path = /home/shares/pi
   browseable = yes
   writeable = true
   admin users = pi
   public = no
   valid users = pi
   hide dot files = no

In order for this to work, I had to follow this article Guest access in SMB2 to change the registry keys for allowing guest access.
What would I need to change in my config so that I don't have change any registry keys for everything to work (meaning: I can successfully access /home/shares/pi from my Windows 10)?
I have various settings in my config that, to my understanding, prohibit guest access, so I don't understand why I still had to enable it.

A: You have two possible approaches:

*

*You can access the files as guest.

*You can configure accounts that have to authenticate.

A guest account is fine if all the users should have access anyway, but it's not what you desire, so you must configure one ore more accounts. Samba allows different kinds of accounts, they are configured with the passdb backend option:

*

*smbpasswd - The old plaintext passdb backend. Some Samba features will not work if this passdb backend is used. Takes a path to the smbpasswd file as an optional argument.

*tdbsam - The TDB based password storage backend. Takes a path to the TDB as an optional argument (defaults to passdb.tdb in the private dir directory.

*ldapsam - The LDAP based passdb backend. Takes an LDAP URL as an optional argument (defaults to ldap://localhost)
The smbpasswd is the oldest and most simple, it's just a plain file similar to /etc/passwd. The tdbsam uses a binary tdb file and can store more information about user accounts. LDAP is more interesting if you want to manage many accounts and/or already have an LDAP server.
See also smbpasswd for adding accounts and changing password.


text:
Q: HTML.Checkboxfor to Toggle button HTML? Is there anyway to convert the @HTML.Checkboxfor into toggle html button?
I have refer the toggle button style from https://www.w3schools.com/howto/howto_css_switch.asp
Currently its working by using :
@Html.CheckBoxFor(model => model.IsEnabled, new { @checked = "checked", @Name = "DelegateChkBox" })

Changed to:

            <input name="DelegateChkBox" id="IsEnabled" type="checkbox" value="true" data-val-required="The IsEnabled field is required." data-val="true" data-bind="checked: IsEnabled">

The toggle button only works and postback to controller if it's CHECKED:

else it won't postback to controller by default UNCHECKED :

Any help will be appreciated!
Thanks!

A: This is very simple, I have implemented in my project.
You just need to keep the value of checkbox in a HiddenFor.
@Html.HiddenFor(model => model.IsEnabled, new{@id = "DelegateChkBox"})

Then display your Toggle button in the page. For example,

    <input name="DelegateChkBox" id="IsEnabled" type="checkbox" value="true"
      data-val-required="The IsEnabled field is required." data-val="true"
      data-bind="checked: IsEnabled">

So now when user check/uncheck the checkbox, call a jquery method and assign the value to @Html.HiddenFor(..). That's it.
$('#IsEnabled').change(function(){
  if($(this).val()==true)
   {
    $('#DelegateChkBox').val(true);
   }
  else
   {
    $('#DelegateChkBox').val(false);
   }
})

Please check once this if ($("this").is(":checked")) instead if($(this).val()==true) and assign the value accordingly. Little busy, could not check my code :)
That's it. Now when you post back your page, you already set value to your IsEnabled field.
In Get method you have to do like the same. You just need to check the value of your HiddenFor() and take that value and assign to your HTML Toggle button in pageload event of js.
$(function() {
 if($('#DelegateChkBox').val()== true)
  {
   $('#IsEnabled').prop("disabled", false);
  }
 else
  {
   $('#IsEnabled').prop("disabled", true);
  }
});

That's it. Please change the HTML accordingly.

A: Based from some experiments and findings, I found that you need to include hidden field generated by the helper (Html.CheckBoxFor) as shown by styling below:

View usage example (just change <input type="checkbox" /> to @Html.CheckBoxFor):

    @Html.CheckBoxFor(model => model.IsEnabled)

To ensure the checkbox is being checked in client-side before doing postback, you can use jQuery code below:
// change event may modified to other events
$("#IsEnabled").change(function () {

    // check if checkbox is being checked
    // taken from /a/23007488 by Alexandru Chichinete
    if ($("#IsEnabled").is(":checked"))
    {
        // enable form submit
    }
});

Demo example: .NET Fiddle
References:
Styling checkboxes in MVC 4
How can I apply a CSS style to Html.CheckBoxFor in MVC 5
@Html.checkboxfor - Get checkbox value using id


text:
Q: Display app name on two lines below the app icon My android app has a two word app name, and the 2nd word doesn't fit on the first line below the app icon.  The OS doesn't automatically carry the 2nd word over to the 2nd line so it just gets cut off.  I was able to use a "\n" as part of the app name string instead of a space, and that forced the 2nd word to display on the 2nd line.  However, when I try to upload my app on the market I get an error (about the icon being improperly formatted, which really means that I have a newline in my app name, google needs to get their error messages straight but that's a different topic).
So, I've seen other apps on the market that don't have a problem showing the 2nd word in the app name on a second line.  How do I do the same and get past the market upload?
Thanks.

A: From what I understand, this is a feature, not a bug. Only custom roms seem to allow more than one line for the names.

A: Even my application had two lines application name. Earlier the name was shown as only one line application name. I just uninstalled the application from device and re-installed it and my problem is solved.
May this helps someone.

A: \r\n worked for me, add it where you want to line break

A: I'd look at some projects that do not have the problem, see how they define things in their manifest and string resources, and try to match them. Barcode Scanner (ZXing) is one such app. This sample app from one of my books also successfully has its two-word name split over two lines.


text:
Q: How to check if the laptop has infrared receiver in linux I want to know if my laptop has infrared receiver in linux terminal. I was wondering if there is a terminal command that I can use to see if the laptop has an infrared receiver?
I know one way is to check if there is a dark glass part in front of it, but that's not an option unfortunately.

A: lshw will show you the system's view of your hardware. man lshw.
You might have to apt-cache search lshw and sudo apt-get install lshw.


text:
Q: Inequality $e^x-1+e^x(1-\cos \pi y+\sin \pi y)<1$ Find a ranges of $x,y\in \mathbb R^+$ in which the following inequality is verified
$$e^x-1+e^x(1-\cos \pi y+\sin \pi y)<1$$
My approach:
$$2-\cos \pi y+\sin \pi y<\frac{2}{e^x}\leq 2$$
Then
$$-\cos \pi y+\sin \pi y<0$$
that have solution in $y\in(0,1/4)$. Instead, if we isolate the $x$, we have:
$$x<\ln\left(\frac{2}{2-\cos \pi y+\sin \pi y}\right)$$
and $x< \ln2$ in $y\in(0,1/4)$. Then $(x,y)\in (0,\ln2)\times(0,1/4)$. Is my procedure right? I made a mistake?
Thank you very much

A: As $x$ and $y$ are different variables, look for the maximum value of $1 - \cos \pi y + \sin \pi y$. In any case, this looks unlikely: If the last expression is ever larger than $-1$, you have an exponential multiplying a positive value, selecting $x$ large enough gives larger than 1.

A:
Your inequality is satisfied in the blue region to the left. (You should be able to pull it off the screen to examine it in more detail.) It looks like (0,0), ($ln(2)$,0), (0,1/4) , bound by the axes and the boundary of the curve in that region


text:
Q: Read Only Domain Controller for standalone/off-site testing location In a bit of a pinch: a client needs to test an Active Directory enabled CRM system that consists of a SQL 2008 Server and a Windows 2008 Standard Server (the application server).  As far as I know, Active Directory is required for end-user authentication and for application-to-SQL authentication.
We need to pull these two servers out of their current domain environment and setup at a testing facility that has Internet connectivity, but is not on the domain (foo.local) or any domain for that matter; they're just a bunch of workstations in a workgroup at the moment.
My initial thought was to setup an IPSec tunnel to the client's location to/from the testing facility, but I'm wondering if the LAN subnet overlap would be a pain (pfSense firewalls here) to manage and/or if changing the IP addresses of the two servers (FOOAPP and FOOSQL) to a different subnet to avoid the overlap would cause some grief in AD land (i.e. the domain controller would not "know" who these servers are).
My other thought was to setup a Read Only Domain Controller and bring it on-site to the testing facility, but from my cursory reading of the technet docs, it sounds like it needs to be able to talk to the client location domain controller(s).
Lastly, I know you can authenticate a workstation off-line with cached credentials: would that work with a member server?  I'm assuming not as the SQL authentication that takes place between FOOAPP and FOOSQL probably does not utilize caching at all, but please enlighten me if not.
Any other options?
CLARIFICATION
These servers aren't being used in production right now.  While they're joined to the customer's domain, there's no data in it and nobody's using it; they're just idle member servers at the moment.  The SQL database will be loaded with test data and then used for training, but we'll be putting them back into the client's location and thus into production after this user acceptance/end-user training period is completed (with the test data removed).
We can't do the testing/training on-site because it would be too disruptive to the client's office and they don't have a large board room to accommodate the testing/training groups.
EDIT
I guess this can all be distilled into two questions:

*

*What happens to a (Read Only | Writable) domain controller when it's isolated from other domain controllers?

*Does Active Directory "care" about IP addresses?  i.e. perhaps I can put these two servers on a different subnet temporarily and setup an IPSec tunnel so that these servers and workstations at the testing facility can communicate with the domain at the client's office.

A: Active Directory functions by default in a multimaster replication mode, where each domain controller is independently authoritative for the domain(s) it manages. Thus, the test DCs will still be able to handle logins and receive updates (password changes and the like) even while disconnected. The two sets of DCs (the live ones and the ones in the test site) will slowly diverge over time, but that's only a problem if you intend to converge them afterwards.
Here is my suggestion for handling this scenario:

*

*Take a full system state backup of each testing domain controller before relocating them.

*Relocate the test DCs and get them settled in (join the workstations to the domain, create users, etc.).

*Run your tests.

*When you're ready to restore the DCs to production service, do a non-authoritative restore of the system state backups you took earlier. This will reset the DCs to their previous system state (of course).

*Return the test DCs to their original network and power them back on. They'll recognize that their copies of the Active Directory data are woefully out of date (due to the ancient USNs), and start sending replication requests to the production DCs that have been there the whole time.

A: As this is for testing only have you considered running a VM on one of the machines and setting that up as a DC? Something like Virtualbox, despite not being a good choice for production use, would do fine in this case.

A: 1) When a standard DC is isolated from other DCs in the domain, it will continue to perform all of its functions, because every AD DC is able to work on its own; you'll only run into problems if you need access to one of the FSMO roles (such as performing a schema extension or running out of RIDs for new users), but this only happens in some very specific situations you're not likely to run into in a test environment. Of course, if you perform any modification to AD on one of the two segments (such as creating a user account or even changing a password), this will not be replicated to the other one... and if you ever plan about reconnecting them, you'll very likely run into replication conflicts.
This doesn't apply to RODCs: if one of them is isolated from the rest of the network and you don't have any writable DC available (even through a WAN link), most AD functions will be unavailable; you will not be able to create/modify anything, and this of course includes joining computers to the domain, managing user accounts ang groups, etc.
2) AD cares about IP addresses for two things: replicating data and locating the "nearest" available domain controller to avoid unnecessary WAN traffic; both functions rely on the definition of sites, subnets and site links. If you want to setup a WAN link to a location with a different IP addressing than your main LAN and put a DC there, you will need to define a site and a subnet in the Active Directory Sites and Services console; this will allow AD to manage replication between the DCs in the main location and the off-site one, and also will tell servers and clients in that location to talk to the local DC.

A: Here's what I would propose:
Set up an isolated network on the current ESXi host. Clone the existing servers needed for the test and bring them up on the isolated network. If need be, you can sieze the FSMO roles on the isolated DC, as it's isolated from the production network this won't have any ramifications for the production network. Join a test client to the isolated domain and perform your testing.
This seems like the easiest solution to me.

A: One issue you absolutely must consider when moving a DC to offline (as far as the production network is concerned) is that if it is off the production network longer than the tombstone time, it may contain objects that have been removed from the production network (known as lingering objects) and there can be consistency problems when it is reconnected to the production network.  I've experienced such problems and it wasn't pretty.
It doesn't have to be problematic if you just take care of a couple issues in the process.  If the domain was originally Windows 2000 and upgraded to 2003, the tombstone age is 60 days where if it started out as a Windows 2003 domain, tombstone age is 180 days.  You can change the tombstone age, but this requires going in with ADSIedit or other tool to directly modify the Directory Service partition of Active Directory and I don't know if you would be comfortable with that or not.  (the path is: CN=Directory Services,CN=Windows NT,CN=Services,CN=Configuration,DC=yourdomain,DC=yourdomainsuffix) This will make Active Directory take up more space on your DCs since they will hold on to all removed objects longer before actually completely deleting them.
Before disconnecting the off site DC you should be sure to do a time sync to minimize any time drift while it is off site.  The important part is when reconnecting, you should first configure strict replication consistency on the production network DCs prior to reintroducing the off site DC (using the Repadm tool with the /regkey switch) and be sure to set the off site DC up for a nonauthoritative restore, also prior to the reconnection, so it will get the new SYSVOL replicated to it as soon  as possible.


text:
Q: Autoload netrw when starting vim I want netrw to autoload when I launch vim using the terminal. Completely new to linux/ubuntu. Is there any way of doing that?

A: Adding the following to your .vimrc (Vim's configuration file, located in the root of your home directory) will cause Vim to automatically load Netrw after starting up.
" Open Netrw after Vim starts up
augroup InitNetrw
  autocmd!
  autocmd VimEnter * :silent! Explore
augroup END

A problem with the preceding approach, as implemented, is that Netrw will also load when you use Vim with an argument to open a specific file. A workaround is to use the following modification, based on the suggested approach in Netrw's documentation (:help netrw-activate).
" Checks if there is a file open after Vim starts up,
" and if not, open the current working directory in Netrw.
augroup InitNetrw
  autocmd!
  autocmd VimEnter * if expand("%") == "" | edit . | endif
augroup END

The following pages have more details on autocommands and the .vimrc configuration file.

*

*https://learnvimscriptthehardway.stevelosh.com/chapters/12.html

*https://learnvimscriptthehardway.stevelosh.com/chapters/14.html

*https://learnvimscriptthehardway.stevelosh.com/chapters/07.html

A: And the following code block in your vimrc:
set autochdir
let g:netrw_browse_split=4
augroup InitNetrw
    autocmd!
    autocmd VimEnter * if argc() == 0 | Lexplore! | endif
augroupend

Kind of does what @dannyadam suggested. But opens the netrw pane as a side bar on the right. If you want to be on the right use Lexplore without the bang(!).


text:
Q: Salesforce PageBlockTable Render an Item's Grandparent I'm trying to display the grandparent of a custom Salesforce Object in a pageblocktable in a Visualforce page.
I can display the parent as expected ie:
<apex:column headerValue="Related Item Parent">
    <apex:outputField id="ItemParent" value="{!item.Parent__c}" />
</apex:column>

works great and gives me a nice table with a 'Related Item Parent' column that is linked to the Item parent exactly as I wanted.
but when I try to go up a further level, the Visualforce Page editor tells me

Could not resolve the entity from  value binding
  '{!item.Parent_c.Parent_c}'.  can only be used
  with SObject fields.

Is there anyway that this can be made to work?  I'm a bit stuck!!
Below is the complete listing for my pageBlockTable , which works correctly if the Related Item Grandparent column is removed.
<apex:pageBlockTable id="RelatedItems" value="{!contact.RelatedItems__r}" var="item">

    <apex:column headerValue="Related Item Name">
        <apex:outputField id="ItemName" value="{!item.Name}" />
    </apex:column>

    <apex:column headerValue="Related Item Parent">
        <apex:outputField id="ItemParent" value="{!item.Parent__c}" />
    </apex:column>

    <apex:column headerValue="Related Item Grandparent">
        <apex:outputField id="ItemGrandParent" value="{!item.Parent__c.Parent__c}" />
    </apex:column>

</apex:pageBlockTable>

Really appreciate any help that anybody can provide.
Best regards
Pete

A: When referencing fields of relationship objects, you will want to use the __r suffix. For example, you could use item.Parent__c to refer to the Id of the parent record, but accessing any of the fields on that record would require something like item.Parent__r.Name.
In this instance, you're looking for {!item.Parent__r.Parent__c} (which will give you the Id of the grandparent), or even {!item.Parent__r.Parent__r.Name} (if you wish to access fields on the grandparent record).


text:
Q: When did the word "snafu" enter the colloquial vernacular? Roughly when did the word "snafu" enter the colloquial vernacular? It was a military term, but at some point it came into fairly common use among the general population. If you can narrow it down to a decade or so, that's good enough for me.
Additionally, if you could, tell me how you figured out the answer (teaching a man to fish and all...)

A: According to the Corpus of Historical American English (COHA) at BYU, snafu began appearing in popular print in the 1940s; in fact, the 1940s is the decade which has the most citations, at 22. For example, an "Army & Navy: Joe & Joe" column in the November 30, 1942 issue of Time provides the basic definition and a few examples.
This matches the Google Ngram. Appearances prior to 1940 appear to be OCR errors or nonsense words, but by 1943 you can find the term used in publications ranging from Yachting magazine to Life to the University of Michigan alumni magazine.

See Google NGram
A letter to the editor in the same complains:

… [Y]ou use the word "snafu." I find this puzzling because it is not listed in any dictionary, nor does it sound like any slang I have heard before.

to which the editors respond

Snafu is a service slang word compounded out of the initial letters of the words in a phrase politely translated: "Situation normal, all fouled up." Pernicious snafu is somethings called susfu, or "Situation unchanged,still fouled up."

By the end of the war, evidently, editors no longer needed to define the term for their audiences. Either its use in plays, films, and publications of the era or the omnipresence of the phenomenon in wartime had made it singularly useful.

A: As I have watched many military themed movies, I believe it has been in continual use since WWII's veterans returned to the US.  It would be interesting to understand the popularity of a word in relation to box office
SNAFU
1941, U.S. military slang, acronym for situation normal, all fucked up, "an expression conveying the common soldier's laconic acceptance of the disorder of war and the ineptitude of his superiors" ["Oxford English Dictionary"]. As an adjective from 1942. In public explanations the word typically was euphemised to fouled.


text:
Q: Resolving this error: "cannot transform sfc object with missing crs" I am attempting to outline a specific grouping of census tracts over entire US states.
This is the code I am attempting to run:
sf_states <- sf::st_as_sf(fifty_states, coords = c("long", "lat")) %>%
  group_by(id, piece) %>%
  summarize(do_union = FALSE) %>%
  st_cast("POLYGON") %>%
  ungroup()

illinois <- sf_states %>%
  filter(id == "illinois")

arlington.crs <- arlington.test %>%
  st_set_crs(4326)

ggplot() +
  theme_minimal() +
  geom_sf(data = illinois) +
  geom_sf(data = arlington.crs, col = "green", alpha = 0, size = 2)

The arlington.test data is coming from the tidycensus package and includes the associated geometry for each census tract.
However, when I run the code, I get the following error:
Error in st_transform.sfc(st_geometry(x), crs, ...) :
  cannot transform sfc object with missing crs

I tried dozens of different answers I have come across on StackOverflow and nothing seems to make this work.
What makes it even more strange is that I can run the two geom_sf functions with ggplot separately, and they plot just fine.
The error only occurs when I attempt to run them together, as shown in the included ggplot code above.
Any other thoughts/ideas?
Thanks in advance.
Edit (to answer the question below):
> sf::st_crs(arlington.test)
Coordinate Reference System:
  User input: NAD83
  wkt:
GEOGCRS["NAD83",
    DATUM["North American Datum 1983",
        ELLIPSOID["GRS 1980",6378137,298.257222101,
            LENGTHUNIT["metre",1]]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["latitude",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["longitude",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    ID["EPSG",4269]]
>

A: Your arlington.test object seems to be in EPSG:4269; you attempted to override it to WGS 84 via sf::st_set_crs(4326). Are you certain you did not mean sf::st_transform(4326)?
The set crs is best reserved for cases you are certain the CRS is malformed / incorrect (it can happen when the *.prj gets lost from your *.shp shapefile). This is not a typical use case for {tidycensus} data.
To change projection from one known CRS to another sf::st_transform() works the best.


text:
Q: Is there any performance reason to store ids as comma seperated string in a RDMS?
Possible Duplicate:
Is storing a delimited list in a database column really that bad?

I have been working on a couple of PHP/MySQL projects where all relationships are stored as comma separated strings.
For example a common relationship would be like
(in psuedocode)
table people
id - integer
name - string
age - integer
teams - string (CSV OF integers, ex '1,3,9,21')

table teams
name - String
id - integer

managing relationships becomes a hassle.
To get all teams for a person:
$person = 'SELECT * FROM People WHERE id= x';
then in php I have been doing something like
$person['teams'] = SELECT * FROM teams WHERE id IN ($person['teams']);

as I was writing this i realized i could probably combine them in a mysql query, something like:
SELECT
  people.id,
  people.name,
  people.teams,
  teams.name
FROM people
JOIN teams ON FIND_IN_SET(teams.id, people.teams) WHERE people.id=x

with this type of setup I find myself using FIND_IN_SET, pretty frequently
So finally, my question is: Is there a performance benefit to creating relationships like this?
In my experiences so far FIND_IN_SET has usually been doing a full table scan.  If there is no performance benefit, in which instances is it beneficial to using a comma seperated list of integers?  It seems that mysql designers had something in mind when creating FIND_IN_SET.

A: You're right, FIND_IN_SET() cannot make use of an index, so it causes a full table scan.  Technically, that function is a bogus operation for a relational database, but no doubt there was a lot of demand for it so MySQL implemented it.
Storing data in a comma-separated list is an example of denormalization.  Any departure from normalized design can give a performance boost for one type of query, but usually at the expense of all other types of queries against the same data.
For example, if you store players and their teams as a comma-separated list, it makes it very easy to get the list of teams for a given player, without doing a join.  That's a performance improvement.  But fetching the details for a given player's teams is much more difficult.  Likewise searching for all players on a given team.
Use comma-separated lists only if that list is treated as a discrete "black box" piece of data.  I.e. your application needs to fetch that list as a whole item, but never a subset of the list, and you never need to write SQL to use elements in that list for searching, joining, sorting, subtotals, etc.
See also my answer to Is storing a delimited list in a database column really that bad?

A: Table scan can not be considered as a benefit, at any time.
Moreover it's breaking the Normal form ( http://en.wikipedia.org/wiki/Database_normalization), as far as I remember from the school.
I think it's a good practice to have all the primary/foreign keys columns indexed to have performance benefit.
The only idea I would have in such a situation, is to politely ask architect on the particular project what was his idea behind the solution and explain him/her the performance disaster behind this :)


text:
Q: Setting fdm=marker in the first line of .vimrc This is the first line of my .vimrc file:
" vim:fdm=marker " Treat comments as folds

Every time I edit .vimrc I get this error (and no other errors):
"~/.vimrc" 409L, 12674C
Error detected while processing modelines:
line    1:
E518: Unknown option: "

Since I have taken this line from some other .vimrc, it should work in my setup as well. Why doesn't it? How can I fix this?

A: The modeline syntax is wrong. I doubt it worked in the vimrc you copied it from. If you read :h modeline you will find that the modeline is trying to interpret the second quote as an option. Since there is no option called quote it fails.
You should use the second modeline syntax if you want to put a comment after the modeline and get something like the following
" vim: set fdm=marker: " Treat comments as folds

:h modeline copied below.
                                        modeline vim: vi: ex: E520
There are two forms of modelines.  The first form:
        [text]{white}{vi:|vim:|ex:}[white]{options}

[text]                  any text or empty
{white}                 at least one blank character (<Space> or <Tab>)
{vi:|vim:|ex:}          the string "vi:", "vim:" or "ex:"
[white]                 optional white space
{options}               a list of option settings, separated with white space
                        or ':', where each part between ':' is the argument
                        for a ":set" command (can be empty)

Examples:
   vi:noai:sw=3 ts=6
   vim: tw=77

The second form (this is compatible with some versions of Vi):

        [text]{white}{vi:|vim:|Vim:|ex:}[white]se[t] {options}:[text]

[text]                  any text or empty
{white}                 at least one blank character (<Space> or <Tab>)
{vi:|vim:|Vim:|ex:}     the string "vi:", "vim:", "Vim:" or "ex:"
[white]                 optional white space
se[t]                   the string "set " or "se " (note the space); When
                        "Vim" is used it must be "set".
{options}               a list of options, separated with white space, which
                        is the argument for a ":set" command
:                       a colon
[text]                  any text or empty


text:
Q: passing a javascript array to a django view I'm using django and have a page of search results that I want to be able to filter by category with ajax (jquery) requests.  There's a filter bar on the side of the page and when someone selects certain categories and clicks submit, those corresponding results should show up on the page.  My code looks something like this:
<input type="checkbox" name="category1" value="1" />
<input type="checkbox" name="category2" value="2" />
<input type="button" name="submit" onclick="{
    var cats = new Array();
    $(input[type=checkbox]:checked).each(function() {
        cats.push($(this).val());
    });
    $.getJSON('page.html', {'cats':cats}, function(data) {...});
}" />

But in the django view when I try to read the cats array it returns a 500 error.  I can, however, pass scalars and strings to the django view with no problem.
Any thoughts?  Is there a more elegant jQuery way to do this without using a javascript array?

A: Rather than getting the field values manually, you can use jQuery's serializeArray() method, which turns a set of fields into an array which can be sent as JSON. Note that you'll probably want both checkboxes to have the same name, so that when it's serialised it becomes something that Django will interpret as a list.
As Steve says, to help further we'll need to know what the view is doing and what the error is.

A: Got it working - I downloaded the jquery-json plugin, encoded my array as a json obect to send to django, and then used simplesjon.loads() in the django view to convert that json object to a python list.  However, the fact that it took so many steps and jQuery on its own doesn't even come with json encode functionality still makes me think there must be a more elegant way - if anyone has any insight, I'd love to hear it.
Thanks Daniel for pointing me in the right direction.

A: I guess that a workaround would be transforming your array into a string, eg in javascript:
a = new Array(0,1,2,3,4);
[0, 1, 2, 3, 4]
a.join(" ")
"0 1 2 3 4"

Then you can pass this to the python back end, split it and reconstruct the data structure you need.....


text:
Q: NDVA and Webpage title tag I am working on a page about World War 1 (WWI).  when NVDA reads the page it says "WW eye".  I can correct this by using the following:
  WWI World War One

However, I have WWI in the page title:
<title>WWI ...</title>

When a user loads the page, NVDA reads the page title and, in this case, will say WW "eye."
Is there a similar technique to make NVDA say something different as it appears in the title tag?

A: You wrote a 1 in your example <title> I presume that is meant to be an "i".
Short answer is there is nothing you can do with the title if you must use an "I" and nothing you need to do, screen reader users are used to this kind of behaviour and will gain context very quickly from the document, from links they followed to get to the page etc.
Just use WW1 it makes more sense than WWI to everybody, not just screen reader users (or better yet World War 1).
Plus in terms of search terms I doubt anyone would use WWI to look for WW1 so go with the obvious choice.
Also in terms of hiding information from screen readers a better approach is to use this visually hidden text class for compatibility (you can inline the CSS if you must, but using classes is obviously preferable as the mark-up is much cleaner and you can use the class elsewhere.)
HTML
WWI
World War One

CSS
.visually-hidden {
    border: 0;
    padding: 0;
    margin: 0;
    position: absolute !important;
    height: 1px;
    width: 1px;
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
    clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
    clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
    white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
}


text:
Q: error in R.java with a boolean instead of assignment I am creating a custom view that extends the LinearLayout, has a TextView as a component and inflates a layout I created. Everything is fine, but I get this error
"public static final int LInearLayout_width==0x7f07000a"
It's the "==" instead of an "=" and I can't modify the R.java file. How do I get around this?

A: R.java error is really mind freaking. Just delete your R.java file and build your project. If it doesn't solve then restart your eclipse.


text:
Q: How do I combine PreviewMouseLeftButtonDown with Command? In sample project I have a button binded to a Command. It works as button-click event.
However, I would like to use PreviewMouseLeftButtonDown/Up event in in conjunction with Command.
For example LeftButtonDown - filling with green, LeftButtonUp -default filling.
Is there a neat way to do that?
        <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="0">
            <Button Command="{Binding ColourChange_command, Mode=OneWay}" Content="Fill with green" />
        </StackPanel>

        <Ellipse Grid.Column="1" Stroke="Black">
            <Ellipse.Style>
                <Style TargetType="Ellipse">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ColourChange}" Value="True">
                            <Setter Property="Fill" Value="LimeGreen" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>
    </Grid>


text:
Q: Interesting -- Sharing postgres tables between 2 r/w users automatically I am new to postgres and am seeing an ownership/accessibility issue where we have 2 users, master and user_rw in the db.
The tables
table_abc  => created owned by master
table_xyz => created and owned by user_rw
The issue: Any new tables created by master are not accessible (select *, write etc) to user_rw and vice versa. I dont want to explicitly grant permissions for new tables to both users every time new tables are created.
I want the following requirements:

*

*All tables created by user_rw should be accessible and read/writable by user master

*All tables created by user master should be accessible and read/writable by user user_rw

*Any new tables created in the db hence forth should automatically be accessible (read/writable) by both users

I only have public schema in my postgres. While creating the user_rw I had done the following
GRANT CONNECT ON DATABASE database_test TO user_rw;
GRANT USAGE ON SCHEMA public TO user_rw;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO user_rw;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO user_rw;

What am I missing?

A: You need to use alter default privileges to set the privileges for objects that will be created in the future.
As both users should be able to read/write tables created by the other, I would recommend to create a role to which all privileges are granted. Then grant that role to the two users:
create role table_access
  role user_rw, master; -- immediately grants this new role to the two existing users

alter default privileges
  for role user_rw, master --<< tables created by one of those users
  in schema public
  grant all privileges on tables to table_access;

A: You can probably use roles for this.

*

*Create a role for both users

*Assign this role to both users

*When the user connects it will have to change to this role explicitly
(SET role)

*Users will then have to do all operations on these tables (create, select, etc) under this role.


text:
Q: Is there a way to gather the points used in a Plot and generate a function that passes through those points? like the title says: is that possible? In my case, I have a plot of an integral that is evaluated numerically. Maybe using Interpolate with the points used by mathematica to draw the graph or something?

A: Starting with the plots
plts = Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi},
  PlotLegends -> "Expressions"]

Extracting the sets of points from the plot
pts = Cases[plts, Line[pts_] :> pts, Infinity];

Interpolating each set of points
funcs = Interpolation /@ pts;

Plotting the interpolations for comparison
Plot[Evaluate[#[x] & /@ funcs], {x, 0, 2 Pi},
 PlotLegends -> Automatic]

EDIT:  Addressing the additional questions in the comments.
To evaluate one of the three functions at x == 1 use Part ( [[...]] ). For example, to evaluate the second interpolated function
funcs[[2]][1]

(* 0.909298 *)

To integrate the product of each function with Sin[x] over the interval {0, 1}
NIntegrate[#[x]*Sin[x], {x, 0, 1}] & /@ funcs

(* {0.272675, 0.397216, 0.321925} *)

Or for a single function
NIntegrate[funcs[[2]][x]*Sin[x], {x, 0, 1}]

(* 0.397216 *)