text:
Q: Isomorphism between Rings using Chinese Remainder Theorem Let $A_n(K)$ be the vector space of applications betwen $\mathbb{Z}_n$ and the field $K$, consider it as a ring with the convolution product $(f*g)(t) = \sum_{m \in \mathbb{Z}_n} f(t)g(t-m)$.
If $K$ has a primitive n-th root of unity, show, using the Chinese Remainder Theorem (CRT), that $A$ is isomorphic to $K^n$.
CRT. Let $f_i: A \rightarrow A_i$ with $i = 1,\dots, t$ Ring morphisms. Then exists a unique morphism $\tilde{f}: \frac{A}{\cap_{i=1}^t Ker f_i,} \rightarrow \prod_{i=1}^t Im f_i$. So, $\tilde{f}$ is isomorphism if and only if $Ker f_i + Ker f_j = A \quad \forall i\neq j$
I know that if $K$ has a primitive n-th root of unity $w$, then $\{1, w, w^2, \dots, w^{n-1}\}$ are different values within $K$. But I can't see how I can relate this information with CRT and I even struggle trying to match $A_n(K)$ and $K^n$ with domain and codomain of $\tilde{f}$. Is this a wrong approach?
I must mention that I proved $A_n(K)$ is isomorphic to $K^n$ using the product $(fg)(k)=f(k)g(k) \quad k \in \mathbb{Z_n} \quad f,g \in A_n(K)$ without CRT and the n-th root hypothesis.


text:
Q: Ansible customizing the output of a result before writing it in the log file I am writing logs into a local file via a task that captures the result of further tasks in my playbook.
I am trying to log only the parts in which the task perfom the wanted action and not the skipped parts
here's the logs task :
 - name: log the changed hosts
   shell: echo "{{ item }}" >> /tmp/changed.txt
   with_items:
      - "{{ansible_facts.hostname}}{{debresult}}"
      - "{{ansible_facts.hostname}}{{redresult}}"
   delegate_to: "localhost"

and here is an one of the two tasks that i want to log :

 - name: change default gateway address
      replace:
        path: /etc/network/interfaces
        regexp: '(up route add default gw [\d]*\.[\d]*.[\d]*)\.[\d]*$'
        replace: '\1.252'
        backup: yes
      register: debresult

So far the log looks like this :
test-vipgw-redhat{'skip_reason': u'Conditional result was False', 'skipped': True, 'changed': False}
test-vipgw-debian{u'msg': u'1 replacements made', 'failed': False, u'changed': True, u'backup_file': u'/etc/network/interfaces.23603.2021-02-07@17:52:48~'}
test-vipgw-debian{'skip_reason': u'Conditional result was False', 'skipped': True, 'changed': False}
test-vipgw-redhat{u'msg': u'1 replacements made', 'failed': False, u'changed': True, u'backup_file': u'/etc/sysconfig/network-scripts/ifcfg-eth0.23282.2021-02-07@17:52:37~'}

But what i want to have should look like this :
test-vipgw-debian{u'msg': u'1 replacements made', 'failed': False, u'changed': True, u'backup_file': u'/etc/network/interfaces.23603.2021-02-07@17:52:48~'}

test-vipgw-redhat{u'msg': u'1 replacements made', 'failed': False, u'changed': True, u'backup_file': u'/etc/sysconfig/network-scripts/ifcfg-eth0.23282.2021-02-07@17:52:37~'}

I tried to add this sed to my echo to get rid of the skipped tasks but it is not working :
shell: echo "{{ item }}" |  sed -nr '/^test/{h;n;/^skipping:/{n;b};H;x};p' >> /tmp/changed.txt

I also tried to use callback and skippy but still the result output keeps the skipped parts.
I tried to use the stdout also but still the result is the same I even have a dict error :
TASK [debug] ***********************************************************************************************************
fatal: [test-vipgw-debian]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'\n\nThe error appears to be in '/home/rezzaamari/gateway_change.yml': line 14, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n register: debresult\n - debug:\n ^ here\n"}

So my question is is there a way in ansible or a module that would help me have the needed result? all advices hints or sed alternatives are welcome.

A: Well I managed to get what I want just by adding a condition to my :
- name: log the changed hosts
      local_action:
        module: lineinfile
        line: "{{item}}"
        dest: /tmp/changed_logs_test.log
      with_items:
        - "{{ansible_facts.hostname}}{{redresult}}"
      when: redresult.changed

this way the log will write only when the the changes are done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to add a delete post button Premise
I use firebase to manage posts, but I can not make posting delete function implemented.
Code
Swift4 postApi
    import Foundation
   import FirebaseDatabase

class PostApi {
    var REF_POSTS = Database.database().reference().child("posts")
    var REF_MY_POSTS = Database.database().reference().child("myPosts")

    static var shared: PostApi = PostApi()
    private init() {
    }

    func observePosts(completion: @escaping (PostModel) -> Void) {
        REF_POSTS.observe(.childAdded) { (snapshot) in
            guard let dic = snapshot.value as? [String: Any] else { return }
            let newPost = PostModel(dictionary: dic, key: snapshot.key)
            completion(newPost)
        }
    }

    func observePost(withPostId id: String, completion: @escaping (PostModel) -> Void ) {
        REF_POSTS.child(id).observeSingleEvent(of: .value) { (snapshot) in
            guard let dic = snapshot.value as? [String : Any] else { return }
            let newPost = PostModel(dictionary: dic, key: snapshot.key)
            completion(newPost)
        }
    }

    func observeMyPosts(withUid uid: String, completion: @escaping (String) -> Void) {
        REF_MY_POSTS.child(uid).observe(.childAdded) { (snapshot) in
            let postId = snapshot.key
            completion(postId)
        }
    }

    func fetchCountPosts(withUid uid: String, completion: @escaping(UInt) -> Void) {
        REF_MY_POSTS.child(uid).observe(.value) { (snapshot) in
            let postCount = snapshot.childrenCount
            completion(postCount)
        }
    }

    func observeLike(withPostId id: String, completion: @escaping (Int) -> Void) {
        REF_POSTS.child(id).observe(.childAdded) { (snapshot) in
            guard let value = snapshot.value as? Int else { return }
            completion(value)
        }
    }

            guard let dic = snapshot?.value as? [String: Any] else { return }
            guard let postId = snapshot?.key else { return }
            let updatedPost = PostModel(dictionary: dic, key: postId)
            onSuccess(updatedPost)
        }
    }

    // 投稿を読み込んで好きな順に並べ替える
    func observeTopPost(completion: @escaping(PostModel) -> Void) {
        REF_POSTS.queryOrdered(byChild: "likeCount").observeSingleEvent(of: .value) { (snapshot) in
            let arraySnapshot = (snapshot.children.allObjects as! [DataSnapshot]).reversed()

            arraySnapshot.forEach({ (child) in
                guard let dic = child.value as? [String: Any] else { return }
                let post = PostModel(dictionary: dic, key: snapshot.key)
                completion(post)
            })
        }
    }

Code
Swift4 userApi
import Foundation
import FirebaseDatabase
import FirebaseAuth

class UserApi {
    // Adresse Datenbank users
    var REF_USERS = Database.database().reference().child("users")

    // Singleton pattern (Einzelstück Muster)
    static var shared: UserApi = UserApi()
    private init() {
    }

    // Aktuell eingeloggte User ID
    var CURRENT_USER_UID: String? {
        if let currentUserUid = Auth.auth().currentUser?.uid {
            return currentUserUid
        }
        return nil
    }

    // Aktuell eingeloggte User
    var CURRENT_USER: User? {
        if let currentUserUid = Auth.auth().currentUser {
            return currentUserUid
        }
        return nil
    }

    // Lade User mit der id
    func observeUser(uid: String, completion: @escaping (UserModel) -> Void) {
        REF_USERS.child(uid).observeSingleEvent(of: .value) { (snapshot) in
            guard let dic = snapshot.value as? [String: Any] else { return }
            let newUser = UserModel(dictionary: dic)
            completion(newUser)
        }
    }

    // Lade user ohne id
    func observeUser(completion: @escaping (UserModel) -> Void ) {
        REF_USERS.observe(.childAdded) { (snapshot) in
            guard let dic = snapshot.value as? [String: Any] else { return }
            let user = UserModel(dictionary: dic)
            completion(user)
        }
    }

    // Lade den aktuellen User
    func observeCurrentUser(completion: @escaping (UserModel) -> Void ) {
        guard let currentUserUid = CURRENT_USER_UID else { return }
        REF_USERS.child(currentUserUid).observeSingleEvent(of: .value) { (snapshot) in
            guard let dic = snapshot.value as? [String: Any] else { return }
            let currentUser = UserModel(dictionary: dic)
            completion(currentUser)
        }
    }

    // User im Suchfeld laden
    func queryUser(withText text: String, completion: @escaping(UserModel) -> Void ) {
        REF_USERS.queryOrdered(byChild: "username_lowercase").queryStarting(atValue: text).queryEnding(atValue: text + "\u{f8ff}").queryLimited(toLast: 5).observeSingleEvent(of: .value) { (snapshot) in
            snapshot.children.forEach({ (data) in
                let child = data as! DataSnapshot
                guard let dic = child.value as? [String: Any] else { return }
                let user = UserModel(dictionary: dic)
                completion(user)
            })
        }
    }
}

Supplementary information
We will add additional information if we have other missing information.
Since I often do not understand Swift in 4 weeks, I would like you to tell me with concrete code etc.
Reference material
How to delete a child from Firebase (Swift)

A: Here's a wild guess at an answer as it's unclear how the OP determines which node to delete.
Let's assume a tableView is displayed in the UI and the user has swiped a row_to_delete. We will also assume we have an array of Post objects that have a 'key' property from a snapshot.
To then delete a post, retrieve the post from the dataSource array and get it's key. Then build a ref to that ans removeValue.
let postToDelete = postsArray[row_to_delete]
let postKey = postToDelete.key
let ref = your_firebase.child("posts").child(postKey)
ref.removeValue()


text:
Q: Rate an Android app on android
Possible Duplicate:
Requesting user to rate/review/comment on Android Market

I have developed and placed an application on the Android market. In its updated version, I want to add the functionality of Rating the App to the user.
I want the following functionality to the app:

*

*As the user tries to exit from the app, one pop up will display to ask for rating the app. This pop up has three options: Yes, No and later

*On selecting any option, the user will exit from the app.

*If user select Yes then he will redirect to android market to rate this app. If user have rated the app once, then he will never show that pop up again.

*If the user selects No, then the user will also not get this pop up again.

*If the user selects 'Later' then pop up will be shown next time

I have problem in Yes option. How to manage, that user has given the rate once on `android market.
Is there any API which returns the information about the user rating?

A: using code on buttonclick listener
 String App_Name="";
 bt.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
                      }});

A: I think what you exactly want is this :
To test it and to tweak the dialog appearence, you can call AppRater.showRateDialog(this, null) from your Activity. Normal use is to invoke AppRater.app_launched(this) each time your activity is invoked (eg. from within the onCreate method). If all conditions are met, the dialog appears.
By the way, there is no API that gives you the information that the user rated it or not. Don't worry about it, he will use the never show this again option...
Another thing : you should prefer to show this at the beginning... When the user wants to leave, he mostly doesn't want to rate your app !
public class AppRater {
    private final static String APP_TITLE = "YOUR-APP-NAME";
    private final static String APP_PNAME = "YOUR-PACKAGE-NAME";

    private final static int DAYS_UNTIL_PROMPT = 3;
    private final static int LAUNCHES_UNTIL_PROMPT = 7;

    public static void app_launched(Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) { return ; }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter
        long launch_count = prefs.getLong("launch_count", 0) + 1;
        editor.putLong("launch_count", launch_count);

        // Get date of first launch
        Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
        if (date_firstLaunch == 0) {
            date_firstLaunch = System.currentTimeMillis();
            editor.putLong("date_firstlaunch", date_firstLaunch);
        }

        // Wait at least n days before opening
        if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
            if (System.currentTimeMillis() >= date_firstLaunch +
                    (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
                showRateDialog(mContext, editor);
            }
        }

        editor.commit();
    }

    public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
        final Dialog dialog = new Dialog(mContext);
        dialog.setTitle("Rate " + APP_TITLE);

        LinearLayout ll = new LinearLayout(mContext);
        ll.setOrientation(LinearLayout.VERTICAL);

        TextView tv = new TextView(mContext);
        tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
        tv.setWidth(240);
        tv.setPadding(4, 0, 4, 10);
        ll.addView(tv);

        Button b1 = new Button(mContext);
        b1.setText("Rate " + APP_TITLE);
        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
                dialog.dismiss();
            }
        });
        ll.addView(b1);

        Button b2 = new Button(mContext);
        b2.setText("Remind me later");
        b2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        ll.addView(b2);

        Button b3 = new Button(mContext);
        b3.setText("No, thanks");
        b3.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (editor != null) {
                    editor.putBoolean("dontshowagain", true);
                    editor.commit();
                }
                dialog.dismiss();
            }
        });
        ll.addView(b3);

        dialog.setContentView(ll);
        dialog.show();
    }
}

source : link


text:
Q: Does std::string need a hash function when used with unordered_sets? I am using an unordered set of std::strings. What is the recommended way to specify the hash function for it? Currently it is using the default. Do I need to specify one explicitly which could perform better?

A: The standard specialization for std::string is probably good enough (probably even extremely good) for strings in general. But if your working with string of a very specific format, you probably could find or design a better algorithm for your particular case.

A: There's no need to provide your own. If you're using VS 2010 the hash function for std::string is in the xfunctional header file included by <functional> if you want to take a look for yourself about whether it would meet your needs:
template<>
    class hash<_STD string>
// ...

A: You could check the wiki , where you can see that in order to specify the hash function you should write something like :
 std::unordered_map<X,int,hash_X> my_map;

where hash_X is the definition of the hash function.
For completeness I include the code of the definition found in the wiki
struct X{int i,j,k;};

struct hash_X{
  size_t operator()(const X &x){
    return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
  }
};

A: I still haven't figured out how to add the little comment under an answer...I would prefer to post this under Michael Burr's answer. Anyway, c++11 has std::hash<string> as a part of the library. Here you can view all the supported hash functions.


text:
Q: After subclass in the viewDidLoad the [super viewDidLoad] gets called, but the methods do not get executed I got a question about subclassing.
I start with my first view:
in my .h file:
@interface viewAController : UIViewController

in my .m file:
-(void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"Begin view");
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;

if (![udpSocket bindToPort:12345 error:&error]) //check ff of dit werkt!
{
    NSLog(@"F you");
    return;
}

NSLog(@"Derde line");
if (![udpSocket beginReceiving:&error])
{
    NSLog(@"Screw you!");
    return;
}
}

Porting and beginreceiving goes well.
and then when I subclass viewAController:
@interface viewBController : viewAController

in my .m file:
-(void)viewDidLoad{
[super viewDidLoad];
}

I am expecting that my subclass [viewBController], will display all of the NSLogs, because Im calling the super  viewDidLoad.
Instead it is saying: F you!
Oke I understand that I can only bind once to the port, BUT Im expecting an error message, this does not show.
So I delete the binding and then I get Screw you, apparently I cannot say beginreceiving when Im not binding to a port. Without these two methods it works just fine though, it is printing everything out of the parent.
QUESTIONS:
Should I bind? I actually only need to listen to port 12345, should I just implement this differently?
Should I work without bind and without beginreceiving? I think I prefer with binding so that I wont listen to all of my ports.
Why cant I do beginreceiving when I dont bind?
How can I show the error?? Cause it is not printing any errors ...
greetz

A: What you are doing is right.But i have only one question to ask whether you have added the object of derived ViewController to some View.
Unless you wont add it you wont get the didLoad Of your superclass get fired.
Check by adding the object of your derived View to SomeView.

A: This is wrong you are doing
NSLog("@Hi there!");

you have to use
NSLog(@"Hi there!");

And if this is a typo (I hope it is) you have to add your sub class to some where using add subview or pushing it.


text:
Q: Hadoop Balancer command WARN messages - threads quota is exceeded I am trying to run Hadoop balancer command as follows:
hadoop balancer -threshold 1
But I am getting several WARN messages as
Failed to move blk_1073742036_1212 with size=134217728 from 192.168.30.4:50010 to 192.168.30.2:50010 through 192.168.30.4:50010: block move is failed: Not able to receive block 1073742036 from /192.168.10.3:53115 because threads quota is exceeded.
And at the end...
No block has been moved for 5 iterations. Exiting...
Balancing took 4.092883333333333 minutes
I set ulimit values as follows:
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 2065455
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) 64000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 65535
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
But still I am getting the same error.
Could someone please give me suggestions on this. Appreciate your help.

A: Question was asked a long time ago, posting an answer for posterity's sake.
The Hadoop balancer has a bug where it prematurely exits iterations. This caused the balancer to be very slow. This was fixed in HDFS-6621 and officially released as part of Apache Hadoop 2.6.0. Since this is a bug in the Balancer itself, it is possible to run an updated version of the Balancer without upgrading your cluster.
Datanodes will limit the number of threads used for balancing so as to not eat up all the resources of the cluster/datanode. This is what causes the WARN statement you're seeing. By default the number of threads is 5. This was not configurable prior to Apache Hadoop 2.5.0. HDFS-6595 added this proeprty dfs.datanode.balance.max.concurrent.moves to allow you to control the number of threads used for balancing. Since this is a datanode side property, this will require an upgrade to your cluster if you want to use this setting.
If you're using a distribution packaged by a vendor (e.g. Hortonworks, Cloudera, etc), the mentioned fixes may have been back-patched to an earlier version. Check your vendors release notes to find out.


text:
Q: PHP xpath get tag name I have an xml file like this:
<js>
<ba>
    <ea>
        <jd>
      <option>first sko</option>
      <option>second sko</option>
      <option>third sko</option>
      <option>fourth sko</option>
      <option>fifth sko</option>
        </jd>
    </ea>
</ba>
</js>

I want to retrieve the tag name of the grandparent tag (i.e. "ea") starting from each value of the "option" tag.
So to get two levels up from this tag I have tried:
$xmlItem = simplexml_load_file(thexmlfile.xml);

foreach ($xmlItem->xpath('//jd/option') as $juzg) {
$cid = $xmlItem->xpath("name(//*[*[option = '" . $juzg . "']])");

$item['cid'] = (string)$cid;
}

The result I get when I echo the $cid or the $item['cid'] is an "Array" for each loop.
I am looking for the full script that will go in place of:
$cid = $xmlItem->xpath("name(//*[*[option = '" . $juzg . "']])");

I will appreciate any guidance on this issue.

A: $xmlItem->xpath returns an Array, so if you do (string)$xmlItem->xpath() you will always get 'Array'
In your example you would have to iterate again over $cid or just select $cid[0], but I don't think getting the name of the parent like this will work.
Either do:
foreach ($xmlItem->xpath('//jd/option') as $juzg) {
    $cid = $xmlItem->xpath("//*[*[option = '".$juzg."']]");

    $item['cid'] = $cid[0]->getName();
}

However this only works if there isn't any other option element in your xml document with the same content, so rather than relying on the content of the element just select its parent nodes:
foreach ($xmlItem->xpath('//jd/option') as $juzg) {
    $cid = $juzg->xpath('../..');

    $item['cid'] = $cid[0]->getName();
}

Here you even can be sure that $cid will only have one object because you select a parent and an element will always have just one parent.


text:
Q: Neo4j plugin : can't use the spatial procedures after installing neo4j spatial plugin So I have neo4j3.1.4 community edition, and tried to put neo4j spatial plugin jar v0.24 file under the "E:\softwares\Neo4j CE 3.2.0\plugins" directory. "E:\softwares\Neo4j CE 3.2.0\" is my neo4j installation directory. I couldn't find any of th procedures of spatial from cypher through browser. But I seem to have done exactly what the manual told me.

A: Judging from the installation path I'd say you actually have Neo4j 3.2.0 running, no ? Anyway (shouldn't make a difference really), if you take the latest release from https://github.com/neo4j-contrib/spatial/releases/download/0.24-neo4j-3.1.1/neo4j-spatial-0.24-neo4j-3.1.1-server-plugin.jar, drop it into the plugins directory and then restart (don't forget that) Neo4j, things should work. You can verify if the spatial-procedures are there with a CALL dbms.procedures(). If not, please verify the neo4j.log file ... there are multiple messages about loading "geometry" related stuff in there if things go well (or you may see the reason it's not loading otherwise).
Also, and again judging from your installation directory, I think you may have used the Windows installer ? If so, the plugins directory is actually located at C:\Users\youruser\Documents\Neo4j\default.graphdb\plugins, not in the installation directory.
Hope this helps,
Tom


text:
Q: What replaces CommandManager in WinRT? I'm getting started with Metro style applications (I know we're not supposed to call it Metro, but I can never remember what it's supposed to be called...), and I'm implementing a DelegateCommand class for use in MVVM. In WPF, the ICommand.CanExecuteChanged event is typically implemented like this:
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

But the CommandManager class does not exist in WinRT... Is there something else instead? Or are we supposed to explicitly trigger this event ourselves?

A: In WinRT, you must update/raise CanExecuteChanged manually. There is no CommandManager to do this globally. You could look at this as a pain in the neck, or a serious performance boost now that CanExecute is not called constantly. It does mean you have to think about cascading property changes where before you did not have to. But this is how it is. Manual.
public void RaiseCanExecuteChanged()
{
    if (CanExecuteChanged != null)
        CanExecuteChanged(this, EventArgs.Empty);
}

A: With WPF it is mandatory that you implement ICommand.CanExecuteChanged as you have described. However, for Silverlight, this is not the case. See this related question:
WPF CommandParameter binding not updating
My guess is that in WinRT, as in Silverlight, the CommandManager is not necessary.
See the related discussion here:
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/477cdd19-ee88-4746-97fe-59b8dbd44e0a/


text:
Q: Difference in the workload related to data-amount and search option A couple of days ago I was asked why it is necessary to use the first normal form also for separation of names.
We have a table which stores private customers (Name+Surname;Information) and business customers (Companyname;Information).
My answer was that first of all it is a bad habit not keeping the values atomic and second the workload for using full-text searches will increase and affect the speed of the results as the amount of data in the database grows. An open end search needs less traffic than a full-text one.
Unfortunately I haven't found data related to the question HOW exactly the speed and efficiency decrease if I am searching for '%whatever%' instead of 'whatever%' or even weirder regular expressions.
Especially related to the scenario if the amount of rows in the table increases.
Can someone provide hard facts related to that?


text:
Q: Mapping const char** to Java type with JNA I am trying to use a C++ library in Java with JNA. In the header file of the library I have the following method declaration:
extern "C" void foo(const char** bar);

The paramterer bar should be passed to foo empty, and foo vill assign it a value that I want to retreive in Java. How should the corresponding Java method declaration be set up (e.g. what Java type should I map bar to), and how can I use it?
I have tried the following Java declarations:
void foo(String bar);
void foo(String[] bar);
void foo(Pointer bar);

They all result in the following error when I call foo:

Exception in thread "main" java.lang.Error: Invalid memory access

A: Find below a small snippet.
libfoo.cpp
#include <stdio.h>
extern "C" void foo(const char** bar);

void foo(const char** bar) {
    for (int i = 0; bar[i] != '\0'; i++) {
        fprintf(stdout, "%s\n", bar[i]);
    }
}

LibFooDemo.java
import com.sun.jna.Library;
import com.sun.jna.Native;

public class LibFooDemo {

    public interface FooLibrary extends Library {
        FooLibrary INSTANCE = (FooLibrary)
                Native.loadLibrary("foo", FooLibrary.class);
        void foo(String[] format);
    }

    public static void main(String[] args) {
        String[] vals = {"foo", "bar", "foobar"};
        FooLibrary.INSTANCE.foo(vals);
    }
}

compile all sources
gcc -c -fPIC libfoo.cpp -o libfoo.o
gcc -shared -o libfoo.so  libfoo.o
javac -cp jna-4.2.1.jar LibFooDemo.java

run the Java program
java -Djava.library.path=. -cp jna-4.2.1.jar:. LibFooDemo

output
foo
bar
foobar


text:
Q: If 'happy' is without a noun If adjective 'happy' is without a noun, does this word still have a meaning or have no meaning without a noun?

A:
If adjective 'happy' is without a noun, does this word still have a meaning or have no meaning without a noun?

'She is happy' (pronoun, verb, adjective) is a perfectly common sentence I'm sure you understand and has meaning.
'It is good to be happy' (pronoun, verb, adjective, preposition, verb, adjective) is also meaningful and has no noun.
I'm guessing that the source of your question comes from the fact that 'happiness' is a state of contentment that only a living being can experience, so you may think there must be a subject or an object that is feeling that emotion whenever you mention it. As my examples show, you can indicate a subject without a noun, and you can also speak about 'being happy' in an abstract sense. However, as an emotion you can't use it in place of other adjectives like 'pleasant' - you couldn't say that the weather was happy, for example.


text:
Q: how to change from Apple Developer Organisation Program to Apple Developer Enterprise Program? i am new to iOS so by mistake i enrolled for Apple Developer Organisation Program (99 USD per membership year), my requirement is to distribute apps to only for selective number of customers but not through Appstore. So by some RnD i got to know about Apple Developer Enterprise Program (299 USD per membership year) which i found relevant. My Apple Developer Organisation Program is still unused and fresh i.e no app is pushed yet on Appstore. So can i change the Program ? If yes then what is the procedure ? please help me. Thanks in advance.

A: You'll need to contact apple. I also believe that is only available for companies (that might not be correct). This page will tell you how to change to a company account.


text:
Q: Strange behavior of rugarch package on cluster I watch a very strange behavior of rugarch package when I try to estimate models via arfimafit method. I have some (usually 1-2) workers never stop after the method calling in parallel.
Code for reproduce:
library(aTSA);
library(parallel);
library(rugarch);
library(pracma);

maxThreads <- max(1, detectCores()-1);
internalCluster <- makeCluster(maxThreads, homogeneous=FALSE, XDR=FALSE);

libraries <- c('data.table',  'rugarch', 'arfima', 'portes');
clusterExport(internalCluster, c('libraries'));
clusterEvalQ(internalCluster, { invisible(lapply(libraries, require, character.only=TRUE)); });

ARParam <- MAParam <- 0:3;
distribs <- c("norm", "snorm", "std", "sstd", "ged", "sged");
mean <- c(TRUE, FALSE);

arfimaNeed <- TRUE;
dFrac <- 0.1;

grid <- expand.grid(ARParam, MAParam, distribs, mean);
names(grid) <- c("AR", "MA", "DISTRIB", "MEAN");
permutationVec <- randperm(c(1:nrow(grid)), nrow(grid));

permGrid <- grid[permutationVec, ];

seriesGlobal <- parLapply(internalCluster, 1:1000, function(i) { as.numeric(arfima.sim(100, model = list(phi = c(0.2, 0.1), theta = c(0.5), dfrac = .2, dint = 0))); });

for (i in 1:1000)
{
  cat('\n Iteration ', i, ' started \n');

  ##series <- rnorm(100);
  series <- seriesGlobal[[i]];

  tmpEnv <- new.env(hash = FALSE);
  assign('arfimaNeed', arfimaNeed, envir = tmpEnv);
  assign('series', series, envir = tmpEnv);
  assign('dFrac', dFrac, envir = tmpEnv);
  assign('permGrid', permGrid, envir = tmpEnv);

  clusterExport(internalCluster , c('permGrid', 'arfimaNeed', 'dFrac', 'series'), envir = tmpEnv);

  specs <- parLapply(internalCluster, 1:nrow(permGrid), function(i) { arfimaspec(mean.model = list(armaOrder = c(permGrid[i, "AR"], permGrid[i, "MA"]), include.mean = permGrid[i, "MEAN"],
                                                                                arfima = arfimaNeed),
                                                                                distribution.model = as.character(permGrid[i, "DISTRIB"]),
                                                                                fixed.pars = list(arfima = dFrac)); });
  models <- parLapply(internalCluster, specs, function(elem)
  {
      try(arfimafit(spec = elem, data = series, solver = "gosolnp"), silent = TRUE);
  });

  cat('\n Iteration ', i, ' finished \n');
}

stopCluster(internalCluster);
rm(internalCluster);
gc(T, T);

and execution result:

My system:
AMD Ryzen 5950X, 128 Gb RAM, AMD64 Family 25 Model 33 Stepping 2 AuthenticAMD ~3401 Mhz
BIOS Version: American Megatrends Inc. 4408, 28.10.2022
OS Windows 11 OS Version 10.0.22621 N/A Build 22621
R 4.2.2, R 4.2.2 Patched, R 4.3 Devel were tested.
gcc (GCC) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
(I use RTools 4.3 now)
All packages were built with -m64 -O3 -w -march=native -mfpmath=both -mfma -mtune=native options.
I also use AMD BLIS + LibFlame libraries in ST mode (I copy and rename these libraries from AOCL installation folder and named it as Rblas.dll and Rlapack.dll for AMD BLIS and AMD LibFlame dlls).
But the same behavior of this code was observed also on OpenBLAS build with -fno-fma key.
It's really strange and stupid problem for me. I have my other code written earlier worked fine on my previous Intel Skylake-6770K with MKL.
Did anyone get the same problem with rugarch package?
Thank you.


text:
Q: azure pipelines pip requirements taking long currently installing pip requirements in azure pipeline using the following
- bash: pip3 install -r requirements.txt
  displayName: Install pip package requirements
  workingDirectory: project-requirements

Would using bash to install requirements.txt  affect the speed compared to using the python task (CMD) to install requirements.txt?

A: I don't expect using bash instead of cmd to make a substantial difference. To avoid having to wait for installing all packages every pipeline execution, you could extend your current Docker image with all required packages.
FROM your-current-docker-image
COPY requirements.txt .
RUN pip3 install -r requirements.txt


text:
Q: Getting issue in tomcat 7 but worked on tomcat 5. (Failed to start component ) My application was running fine on tomcat 5.5 but now i want to use tomcat 7.I am getting issue if i use tomcat 7.
I found on net and saw that people getting this issue. But i am facing this issue on tomcat 7 but on tomcat 5 my application was working fine.
Any clue ?
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEng
ine[Catalina].StandardHost[localhost].StandardContext[/ServiceDefinitionApp]]
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
ADDITON after comments :
Caused by: java.lang.ClassNotFoundException: com.alc.alcml.jaxb.xjc.Attributetype
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at com.container.AppClassLoader.findClass(AppClassLoader.java:98)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
As a solution i added the jar which contains this file in my application WEB-INF/lib and all worked fine.
NOW Question :
when i was running on tomcat 5.5, same application was running fine without having a jar in WEB-INF/lib.Why ?
Please make a note that JAR is available in class-path from some other directory but this is applicable same for tomcat5.5 and tomcat 7.

A: I can't give you a definite answer, but one possible explanation is that the JAR file was in the "shared libraries" directory of your Tomcat 5.5 installation.


text:
Q: C++ Open-MPI: custom struct type Not able to send over Ssend So I am working on a project using MPI and I am trying to create my own structure. The problem I am having is that it seems to not be working correctly as I never receive anything inside the worker and so I time out. I tried with a standard MPI_INT and it worked great. However, when I tried implementing my own type, it didn't like it... Here is my code:
#include <iostream>
#include <mpi.h>
#include "main.hpp"

int main(int argc, char *argv[]){
    //initialize MPI
    MPI_Init(&argc, &argv);

    message_to_worker message;
    //declare my new type
    MPI_Datatype MessageType;

    //declare the types the the structure will have
    MPI_Datatype type[1] = { MPI_INT };
    //the number of results for each type(int[50] will be 50 etc..)
    int blocklen[1] = {1};

    //this will store the displacement for each var in the structure
    MPI_Aint disp[1] = {0};
    MPI_Aint var1, var2;

    //number of vars
    int count = 1;

    //define the type
    MPI_Type_struct(count, blocklen, disp, type, &MessageType);
    MPI_Type_commit(&MessageType);

    std::cout << "The displacement is " << disp[0] << std::endl;

    int rank;
    int world_size;

    //give me my current rank(node 1 reiceves 1 , node 2 etc... )
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    int counter = 1;
    message.N = 5;

    //IF MASTER
    if (rank == 0) {
        int result;

        //send messages to the workers
        while(counter<world_size){
            //send 1 message of type MessageType using my own structure(first parameter)
            result = MPI_Ssend(&message, 1, MessageType, counter, 123, MPI_COMM_WORLD);

            //make sure the mssage was sent correctly
            if (result == MPI_SUCCESS){
                std::cout << "I am master and the world size is : " << world_size << std::endl;
                std::cout << " I send a message to mky worker thread " << std::endl;
            }else{
                std::cout << "There was a problem with the sending for worker " << counter << std::endl;
            }
            counter++;
        }
    }
    //IF WORKER
    else if (rank > 0) {
        //the worker will wait until it receives a message
        int result = MPI_Recv(&message, 1, MessageType, 0, 0, MPI_COMM_WORLD,
                  MPI_STATUS_IGNORE);

        //make sure the message was RECEIVED correctly
        if (result == MPI_SUCCESS){
            std::cout << "Worker - Rank: " << rank <<" OK! and the value received through the message is " << message.N << std::endl;
        }
    }

    //shutdown MPI
    MPI_Finalize();
    return 0;

}

A: My tag param(3 param from last) was different for the sender and receiver.. The master was using tag 123, and the worker was looking for tag 0. They both need to be synched since they need to establish a communication channel. Here is the fix(notice how the 5th paramenter, the tag, changed).
Before:
MPI_Ssend(&message, 1, MessageType, counter, 123, MPI_COMM_WORLD);

MPI_Recv(&message, 1, MessageType, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

After
MPI_Ssend(&message, 1, MessageType, counter, 123, MPI_COMM_WORLD);

MPI_Recv(&message, 1, MessageType, 0, 123, MPI_COMM_WORLD, MPI_STATUS_IGNORE);


text:
Q: Unable to connect to 3rd party ODBC driver in Go with alexbrainman/odbc on Linux I'm attempting to connect to a data source with a 3rd party ODBC driver (downloadable here) in Go using the alexbrainman ODBC driver. I've tested the DSN in question using:
isql -v "CData Redis Source"

Everything works as expected there. And I know that I have unixODBC 2.3.1 installed (isql --version).
The Problem
When I try to run the following Go program, I get this error message, spawned from the db.Ping() call (which Google translate seems unable to translate):

SQLDriverConnect: {㄰こ0} [unixODBC]湉慶楬潣湮捥楴湯猠牴湩祳瑮硡愠⁴湩敤⁸ㅛ㩝

My code:
package main

import (
  _ "github.com/alexbrainman/odbc"
  "database/sql"
  "log"
)

func main() {
  db, err := sql.Open("odbc","DSN=CData Redis Source")
  if err != nil {
    log.Fatal(err);
  }

  var (
    name string
  )

  rows, err := db.Ping()
  if err != nil {
    log.Fatal(err)
  }
}

I see the same error if I do a db.Query() or a db.Prepare().
The Details

*

*Ubuntu 16.04.3 LTS

*unixODBC 2.3.1

*CData Software ODBC Driver for Redis

*go1.6.2 linux/amd64

*github.com/alexbrainman/odbc

The Request
I'd be happy with a translation of the error message to help me debug AND/OR some help in determining why my error message is not in English AND/OR an actual proposed solution to the error message.

A: It turns out that I needed to ensure that the CData Driver was configured to use UTF-16 encoding, as is required by unixODBC. To do so, I edited the driver's INI file:
/opt/cdata/cdata-odbc-driver-for-redis/lib/cdata.odbc.redis.ini
[Driver]
DriverManagerEncoding = UTF-16

Once this was done the CData driver worked with the alexbrainman/odbc database driver (and other Go-related ODBC database drivers) as expected.


text:
Q: How much is the universe blueshifted at a black hole event horizon? If Alice falls into a black hole wearing a wrist-watch, an outside observer Bob sees Alice freeze at the horizon, her watch seems to have stopped. This also means that all light that originates from Alice is redshifted asymptotically to zero Herz.
Now my question is what Alice sees when she is just a few femtometers above the event horizon and looks back at Bob. Is Bob blueshifted and does his watch seem to spin to the end of time in a wink of her eye? Can Alice see the universe evolve to the end of time and see the black hole below her evaporate? In other words: if Alice is redshifted to zero to Bob, should not Bob be blueshifted to infinity to Alice?
I believe the actual amount of blueshift is not explained by the answers to question: What will the universe look like for anyone falling into a black hole? ?

A: You're right. Let's assume Alice is hoovering just above the horizon (let's not consider the fact that an enormous amount of energy is needed for this).
Her time is almost standing still wrt to the most parts of the Universe. She sees the hole evaporate in a flash (though when the hole gets smaller she'll have to maintain the infinitely small distance to the shrinking horizon.
When the hole has evaporated (how long this takes depends on the mass of the hole), she'll be in sync again with most parts a the Universe (where gravity is weak).
So, indeed, it works in both directions, but oppositely.
EDIT
After reading the comment below by @anneb, the situation gets more complicated.
Of course, Alice needs a huge energy supply (dependent on the BH's mass) of energy to hoover above the BH's horizon. In the part above I assumed to ignore this.
If she could fill her rocket with energy extracted from the BH and her rocket will use photons to propel the rocket and counteract the gravity of the hole. The photons will re-enter the hole though, so the mass of the BH will stay the same. So there will be no difference.
The question remains essentially the same if Alice is hoovering at a considerable distance. In that case, she still needs much fuel to counteract the BH's gravity. If this is done again by ejecting photons, the photons will be absorbed by the hole which thus gets heavier.
Alice makes sure that the distance to the horizon stays the same. While her tank (say positrons and electrons) gets emptier it will in time become easier to stay put where she is.
The BH's mass has increased, so the time to evaporate has increased also. In that case, it takes more time for Alice to get back in sync with the clocks in the major part of the Universe, where gravity is absent. The times on her clock and the times on the clocks in empty space will differ though.
It needs a calculation to find out if the rocket's mass, i.e., including the fuel (which we assume to be positrons) will be that high to form a BH. But since I just woke up, I'll do that later.


text:
Q: . Read in real numbers until 10 positive values have been found. Write out the sum of the 10 positives Here's the important part of my code:
int realnum, positive = 0, total, poscount;
for (poscount = 1; poscount < 11; poscount++)
{
    cin >> realnum;
    while (realnum > 0)
    {
        total = realnum + positive;
    }
}
cout << "Total of 10 positive values is " << total << endl;

I really just don't see what's wrong here. After declaring my integers the program goes into my for, increase the poscount to 2, asks my to input realnum. I put in a positive number (ex: 6), which should in theory add my realnum with positive (which I declared 0) and give total the value (ex: 6 + 0 = 6). It should keep looping until poscount reaches 11 and output the total of 10 positive numbers.
When I run it, I put in 6 and the command prompt just shows 6, nothing happens, and I have to close through the x button. Can someone please tell me what the error is?

A: I would just use a while in the outer loop, to keep the number of so-far positive numbers.
Also, your total is uninitialised and you assign positive to it, which is just 0?
This is what I have in mind:
int realnum, total = 0, poscount = 0;

while (poscount < 10) {
    cin >> realnum;
    if (realnum > 0)
    {
        total += realnum;
        poscount++;
    }
}
cout << "Total of 10 positive values is " << total << endl;

A: Replace your while with an if since currently, once you enter that while loop you never exit it.
Also, why are you always increasing poscount? Shouldn't you only do that if realnum is positive? The iteration statement in the for loop is allowed to be blank; then you write poscount++ inside the new if block.
You also need to write total += to increment the total amount.
These things are easy to spot if you use your debugger.

A: Okay, so I think I've corrected myself (without blatantly copying blurry but also using Bathsheba's tip on replacing my while.
int realnum = 1, positive = 0, total, poscount;
if (realnum > 0)
{
    for (poscount = 1; poscount < 11; poscount++)
    {
        cin >> realnum;
        total = realnum + positive;
        positive = total;
    }
}
cout << "Total of 10 positive values is " << total << endl;

So far, it seems to work, there's probably a lot of unnecessary things that make it inefficient but I didn't want to copy examples.  *Edit of course I still need to do with the ignoring negative part
I think I backed myself into the point of no return, ha. I really thought there was an alternate way I was going... Anyways, thanks for your replies, guys. I've always been lurking around here, until I made an account now.

A: Add a condition to terminate the while loop. And instead of adding positive to realnum, try adding poscount. That should provide the desired result.


text:
Q: tufte-latex: vertical adjustment of biblatex citations in captions I successfully implemented these three solutions:
tufte-latex: biblatex citations in captions
Is it possible to fine-tune the citation positions in Tufte-BibLaTeX combination?
Biblatex citecounter not counting reference in figure caption
Now, I am facing a related challenge.  Basically, I need to make a vertical adjustment to the sidenote that is located within a caption. In the MWE below I need to move it down in the margin.  I have attempted to do this, but it is not working for some reason.  Any help on how to overcome this issue would be greatly appreciated!
(two other unrelated issues are that 1. the figure scaling option is not working. and, 2. there is no period after the urldate field (or the year field) under the listed "Internet Sources" (@online entry) in the bibliography which is causing the subsequent word "cited" not to be capitalized.) Regarding the period issue, I created a new question here:  tufte-latex: missing periods in biblatex entry
\RequirePackage[l2tabu, orthodox]{nag}
\RequirePackage[hyphens]{url}
\documentclass[a4paper,twoside,nobib]{tufte-book}
\hypersetup{colorlinks,citecolor=blue}
\usepackage{hyphenat}
\usepackage{xpatch}
\usepackage[
style=verbose,
autocite=footnote,
sorting=nty,
citecounter=true,
citetracker=true,
backref=true,
backend=biber
]{biblatex}
\setlength\bibitemsep{0.5\baselineskip}
\addbibresource{HSFSS-BIBLATEX.bib}
\renewbibmacro*{doi+eprint+url}{%
  \iftoggle{bbx:doi}
    {\printfield{doi}}
    {}%
  \newunit\newblock
  \iftoggle{bbx:eprint}
    {\usebibmacro{eprint}}
    {}%
  \setunit{\addspace}\newblock
  \iftoggle{bbx:url}
    {\usebibmacro{url+urldate}}
    {}}
\usepackage{xparse}
\makeatletter
\xpatchcmd{\@footnotetext}%
{\color@begingroup}
{\color@begingroup\toggletrue{blx@footnote}}
{}
{}
\makeatother
%
\DeclareCiteCommand{\sidecitehelper}[\bibfootnotewrapper]
{\usebibmacro{prenote}}
{\usebibmacro{citeindex}%
    \usebibmacro{cite}}
{\multicitedelim}
{\usebibmacro{cite:postnote}}
%
\ExplSyntaxOn
\NewDocumentCommand\sidecite{D<>{}O{}om}{%
    \iftoggle{blx@footnote}
    {\cs_set_protected_nopar:Npn \__sct_wrapper:nn ##1 ##2 {\mkbibparens{##2}}}
    {\cs_set_protected_nopar:Npn \__sct_wrapper:nn ##1 ##2 {\sidenote[][##1]{##2}}}
    {\IfNoValueTF{#3}
        {\__sct_wrapper:nn{#1}{\sidecitehelper[#2]{#4}}}
        {\__sct_wrapper:nn{#1}{\sidecitehelper[#2][#3]{#4}}}}
}
\ExplSyntaxOff
%
\makeatletter
\long\def\@caption#1[#2]#3{%
    \expandafter\ifx\csname if@capstart\expandafter\endcsname
    \csname iftrue\endcsname
    \global\let\@currentHref\hc@currentHref
    \else
    \hyper@makecurrent{\@captype}%
    \fi
    \@ifundefined{NR@gettitle}{%
        \def\@currentlabelname{#2}%
    }{%
        \NR@gettitle{#2}%
    }%
    \par\addcontentsline{\csname ext@#1\endcsname}{#1}{%
        \protect\numberline{\csname the#1\endcsname}{\ignorespaces #2}%
    }%
    \begingroup
    \toggletrue{blx@footnote}%
    \@parboxrestore
    \if@minipage
    \@setminipage
    \fi
    \@tufte@caption@font\@tufte@caption@justification%
    \expandafter\ifx\csname if@capstart\expandafter\endcsname
    \csname iftrue\endcsname
    \global\@capstartfalse
    %\@makecaption{\csname fnum@#1\endcsname}{\ignorespaces#3}%
    \noindent\csname fnum@#1\endcsname: \ignorespaces#3%
    \else
    %\@makecaption{\csname fnum@#1\endcsname}{%
    \noindent\csname fnum@#1\endcsname:
    \ignorespaces
    \ifHy@nesting
    \expandafter\hyper@@anchor\expandafter{\@currentHref}{#3}%
    \else
    \Hy@raisedlink{%
        \expandafter\hyper@@anchor\expandafter{%
            \@currentHref
        }{\relax}%
    }%
    #3%
    \fi
    %}%
    \fi
    \par
    \endgroup
}
%
\renewcommand\@footnotetext[2][0pt]{%
    \marginpar{%
        \hbox{}\vspace*{#1}%
        \def\baselinestretch {\setspace@singlespace}%
        \reset@font\footnotesize%
        \@tufte@margin@par% use parindent and parskip settings for marginal text
        \vspace*{-1\baselineskip}\noindent%
        \protected@edef\@currentlabel{%
            \csname p@footnote\endcsname\@thefnmark%
        }%
        \color@begingroup%
        \toggletrue{blx@footnote}%
        \@makefntext{%
            \ignorespaces#2%
        }%
        \color@endgroup%
    }%
}%
\makeatother
%
\makeatletter
\AtBeginDocument{%
    \patchcmd\@floatboxreset
    {\boolfalse{citetracker}%
        \boolfalse{pagetracker}}
    {}
    {}
    {\blx@err@patch{float}}}
\makeatother
%
\renewbibmacro*{pageref}
{%
    \iflistundef{pageref}
    {\printtext{(\autocap{n}o citation in the text.)}}
    {
        \printtext{\autocap{c}ited \arabic{citecounter} time\ifnumgreater{\value{citecounter}}{1}{s}{}}%
        \setunit{\addspace}
        \ifnumgreater{\value{pageref}}{1}
        {\bibstring{backrefpages}\ppspace}
        {\bibstring{backrefpage}\ppspace}%
        \printlist[pageref][-\value{listtotal}]{pageref}
    }
}
\DefineBibliographyStrings{english}{
    backrefpage  = {on page},
    backrefpages = {on pages},
}
\usepackage[T5,T1]{fontenc}
\usepackage[english]{babel}
\usepackage{ebgaramond}
\usepackage{textcase}
\usepackage{mfirstuc}
\usepackage{expl3}
\usepackage[stretch=10]{microtype}
\usepackage{ragged2e}
\makeatletter\usepackage{microtype}\g@addto@macro\@verbatim{\microtypesetup{activate=false}}\makeatother
\usepackage[svgnames]{xcolor}
\usepackage{amssymb,amsmath,amsthm}
\usepackage{mathtools}
\usepackage{todonotes}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepackage[toc,page]{appendix}
\usepackage{makeidx}
\makeindex
\usepackage{multicol}
\usepackage{enumitem}
\usepackage{multirow}
\usepackage{booktabs}
\usepackage{array}
\usepackage{tabularx}
\usepackage{float}
\usepackage[autostyle=true]{csquotes}
\usepackage{graphicx}
\setkeys{Gin}{width=\linewidth,totalheight=\textheight,keepaspectratio}
\graphicspath{{graphics/}}
\usepackage{fancyvrb}
\fvset{fontsize=\normalsize}
\usepackage{units}
\usepackage{xspace}
\newcommand{\openepigraph}[3]{
    \begin{fullwidth}
        \sffamily\small
        \begin{doublespace}
            \noindent\allcaps{#1}\\% epigraph
            \noindent\allcaps{#2}#3% author & autocite
        \end{doublespace}%
    \end{fullwidth}
}
\usepackage[toc]{glossaries}
\makeglossaries
\newglossaryentry{hybridization}{name=hybridization,description={The genetic cross of two species or subspecies either naturally or artificially resulting in a new species referred to as a hybrid. Some common examples include mules, ligers, bananas and maize. For further study see:\\ \url{https://en.wikipedia.org/wiki/List_of_plant_hybrids}\\ \url{https://youtu.be/JarGdMEQElo}\\ \url{https://en.wikipedia.org/wiki/Hybrid_(biology)}\\ \url{https://en.wikipedia.org/wiki/List_of_genetic_hybrids}\index{hybridization}}}
%
\begin{document}
\openepigraph{%
Here, the intersection of the timeless moment\\\noindent
Is England and nowhere. Never and always.
}{—T.S. Eliot}{\sidecite<-0.2in>[][lines 41-55]{tseliot}}
\vfill
\openepigraph{%
The unexamined life is not worth living.
}{—Socrates}{\sidecite<-0.3in>{Socrates}}
\openepigraph{%
And in the end, the love you take is equal to\\\noindent
the love you make.
}{—The Beatles}{\sidecite<-1cm>{Beatles}}
Hybrid\index{hybrid} life forms are interesting. This is due to the fact of \textbf{\gls{hybridization}}\index{hybrid!hybridization}. Hybridization can be either natural or artificial. One could view hybridization as a cross of parents.\sidecite<-0.45in>{Hybridization}
In this scenario the potato acts like a pesticide, killing the Colorado potato beetle.\sidecite<0.7in>{BtPotato}
\begin{figure}
    \includegraphics[scale=0.5]{helix.pdf}
    \caption[The Helix Compass][6pt]{\emph{Used with permission.}\xspace\sidecite<1.5in>{tseliot}}\index{helix}\index{Helix Compass|emph}
    \label{fig:helix compass}
\end{figure}
 Furthermore, the same eventually leads to stereotypes, racism, poor public policy decisions and limited diagnoses and services.\sidecite<-1in>{Autism}
\openepigraph{%
To believe is to know you believe,\\\noindent
and to know you believe is not to believe.}{—Jean-Paul Sartre}{\sidecite<>[][34]{jpsarte}}\index{belief}
Your key to all of this is \textbf{Love\index{Love}}.
\openepigraph{%
    The first problem for all of us, men and women,\\\noindent
 is not to learn, but to unlearn.
}{—Gloria Steinem}{\autocite{GSteinem}}\index{Steinem, Gloria}
\openepigraph{Love is Love.}{—President Barak Obama}{\autocite{Obama}}\index{Love}\index{Obama, Barak}
\openepigraph{%
Into the crowned knot of fire\\\noindent
And the fire and the rose are one.
}{—T.S. Eliot}{\sidecite<>[][lines 241-263]{tseliot}}
\printglossaries
\printbibheading
\printbibliography[type=book,heading=subbibliography,title={Book Sources}]
\printbibliography[type=online,heading=subbibliography,title={Internet Sources}]
\printbibliography[nottype=book,nottype=online,heading=subbibliography,title={Other Sources}]
\printindex
\end{document}

.bib file
@MISC{Autism,
    author = {Garcia, Eric},
    title = {{"Eric Garcia's 'We're Not Broken' Aims to Change the Conversation About Autism." Interview with April Dembosky. Produced by KQED Inc.}\textit{ Forum}},
    date = {},
    addendum = {Oct. 8, 2021. Podcast audio, 53:12. [Acc. 3 Sep. 2022].},
    howpublished = {\url{https://www.kqed.org/forum/2010101885895/eric-garcias-were-not-broken-aims-to-change-the-conversation-about-autism}}
 }

@online{BtPotato,
    author = {contributors SourceWatch},
    title = {{"Colorado Potato Beetle Resistant Bt Potato"}\textit{ SourceWatch}},
    year = {2012},
    url = {https://www.sourcewatch.org/index.php?title=Colorado_Potato_Beetle_Resistant_Bt_Potato&oldid=583413},
    urldate = {2022-08-22}
}

@MISC{Hybridization,
    author = {Colston-Nepali, Lila M.
     and Leigh, Deborah M.},
    title = {{"Ligers and Tigons and Grolars, Oh My! Hybridization, and How It Affects Biodiversity"} \textit{Frontiers for Young Minds} | 7:113. doi: 10.3389/frym.2019.00113},
    date = {},
    addendum = {Sep. 12, 2019. [Acc. 21 Aug. 2022].},
    howpublished = {\url{https://kids.frontiersin.org/articles/10.3389/frym.2019.00113}}
}

@MISC{GSteinem,
    author = {Steinem, Gloria},
    title = {{"A New Egalitarian Life Style"} \textit{New York Times}},
    date = {},
    addendum = {Aug. 26, 1971. [Acc. 12 Feb. 2022].},
    howpublished = {\url{https://www.nytimes.com/1971/08/26/archives/a-new-egalitarian-life-style.html}}
}

@MISC{Obama,
    author = {Obama, Barak},
    title = {{"President Obama lauds high court decision on gay marriage"}},
    date = {},
    addendum = {White House Rose Garden, filmed Jun. 26, 2015. Video of lecture, 9:07. [Acc. 1 Feb. 2022].},
    howpublished = {\url{https://youtu.be/toAVEgQUhxo}}
}

@MISC{Beatles,
    author = {Lennon, John and McCartney, Paul},
    title = {\textit{The End} {(line 8) | Abbey Road No. 10 | The Beatles}},
    date = {},
    addendum = {Apple, 1969. [Acc. 28 Jan. 2022].},
    howpublished = {\url{https://thebeatles.com/end}}
}

@MISC{Socrates,
    author = {Plato},
    title = {\textit{The Socratic Dialogues} {| The Apology of Socrates, Part II (Translated by W. D. Woodhead, 1953)}},
    date = {},
    addendum = {Mar. 2008. [Acc. 28 Jan. 2022].},
    howpublished = {\url{http://davidgorman.com/socrates.htm}}
}

@MISC{tseliot,
    author = {Eltiot, T. S.},
    title = {\textit{Four Quartets}{ | Quartet No. 4: Little Gidding}},
    date = {},
    addendum = {Dec. 2013. [Acc. 27 Jan. 2022].},
    howpublished = {\url{http://davidgorman.com/4quartets/4-gidding.htm}}
}

@MISC{pkg-geometry,
    author = {Hideo Umeki},
    title = {The \texttt{geometry} package},
    date = {},
    addendum = {Dec. 2008.},
    howpublished = {\url{http://ctan.org/pkg/geometry}},
}
%
% NOTE: If using the MISC entry, the title must be in %
% double brackets {{ title }} %
% in order to avoid a capitalization issue. %
%

@BOOK{jpsarte,
    author = {Jean-Paul Sartre},
    title = {Being and Nothingness},
    year = {2003},
    edition = {2},
    publisher = {Routledge},
    location = {London, England},
    isbn = {9780415278485.}
}

@BOOK{Carse,
    author = {James P. Carse},
    title = {FINITE \textsc{and} INFINITE GAMES},
    subtitle = {A Visioin of Life as Play and Possibility},
    year = {1986},
    publisher = {The Free Press, A Division of Macmillan, {Inc.}, Simonandschuster.com},
    location = {New York, New York},
    addendum = {ISBN-0-02-905980-1; eISBN-13:978-1-45165-729-6 Kindle.}
}

@BOOK{Tufte2006,
    author = {Edward R. Tufte},
    title = {Beautiful Evidence},
    year = {2006},
    publisher = {Graphics Press, {LLC}},
    month = {5},
    edition = {First},
    location = {Cheshire, Connecticut},
    isbn = {0-9613921-7-7.}
}

@BOOK{Tufte2001,
    author = {Edward R. Tufte},
    title = {The Visual Display of Quantitative Information},
    publisher = {Graphics Press},
    year = {2001},
    location = {Cheshire, Connecticut},
    isbn = {0-9613921-4-2.}
}

@BOOK{Tufte1990,
    author = {Edward R. Tufte},
    title = {Envisioning Information},
    publisher = {Graphics Press},
    year = {1990},
    location = {Cheshire, Connecticut},
    isbn = {0-9613921-1-8.}
}

@BOOK{Tufte1997,
    author = {Edward R. Tufte},
    title = {Visual Explanations},
    publisher = {Graphics Press},
    year = {1997},
    location = {Cheshire, Connecticut},
    isbn = {0-9613921-2-6.}
}

@BOOK{Bringhurst2005,
    author = {Robert Bringhurst},
    title = {The Elements of Typography},
    publisher = {Hartley \& Marks},
    year = {2005},
    edition = {3.1},
    isbn = {0-88179-205-5.}
}

@BOOK{Mittelbach2004,
    author = {Frank Mittelbach and Michel Goossens},
    title = {The \LaTeX\ Companion},
    publisher = {Addison--Wesley},
    year = {2004},
    edition = {Second},
    isbn = {0-201-36299-6.}
}

A: I was able to utilize a workaround to my issue since I learned that the tufte-latex class has customized a vertical offset for captions in the form:
\caption[short caption][<offset>]{long caption}

(I am still seeking any feedback, guidance, solutions etc. to the other two parenthetical issues I mentioned in my question. Regarding the period issue, I created a new question here:  tufte-latex: missing periods in biblatex entry )


text:
Q: Terminology about G- simplicial complexes For a simplicial complex $X$ with an action of a discrete group $G$, we can impose the following condition, namely that if $g\in G$ stabilizes a given simplex $\sigma\subseteq X$, then $g:\sigma\to\sigma$ is in fact the identity map.  This condition is nice because it implies that the quotient $X/G$ is glued out of simplices (rather than simplices modulo a finite group of permutations of their vertices).

Is there a standard term for this condition (or any related one) on the action $G\curvearrowright X$?

A: I've never stumbled across a standard one in all of the literature, though I've definitely appreciated a remark by Ken Brown in his group cohomology bible: "The hypothesis that $G_\sigma$ fixes $\sigma$ pointwise is not very restrictive in practice. In the case of a simplicial action, for example, it can always be achieved by passage to the barycentric subdivision."
Some references have the pointwise-fixed assumption baked into the definition of a $G$-CW-complex, but not all. Ken Brown's book doesn't, and he calls a $G$-CW-complex "admissible" if we include the pointwise-fixed constraint. This doesn't seem to be standard though. (Now as for definite nonstandard terminology, Farb-Margalit's book "A Primer on Mapping Class Groups" calls it a group action "without rotations".)


text:
Q: Navigation Bar "Cancel" I'm currently facing the issue in which if I select on a row in a tableview and go back and press on the "+" button in the navbar, my app will crash. I suspect this may be because I chose the "show modally" option in xcode. Anyways, I may be completely off but here's my code. Please bear with me as I have only picked up coding
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  NSIndexPath *path = [self.tableView indexPathForSelectedRow];
  displayViewController *vc;

  vc = [segue destinationViewController];
    if (path != NULL) {
        vc.pID = path.row;
    }
}

This is my prepareForSegue function and the error is happening when I try to set vc.pID to path.row because if I click on the "+" button, it doesn't have a row. Is there a way to not go into the prepareForSegue function if I press the "+" button?
Thank you for your help!

A: What you want to do is add a test for the segue identifier into prepareForSegue.
The segue property has an identifier value.
if segue.identifier == "nameOfSegueIdentifier" { // do stuff here }

That way you can run specific code depending on which aspect of your UI is triggering the segue.
edit
Sorry, only saw now that you're using objective C. My code is in Swift. Not sure how to implement it in objective C, but the concept will be the same.

A: The form of prepare for segue in objective-c is...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"someIdentifierA"]) {
        // get the table view selection, for example
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        // get some part of my datasource (model), for example
        MyModelObject *modelObject = self.datasourceArray[indexPath.row];
        // initialize part of the model on the destination vc
        MyOtherViewController *destination = (MyOtherViewController *)segue.destinationViewController;
        destination.modelObject = modelObject;
    } else if ([segue.identifier isEqualToString:@"someIdentifierB"]) {
        // same idea here, but different segue to different destination
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        displayViewController *vc = (displayViewController *)[segue destinationViewController];
        vc.pID = path.row;
    } else if // and so on
    }
}


text:
Q: TextInputLayout is not working when I set OutlinedBox in style Working on layout added dependencies implementation 'com.google.android.material:material:1.1.0'
after also it is not working
   <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:layout_below="@+id/textView"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

        <EditText
                android:id="@+id/editTextCode"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:drawablePadding="10dp"
                android:inputType="phone"
                android:maxLength="6"
                android:paddingStart="3dp"
                android:drawableLeft="@android:drawable/stat_sys_phone_call"
                android:gravity="start"
                />
    </com.google.android.material.textfield.TextInputLayout>`

A: use TextInputEditText insted of EditText. Check the below code
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/textInputLayoutName"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/textInputLayoutEditTextName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Name"
                    android:inputType="text"
                    android:text="Data" />

</com.google.android.material.textfield.TextInputLayout>

A: Use the startIconDrawable attribute to define an icon and use the TextInputEditText instead of the EditText:
    <com.google.android.material.textfield.TextInputLayout
        app:startIconDrawable="@drawable/ic_add_24px"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        ..>

        <com.google.android.material.textfield.TextInputEditText
            android:inputType="phone"
            android:maxLength="6"
            android:paddingStart="3dp"
            />
    </com.google.android.material.textfield.TextInputLayout>

A: //Got solution actually problem in style

<style name="AppTheme" parent="**Theme.MaterialComponents.Light.DarkActionBar**">

//Changed parent theme to MaterialComponents its working well for me.


text:
Q: WordPress site layout broken in IE8 I am having an IE8 css problem on a WordPress site.  The layout keeps breaking and everything shifts to the left on the home page.  Of course it is driving the client crazy and I need a fix this morning. Any IE8 gurus out there that can help?  http://stat-management.net

A: IE should have been taken out back and shot. Try adding:
body {
   text-align: center;
}
#page {
   text-align: left;
}

And this will fix the (quirks mode) problem.


text:
Q: javascript object filter using user_id not return expect result I have below object
var total_hours = <?php echo json_encode($total_hours); ?>;

    [
      {"user_id": 2959
       "total_hours": "38"
      }
      {"user_id": 116
       "total_hours": "1"
      }
    ]

i want to get total_hours base on user_id
var user = document.getElementById("user").value;

            var yahooOnly = total_hours.filter(function (entry) {
                return entry.user_id === user;
            });

            total_hours = yahooOnly;

but um unable to get required output. Can someone helps me?
Try this question but didn't get required output!

A: filter() returns an array. You need to index it and then access the total_hours property.
You can use .find() instead of .filter() to get the object instead of an array.

var total_hours = [{
  "user_id": 2959,
  "total_hours": "38"
}, {
  "user_id": 116,
  "total_hours": "1"
}];

var user = 2959;
var yahooOnly = total_hours.find(entry => entry.user_id == user);
var yahoo_hours = yahooOnly.total_hours;
console.log(yahoo_hours)


text:
Q: Having trouble solving a Django test for page content I'm currently working my way through the Django tutorial and I'm having trouble getting one of the tests from chapter 5 to pass.
Specifically this one:
    def test_detail_view_with_a_past_question(self):
        past_question = create_question(question_text='Past question.', days=-5)
        response = self.client.get(reverse('polls:detail', args=(past_question.id,)))
        self.assertContains(response, past_question.question_text, status_code=200)

I see the response does contain 'Past question'. But it's stored under response -> context_data -> 'question'
Here's the function for create question:
def create_question(question_text, days):
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)

The Question model:
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

And the view:
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

If it helps, the Git repo with everything can be found here.
Thanks in advance for the help!

A: In your template in file templates/polls/detail.html you have a typo:
You should replace:

{{ question.question_test }}

with

{{ question.question_text }}


text:
Q: Which pseudo random number generator algorithm does java.util.Random in Java 8 use? I'm trying to find out exactly how java.util.Random in java 8 generates its random numbers, more specifically the algorithm behind it. All I keep seeing is how to generate random numbers in java 8 and not the driving forces behind it.
If you could point me to any documentation regarding the PRNG that java.util.Random uses that would be perfect.
Also in case its been done already, is there a way of replicating the output of java.util.Random in python?
A Quick test using a seed of 5 and int range of 0 to 100 gives different results to pythons random module

A: Quoting Java docs:

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

So it seems that a Linear congruential generator with a 48bit seed is used.
I do not have access to the mentioned book, but I would guess it gives more detailled information.


text:
Q: Rails association for different user types I have a user model and want to attach profile information to it specific to the gender.
Should I have a FemaleProfile & MaleProfile model in addition to the User model that holds the gender neutral data as illustrated below?
User model:
has_one :FemaleProfile
has_one :MaleProfile

Fields :Name, :Age

FemaleProfile model:
belongs_to :User

Fields :Name, :Age, :Dress_Color

MaleProfile model:
belongs_to :User

Fields :Name, :Age, :Tie_Color

What I don't understand if this is indeed correct is that a user has either a male or female profile yet the association has both types of profile associated with the User.
Is there an inverse polymorphic relationship? I have taken a look at STI but it does not allow fields exclusive to the inheriting models.

A: I would consider in this cas using Multi Table Inheritance. I personally use the citier gem to implement this : http://inspiredpixel.net/citier/
Concretely, you would have a User table with the 4 common fields, and 2 inherited tables, each one with its own fields, which seems to be what you look for.

A: You can go with polymorphic associations (why are you asking for an inverse polymorphic implementation?) or a serialized attribute.
Serialized Attribute
you can add a gender_details column with type text and then serialize this attribute.  then define female and male attributes.
# user.rb
class User < ActiveRecord::Base
  MALE_DETAILS = %w[sports cars]
  FEMALE_DETAILS = %w[perfume flowers]

  serialize :gender_details, Hash

  (MALE_DETAILS + FEMALE_DETAILS).each do |attr|
    define_method attr do
      self.gender_details ||= {}
      self.gender_details[attr.to_sym]
    end

    define_method "#{attr}=" do |value|
      self.gender_details ||= {}
      self.gender_details[attr.to_sym] = value
    end
  end
end

so you can use
user.sports = 'Basketball'
user.flower = 'Rose'


text:
Q: GPS PPS signal corresponds to data time? I currently have an Adafruit Ultimate GPS connected to an Arduino that outputing GPS data (nmea sentences) once per second.  There is also a pin on the GPS outputting 1 PPS signal.
My question is whether the pulse of the PPS suppose to match the time that the GPS data is coming in i.e are they are coming in at the same time?
Also does PPS pulse come in at the beginning of a UTC second or is it random and simply once a second?

A: I have not used the Adafruit GPS, but GPS units almost always output the time after the PPS signal has been sent.  They do this because the PPS signal is typically tied to the timing of the data stream coming from the satellite (or at least most GPSs have a mode where they are tied).  In this case, the PPS is sent at exactly the moment the GPS satellite data stream says a UTC second starts.  After that, they process the data, determine what time it actually was, and relay that data.
Some GPS have other modes where the PPS does not occur exactly at the top of a UTC second (which is helpful if you want to use the PPS signal before you have a GPS feed), but those that I have seen typically default to the PPS occurring at the top of the second.
If you need to know the time of the PPS, you need to latch an internal timer when the PPS signal occurs, then associate that with the data from the GPS when it comes in.  Alternatively, keep track of the GPS data and, when the PPS is asserted, you can assume that it is now most_recent_gps_time_utc + 1 second.

A: I have a Dragino Lora/GPS Shield, which is based on the MT3339 chipset
also used in the Adafruit Ultimate GPS Module. I did a couple of
experiments with this shield in order to answer this very same
questions. My conclusions are in line with the previous answers, namely:

*

*The rising edge of the PPS signal is aligned with the start of a UTC
second (this I already knew).

*The time stated in an NMEA sentence is valid on the rising edge of
the PPS pulse that immediately preceded that sentence.

Here is what I did:

*

*I captured both the PPS and the TX signals on a scope, as suggested
in old_timer's answer

The yellow trace is the PPS signal. It's high for about 100 ms
every second. The cyan trace is TX. This trace shows the serial data is
sent in bursts, with each burst starting shortly after the falling edge
of the PPS signal.

*I timed the serial stream on my computer

The hardware setup was:
amplified antenna → GPS module → Arduino Uno → laptop

The Arduino was used just as a serial/USB gateway (TX of GPS connected
to TX of Arduino, which runs a "do nothing" program). The laptop was
synchronised to within a few milliseconds of UTC via NTP. I used the
following Node.js program for logging timestamped serial data:
const SerialPort = require("serialport");
var port = new SerialPort("/dev/ttyACM0", { baudRate: 9600 });

// Discard the first data chunk.
port.once("data", function() {

    // Log subsequent chunks.
    port.on("data", function(data) {
        console.log(new Date().toISOString().split(/[TZ]/)[1],
              JSON.stringify(String(data)));
    });
});

The output of the program looks like this (comments added):
20:16:44.810 "\n"     <-- end of burst
20:16:45.171 "$GP"    <-- start of burst, "GPRMC" sentence
20:16:45.175 "RMC,"   <--
20:16:45.179 "2016"   <-- UTC time: "201645.000",
20:16:45.183 "45.0"   <-- meaning 20:16:45.000 UTC
20:16:45.187 "00,A"   <--
...

where the first column is the UTC time, with millisecond resolution.
This shows the program (or the serial port driver) is not fast enough to
catch and timestamp individual characters, and there is some buffering
going on. But it is still fast enough four our purposes. It also shows
that the "GPRMC" sentence announcing the time 20:16:45.000 UTC was
transmitted around 20:16:45.18, give or take a few tens of milliseconds.
Note that the same announced time was repeated twice within the same
burst: first in a GPGGA sentence transmitted around 20:16:45.30, then in
a GPGLL sentence transmitted around 20:16:45.74.

A: There is no way to accurately output a message at a given time. The accuracy is given by the pulse, the message completes all the needed data (day, hours, minutes, etc.)
But the accurate time signal is the PPS signal itself

A: As far as I can tell, the PPS pin is pulled high for 100 milliseconds at the start of each UTC second (assuming GPS lock).  By default, the GPS outputs position information at 1Hz, and the time given in the NMEA sentences indicates that they also are specified at the start of each UTC second.
The serial data is not sent at the exact instant the PPS pin goes high, but you need to wait a few milliseconds to get the full set of NMEA sentences anyway.  Using the default sentence settings and baud rate, I got an average of 348 bytes/s, which with a baud rate of 9600 (9600 bits/second) would take 290 milliseconds to send.  So, as Cort says, each rising edge of the PPS pin occurs at "most_recent_gps_time_utc + 1 second".
The GPS gathers satellite data while sending a PPS pulse at UTC second X.  It does the necessary calculations, then outputs the NMEA sentences for the position at second X, therefore the GPS data for second X is always received a few hundred milliseconds after the PPS pulse for second X.

A: The manual for the receiver used on that Adafruit board is pretty bad.  I randomly selected a trimble based one on sparkfun and at least for that module it was a bit better.  first and foremost for the trimble one you select positive edge or negative edge, so you need to know from the one you are using which edge is the correct edge (if it is a short pulse, not a 50% duty cycle, from a scope it is hopefully obvious the leading edge of the short pulse is likely the edge you want).
The only other clue we get from the trimble manual (again not the one you have is):
Once time is acquired, on the next PPS add 1 to the whole second to read the correct time.
Which for that unit means the time you get from the nmea string and then on the next pulse you add one second.  I would not assume that this is true for all of them but it makes sense.  It implies that for this one the pulse is related to the string that is coming out or about to.  by then it is too late of course.
EDIT
Of course no reason why you couldnt have found this information yourself, another brand unit says that Each message is output within a few hundred ms after the 1PPS pulse is output and tells the time of the pulse that just occurred.   So basically the same as the trimble add one second to the time you just read when you get a pulse.  This other brand is a rising edge doesnt sound like you have control over that.
You also need to understand how your signal is recived by hardware, for example if they are using an optoisolator or some other form of isolation it may invert the signal so it may go out the receiver one way but enter your chip the other.  With your arduino it is hardwired no isolation you get what you get.
A scope should make all of this obvious, put both the serial tx and the 1pps on the scope ideally you see the 1pps leading edge and then after that see the burst of serial messages.  That one picture should tell the whole story.

A: My small contribution here. To double check this, I wrote a bit of code (available here: https://github.com/jerabaul29/interrupt_GPS_synchronization/tree/master/PPS_clock_signal ) that basically:

*

*measures the time (micros) when PPS rises with an interrupt pin

*dump all GPS NMEA sentences as they arrive together with corresponding receiving time (micros again)

*measures the time (micro again) when 'new second' messages arrive from the computer.

The results are following, and correspond to what the other answers have been describing:
2020-04-08 11:46:39.000017
interrupt pin 2 triggered 2717740 elapsed 999792
2020-04-08 11:46:39.007220
interrupt pin 3 triggered 2720380 elapsed 999796
2020-04-08 11:46:39.011312
delay 2 to 3 is 2640
2020-04-08 11:46:39.014655
$GPGGA,094639.000,5956.4113,N,01040.6931,E,2,08,0.88,91.0,M,40.7,M,0000,0000*5D
2020-04-08 11:46:39.477875
micros = 3195544
2020-04-08 11:46:39.478235
$GPRMC,094639.000,A,5956.4113,N,01040.6931,E,0.12,125.18,080420,,,D*68
2020-04-08 11:46:39.555399
micros = 3271192
2020-04-08 11:46:39.555585
start new second

This is one more hint that, similar to what the other answers suggest:

*

*first the pin 2 (in my case, PPS) rises

*then very soon after the pin 3 (driven by another board that follows the 'new second' message from the computer) rises

*then, the NMEA sentences arrive.

This is one more hint that for each given second, one first observes the rising PPS, and then after a while (due to processing / finite serial speed) the NMEA sentences for this UTC second are received.


text:
Q: Why are my matchers not working after adding an overloaded method? To help getting past our permission checks during unit tests to test actual functionality, I created a mocking class so people could just call the mocking method they needed from that class for the security class.  This includes methods that would take only a "desired result boolean", and uses matchers for the object and field.
I'm now getting errors as if the system doesn't recognize the mocking.
How do I mock this properly between the overloaded signatures and matchers?
I'll detail as best I can, but please let me know if I can supply any additional information.
We added a parameter to the field level methods in the security class to skip redundant object checks, and (to retain the references to the original method signature) overloaded it so that there was the original signature
//Old Security Class method:
isReadable(Boolean desiredResult, SObjectType targetObjectType, String fieldString)

and that one just forwarded to the next with objectCheck = true,
//New Security Class method:
isReadable(Boolean desiredResult, SObjectType targetObjectType, String fieldString, Boolean objectCheck)

isReadable(true, Device.getSObjectType(), 'Courier', true)

This meant we had to update the mocking to handle both method signatures, and a result of true or false for the new one:
//Non matcher and 2 matcher variants of Mocking Class methods
@TestVisible
    private static SecurityInterface isReadable(Boolean mockValue, SObjectType targetType, String fieldName){
        return isReadable(mockValue, targetType, fieldName);
    }

@TestVisible
    private static SecurityInterface isReadable(Boolean mockValue, SObjectType targetType){
        return isReadable(mockValue, targetType, fflib_Match.anyString());
    }

@TestVisible
    private static SecurityInterface isReadable(Boolean mockValue){
        return isReadable(mockValue, fflib_Match.anySObjectType(), fflib_Match.anyString());
    }

//Old mock implementation
@TestVisible
    private static SecurityInterface mockSecurityClassIsReadable(Boolean mockValue, SObjectType targetType, String fieldName){
        setupSecurityService();

        MOCKS.startStubbing();
        MOCKS.when(MOCKED_SECURITY_CLASS.isReadable(targetType, fieldName)).thenReturn(mockValue);
        MOCKS.stopStubbing();

        return MOCKED_SECURITY_CLASS;
    }

//New mock implementation
@TestVisible
    private static SecurityInterface mockSecurityClassIsReadable(Boolean mockValue, SObjectType targetType, String fieldName){
        setupSecurityService();

        MOCKS.startStubbing();
        MOCKS.when(MOCKED_SECURITY_CLASS.isReadable(targetType, fieldName)).thenReturn(mockValue);
        MOCKS.when(MOCKED_SECURITY_CLASS.isReadable(targetType, fieldName, true)).thenReturn(mockValue);
        MOCKS.when(MOCKED_SECURITY_CLASS.isReadable(targetType, fieldName, false)).thenReturn(mockValue);
        MOCKS.stopStubbing();

        return MOCKED_SECURITY_CLASS;
    }

This also required that I update the CommonMocks file to include both versions of the Security Class Method:
public Boolean isReadable(SObjectType objectType, String field)
{
    return (Boolean) mocks.mockNonVoidMethod(this, 'isReadable', new List<Type> {System.Type.forName('SObjectType'), System.Type.forName('String')}, new List<Object> {objectType, field});

}

public Boolean isReadable(SObjectType objectType, String field, Boolean objectCheck)
{
        return (Boolean) mocks.mockNonVoidMethod(this, 'isReadable', new List<Type> {System.Type.forName('SObjectType'), System.Type.forName('String'), System.Type.forName('Boolean')}, new List<Object> {objectType, field, objectCheck});
}

But when I implement my tests, I'm getting errors:
1) Succeeds
2) "CMPL123.fflib_ApexMocks.ApexMocksException: The number of matchers defined (1). does not match the number expected (2)
If you are using matchers all arguments must be passed in as matchers.
For example myList.add(fflib_Match.anyInteger(), 'String') should be defined as myList.add(fflib_Match.anyInteger(), fflib_Match.eq('String'))."
3) "System.NullPointerException: Attempt to de-reference a null object"
The de-reference null object message is typical for when the mocked instance isn't found for the implementation.
@IsTest
private static void mockSecurityClassIsReadableDoesNotThrowsExceptionWhenTrue(){
    MockingClass.mockSecurityClassIsObjectReadable(true);
    MockingClass.mockSecurityClassIsReadable(true,TEST_OBJECT_TYPE,TEST_FIELD);
    Boolean result = false;

    Test.startTest();
        result = SecurityClass.IsReadable(TEST_OBJECT_TYPE, TEST_FIELD, TEST_OBJECT_MESSAGE, TEST_FIELD_MESSAGE);
    Test.stopTest();

    System.assertEquals(true,result,'SecurityClass did not return correct result.');
}

@IsTest
private static void mockSecurityClassIsReadableDoesNotThrowsExceptionWhenTrueUsingMatcherFormForObject(){
    MockingClass.mockSecurityClassIsObjectReadable(true);
    MockingClass.mockSecurityClassIsReadable(true,TEST_OBJECT_TYPE);
    Boolean result = false;

    Test.startTest();
        result = SecurityClass.IsReadable(TEST_OBJECT_TYPE, TEST_FIELD, TEST_OBJECT_MESSAGE, TEST_FIELD_MESSAGE);
    Test.stopTest();

    System.assertEquals(true,result,'SecurityClass did not return correct result.');
}

@IsTest
private static void mockSecurityClassIsReadableDoesNotThrowsExceptionWhenTrueUsingMatcherFormForObjectAndField(){
    MockingClass.mockSecurityClassIsObjectReadable(true);
    MockingClass.mockSecurityClassIsReadable(true);
    Boolean result = false;

    Test.startTest();
        result = SecurityClass.IsReadable(TEST_OBJECT_TYPE, TEST_FIELD, TEST_OBJECT_MESSAGE, TEST_FIELD_MESSAGE);
    Test.stopTest();

    System.assertEquals(true,result,'SecurityClass did not return correct result.');
}

A: Here's a service (BarService) with an overloaded method execute. In both methods, true is returned.
public class BarService {
    public Boolean execute(Date d) {return true;}
    public Boolean execute(Date d, Id uId) {return true;}
}

And here's another service (the code-under-test, named FooService with method-under-test doStuff()) that calls both overloaded BarService execute(..) methods based on a runtime parameter.
public class FooService {
    private final BarService barService;
    public enum Dispatch {method1Arg,method2Arg}
    private Dispatch method;
    public FooService(Dispatch method) {
        this.barService = new BarService();
        this.method = method;
    }
    public FooService (BarService mockBarService, Dispatch method) {
        this.barService = mockBarService;
        this.method = method;
    }

    public Boolean doStuff() {
        switch on this.method {
            when method1Arg {
                return this.barService.execute(Date.today());
            }
            when method2Arg {
                return this.barService.execute(Date.today(),UserInfo.getUserId());
            }
            when else {return null;}
        }
    }
}

And here is the testmethod for the code-under-test
static void testBehavior() {
    fflib_ApexMocks mocks = new fflib_ApexMocks();
    // Given mock Service class
    BarService mockBarService = (BarService) mocks.mock(BarService.class);

    //  Given mock Service results for both 1 and 2 arg invocations
    mocks.startStubbing();
    mocks.when(mockBarService.execute(fflib_Match.anyDate()))
            .thenReturn(false);
    mocks.when(mockBarService.execute(fflib_Match.anyDate(),fflib_Match.anyId()))
            .thenReturn(false);
    mocks.stopStubbing();
    // Given a service that in turn calls BarService.execute w/ 1 arg
    //  use Dependency Injection so mock service is invoked
    FooService f1 = new FooService(mockBarService,FooService.Dispatch.method1Arg);

    // Given a service that in turn calls BarService.execute w/ 2 arg
    //  use Dependency Injection so mock service is invoked
    FooService f2 = new FooService(mockBarService,FooService.Dispatch.method2arg);

    //  when 1 arg use case
    System.assertEquals(false,f1.doStuff(),'sb result of mock for 1 arg BarService.execute(Date)');

    //  when 2 arg use case
    System.assertEquals(false,f2.doStuff(),'sb result of mock for 2 arg BarService.execute(Date,Id)');
}

Note that:

*

*No mismatched matchers error

*Mock service thenReturn works as expected as false is returned when underlying "real" method always returns true.

*I did not use the fflib Enterprise Pattern factory Application class as it didn't look like you were using that pattern. Instead the code-under-test is supplied via dependency injection the mocked dependent service. Of course, you could use your own factory pattern.

Now, this is more of a proof that overloaded methods can be mocked rather than directly answering your specific code issue.
But the point is that

*

*There is some code under test that depends on some dependent object method returning some value. In my example, this is FooService.doStuff()

*Hence, you mock the dependent object's methods as they will be called by the code-under-test. Since FooService.doStuff() invokes BarService.execute() in both 1 and 2 arg use cases, both of these execute invocations must be mocked using mocks.when(..)


text:
Q: GNU Makefile dependency in multi-job make I have a c++ project under linux. I'm using GNU make and GCC
I have following rules:
all: ...
version:
config:
  rm -f config.h
  @$(MAKE) --no-print-directory config.h
config.h:
 # ..... create the file config.h here

make version increases build number. 1.1-123, then 1.2-124 ... etc. The version is written in config.h file and config.h is included in all files in the project.
Now the idea is config.h to be rebuild in one of these cases:
  - when releasing a version of the program (rather than just developing/testing)
  - when it does not exists
so I do not want to make this dependancy:
all: config
config: version

because then config file will be rebuild on every make and every single file will be recompiled, not only changed files. So I want to not re-build config file while developing, but only if I do make release_version
Now. Lets say that rule is:
release_version: config version all

The problem is that when I do make release_version -j 3 it'll make all the 3 targets (config, version, all) at the same time which means that version might not be ready for creation of config.h, then config.h might not be ready for all. So I must make this dependency:
release_version: all
all: config
config: version
BUT ONLY when make release_version is executed. if make all is executed I don't want to have these dependencies.
Maybe I need something like:
release_version: version_release config_release all_release
all_release: config
config_release: config
version_release: version

A: Your examples are a bit haphazard.  It would be good if you re-read what you have and clarified it.  What does the version target do?  What is the relationship between version and config?  What is the relationship between this release_version which you don't show anywhere, and config and version?
If I understand correctly you want to have the all rule that will build the code using the existing version of config.h (creating it if it doesn't exist), and the release_version rule that will update config.h, then build the code as if it were all.  I'm not sure what version and config do.
You can do it like this, unless I'm missing something:
all: ...

release_version:
        @rm -f config.h
        @$(MAKE) config.h
        @$(MAKE) all

config.h:
        ...create config.h...

.PHONY: all release_version

There are lots of other options as well.

A: With GNU-make you can use an order-only prerequisite to force rules to be run in a particular order withou forcing them to run if they aren't needed by something else:
all: ...other targets... | config
        ...actions...

release_version: config version all

Now if you do a make all it will just rebuild the other targets before the |.  If config is needed for some other reason, it will wait for it to be done before running ...actions....
This may not be enough, as those other targets may run before config.  If you need them to wait until after config, you need to add | config to their prerequisites as well.


text:
Q: Vb.net tcplistener as a service I have written a code that works as a ftp windows service in vb.net and when a client request to connect it through my local address in same computer it works but when the request is from a camera to ftp picture to it with its own ip address it doesn't work.
In advance, I would appreciate it if you answer me.