text:
Q: IndexWriter deleteDocuments function is not working public void index(IndexItem indexItem) throws IOException {
    writer.deleteDocuments(new Term(IndexItem.ID,indexItem.getId().toString()));
    Document doc = new Document();
    // doc.add(new LongField(IndexItem.ID, indexItem.getId(), Field.Store.YES));
    doc.add(new TextField(IndexItem.CONTENT, indexItem.getContent(), Field.Store.NO));
    doc.add(new StringField(IndexItem.PATH, indexItem.getPath(), Field.Store.YES));

    // add the document to the index
    writer.addDocument(doc, analyzer);

    writer.updateDocument(new Term(IndexItem.CONTENT, indexItem.getContent().toString()), doc);
    System.out.println(indexItem.getTitle());
    writer.close();
}

Here Writer.deleteDocuments is not working. Thus each time I index a file, it doest not deletes already existing file then create a new one rather it just makes a copy of it.
Is this anything have to do with work.lock file

A: You appear to have commented out the line that adds the IndexItem.ID field to the document.  If that field isn't added to the document, then the call to deleteDocuments won't find any matches on that field, and nothing will be deleted.


text:
Q: Sending Request via Postman works fine but not via angular client my Setup:
Web-API implemented in .Net Core 3.1.
Angular12 Frontend.
My API has an Endpoint that, when requested with the email address of user, searches in my Active Directory and returns the fullName of that user.
Then I want to display that name in a component in angular.
It works perfectly with Postman, I get the name of the user as text

As you can see there are no custom headers and no query params attached to that Get Request that I make.
So I thought I could implement the same in angular.
I added:
    getFullName() {
    this.http.get<string>('https://localhost:44316/api/ADInfo/maid.sabanovic@gws.ms').subscribe(Response => {
      this.fullName = Response;
      console.log(this.fullName);
    });
  }

And I get:

Also the FullName Variable is undefined
Are there big Differences when sending Requests via Postman and via Angular?
Do I need to add headers to my request?

A: In order to return Non-Json data, you need to pass {responseType: 'text'} in your request header.
getFullName() {
this.http.get<string>('https://localhost:44316/api/ADInfo/maid.sabanovic@gws.ms', {responseType: 'text'}).subscribe(Response => {
  this.fullName = Response;
  console.log(this.fullName);
});
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check Contraint Bypassing CATCH block in Distributed Transaction I have a MSSSQL stored procedure performing a distributed transaction that looks like this:
SET XACT_ABORT ON;
SET NOCOUNT ON;

BEGIN TRY
  BEGIN DISTRIBUTED TRANSACTION

  insert into LNKSRV.INST.dbo.zz (id, val) values (1, 'a');
  insert into LNKSRV.INST.dbo.zz (id, val) values (2, 'b');

  COMMIT TRANSACTION
END TRY
BEGIN CATCH
  if (XACT_STATE() <> 0)
  BEGIN
    ROLLBACK TRANSACTION;
  END
  print ERROR_MESSAGE();
  print ERROR_LINE();
  print ERROR_SEVERITY();

END CATCH

This works fine.
If I add this 3rd insert statement:
  insert into LNKSRV.INST.dbo.zz (id, val) values ('error', 'b');

...it fails correctly -- the transaction is rolled back on the remote server and control passes to the CATCH block and I get information about the error (can't convert 'error' to int).
But if I add this insert statement:
  insert into LNKSRV.INST.dbo.zz (id, val) values (-1, 'b');

..and I have a check contraint on the remote table requiring values > 0 in the id column, then things do not work as I expect.  The transaction DOES roll back, but control DOES NOT transfer to the catch block.  Instead, execution just dies and this is printed to the  output window:
The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction

Why?  I need to log these errors in the catch blog.

A: Since the distributed transaction coordinator is handling this, when the transaction fails on the distributed part of the transaction, the DTC sends a message in the form of an attention, which stops your code from executing, and which the TRY/CATCH cannot process.
SQL Server can detect on your end when you are trying to insert an incorrect data type into a table (even on a remote instance) but the constraint is processed on the linked server, which causes the attention to be sent to DTC and your TRY/CATCH to be ignored.
For more information see the first "Note" section in the "Using TRY...CATCH in Transact-SQL" section of SQL Server 2008 Books Online, located at:
http://msdn.microsoft.com/en-us/library/ms179296.aspx


text:
Q: sql (or postgres) how to set the date as single year and month? I am compiling data of multiple years but I only need time not date and year. How can I set the year and date data into a single year and a single date so that I can use the time information as accumulative data?
2020-01-01 + time value.
Thanks!!!!

A: The information you provided is a little light. Still with certain assumptions:
create table ts_sum (ts_fld timestamptz);

insert into ts_sum values ('2020-04-14 08:15:32'), ('2021-09-27 18:45:01'), ('2022-01-09 20:21:05');

select sum(to_char(ts_fld, 'HH24:MI:SS')::interval) from ts_sum;
   sum
----------
 47:21:38

Needs to be tested with your data. The procedure is extract the time portion out of the timestamp using to_char then cast that to an interval and then sum the time intervals.


text:
Q: AngularJS: jQuery functions in jqLite I just want to ask for some help with converting the following code from jQuery to jqLite (angular jQuery):
$(window).on("load", function() {
    setTimeout(function(){
          #some funcs
    }, 100)
});

Thanks in advance.

A: Use this:
angular.element(document).ready(function () {

    // your code here

});

A: The answer to that question depends on the context and use case and how it relates to the AngularJS framework and the phases of the app.
To start something in the AngularJS run phase:
app.run(function($timeout) {
    $timeout(function() {
        //Startup code
    },100);
});

To start something in an AngularJS service:
app.service("something", function($timeout) {
    $timeout(function() {
        //Startup code
    },100);
});

Of course the $timeout may not be necessary.
Or to start third-party code before bootstrapping AngularJS:
angular.element(function() {
    //Third-party startup code
    angular.bootstrap(document,['myApp']);
});

The choice really depends on the context and how the third-party code interacts with the AngularJS framework.


text:
Q: Errors with BigQuery Sink Connector Configuration I am trying to ingest data from MySQL to BigQuery. I am using Debezium components running on Docker for this purpose.
Anytime I try to deploy the BigQuery sink connector to Kafka connect, I am getting this error:
{"error_code":400,"message":"Connector configuration is invalid and contains the following 2 error(s):\nFailed to construct GCS client: Failed to access JSON key file\nAn unexpected error occurred while validating credentials for BigQuery: Failed to access JSON key file\nYou can also find the above list of errors at the endpoint `/connector-plugins/{connectorType}/config/validate`"}

It shows it's an issue with the service account key (trying to locate it)
I granted the service account BigQuery Admin and Editor permissions, but the error persists.
This is my BigQuery connector configuration file:
{
    "name": "kcbq-connect1",
    "config": {
      "connector.class": "com.wepay.kafka.connect.bigquery.BigQuerySinkConnector",
      "tasks.max" : "1",
      "topics" : "kcbq-quickstart1",
      "sanitizeTopics" : "true",
      "autoCreateTables" : "true",
      "autoUpdateSchemas" : "true",
      "schemaRetriever" : "com.wepay.kafka.connect.bigquery.retrieve.IdentitySchemaRetriever",
      "schemaRegistryLocation":"http://localhost:8081",
      "bufferSize": "100000",
      "maxWriteSize":"10000",
      "tableWriteWait": "1000",
      "project" : "dummy-production-overview",
      "defaultDataset" : "debeziumtest",
      "keyfile" : "/Users/Oladayo/Desktop/Debezium-Learning/key.json"
    }

Can anyone help?
Thank you.

A: I needed to mount the service account key in my local directory to the Kafka connect container. That was how I was able to solve the issue. Thank you :)


text:
Q: How to execute an update via SQLQuery in Hibernate I need to update a joined sub-class. Since Hibernate doesn't allow to update joined sub-classes in hql or named-query I want to do it via SQL. I also can't use a sql named-query because updates via named-query are not supported in Hibernate.
So I decided to use a SQLQuery. But Hibernate complaints about not calling addScalar():

org.hibernate.QueryException: addEntity() or addScalar() must be called on a sql query before executing the query.

Are updates returning the number of rows affected and how is named that column?
Are there any other ways to do an update on a joined sub-class in hibernate?
Here is a brief example of what i'm trying to do:
<hibernate-mapping>
        <class name="example.NiceClass" table="NICE_CLASS">
  <meta attribute="class-code"></meta>
  <id name="id" type="java.lang.Long">
   <column name="NICE_CLASS_ID" precision="8" />
   <generator class="sequence">
    <param name="sequence">NICE_CLASS_SEQ</param>
   </generator>
  </id>
    </class>
</hibernate-mapping>
<hibernate-mapping package="example">
    <joined-subclass name="SubJoinedClass" table="SUB_JOINED_CLASS"
     extends="NiceClass">
        <key column="NICE_CLASS_ID" foreign-key="NICE_JOINED_ID_FK"/>
  <property name="name" type="string" not-null="false">
   <column name="NAME" >
    <comment>name</comment>
   </column>
  </property>
         </joined-subclass>
</hibernate-mapping>

Thanks in advance!
So I want to do a:
update SubJoinedClass set name = 'newName'

A: How do you execute the update query ?  What method do you call to execute it ? Do you call 'ExecuteUpdate' ?
And why do you think that you cannot execute an update query on a subclass using HQL ? AFAIK, it is possible.


text:
Q: Disable screen shut off for specific software I have a PC with windows 10 and use it for multiple purposes. One of them is monitoring a finances software — which doesn't need my input most of the time.
I know there's a way to stop my screen from turning off after X minutes, but I want this feature to work when I'm not using this specific software.
I want the screen to turn off normally when my PC is idle, EXCEPT when I'm using this software.
Is there a way to do it? Thanks.

A: Windows 10 64-bit.
Change power settings, open program, restore power settings:
How to write a one line Windows shortcut, or a cmd batch file to change your power settings (display timeout, sleep timeout, hard disk timeout, ...), open any program, and restore your original power settings when you close the program.  Does not require log off or restart. Can be run w/o admin privileges.
Power timeouts are between 1 minute and 9999999 minutes.
The four most common AC/DC power settings and their default Windows 10 timeouts:

*

*monitor-timeout-ac 10 monitor-timeout-dc 10

*disk-timeout-ac 20 disk-timeout-dc 20

*standby-timeout-ac 30 standby-timeout-dc 30

*hibernate-timeout-ac 30 hibernate-timeout-dc 30
I like to start shortcuts like this minimized. See pic at bottom. Change your path to your program. Do not start your program like this:
start "" "C:\Program Files\Finance Software\FinanceSoftware.exe.lnk"
One line shortcut for a desktop. Change monitor timeout to 60 minutes, open program, and restore monitor timeout to 10 minutes after program closes:
C:\Windows\System32\cmd.exe /c POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 60 &"C:\Program Files\Finance Software\FinanceSoftware.exe" &POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 10

One line shortcut for a laptop both AC and DC:
C:\Windows\System32\cmd.exe /c POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 60 &POWERCFG /CHANGE/MONITOR-TIMEOUT-DC 60 &"C:\Program Files\Finance Software\FinanceSoftware.exe" &POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 10 &POWERCFG /CHANGE /MONITOR-TIMEOUT-DC 10

If you want a batch file:
On a desktop:
@title Change power settings, open program, restore power settings
@echo off
setlocal enableextensions
rem change timeout from 1 - 9999999 minutes
POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 60
rem do not use:
rem start "" "C:\Program Files\Finance Software\FinanceSoftware.exe.lnk"
"C:\Program Files\Finance Software\FinanceSoftware.exe"
POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 10
exit /b

On a laptop both AC and DC:
@title Change power settings, open program, restore power settings
@echo off
setlocal enableextensions
rem change timeout from 1 - 9999999 minutes
POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 60
POWERCFG /CHANGE/MONITOR-TIMEOUT-DC 60
rem do not use:
rem start "" "C:\Program Files\Finance Software\FinanceSoftware.exe.lnk"
"C:\Program Files\Finance Software\FinanceSoftware.exe"
POWERCFG /CHANGE /MONITOR-TIMEOUT-AC 10
POWERCFG /CHANGE /MONITOR-TIMEOUT-DC 10
exit /b

How to change Windows 10 power settings from the command line
Powercfg examples
Shortcut to Power Control Panel:
C:\Windows\System32\control.exe powercfg.cpl,,23

For more info from cmd:
powercfg /change /?

Run minimized:

How to customize your power settings for any program you want to run with a windows shortcut or a cmd batch file.
Disable screen shut off for specific software. Enable screen shut off for specific software. Disable sleep for specific software. Enable sleep for specific software. Disable disk sleep for specific software.  Enable disk sleep for specific software.


text:
Q: Access 2010 SQL Update Query I need to update every row in one table, with the help with two subqueries...
UPDATE MyTable
SET MyTable.ColumnToUpdate =
((SELECT 10000 / DCount("ID","MyTable")) *  DCount("ID","MyTable","ID<="& MyTable.ID))

But this doesn't work, access complanis about an error in the first subquery...
How can i do this?
Thanks

A: You don't need the SELECT statement in the first piece.  Try this:
UPDATE MyTable
SET MyTable.ColumnToUpdate =
((10000 / DCount("ID","MyTable")) *  DCount("ID","MyTable","ID<="& MyTable.ID))


text:
Q: Wordpress, setup_postdata() not doing its job My posts get ordered by date which is picked by an advanced custom field datepicker. I want to use the regular Wordpress function references [the_title(), etc …] and the post related custom field's.
Right now the output of every loop is the the same. I read setup_postdata() can solve this issue and enable the use of the regular function references. I tried to apply it, but the output keeps being always the same. Thanks
<?php

global $posts;

$posts = get_posts(array(
    'post_type' => 'post',
    'meta_key'  => 'release_date',
    'orderby'   => 'meta_value_num',
    'order'     => 'DESC'
));

$group_posts = array();

if( $posts ) {

    foreach( $posts as $post ) {

        $date = get_field('release_date', $post->ID, false);

        $date = new DateTime($date);

        $year = $date->format('Y');
        $month = $date->format('F');

        $group_posts[$year][$month][] = array($post, $date);

    }

}

foreach ($group_posts as $yearKey => $years) {

    foreach ($years as $monthKey => $months) {

        echo '
' . $monthKey . ' ' . $yearKey . '
';

        foreach ($months as $postKey => $posts) {

            setup_postdata($posts); ?>

                <?php the_title();?>
                <?php the_permalink();?>

                <?php the_field('blabla')?>

        <?php
        }

    }

} wp_reset_postdata();

?>

A: You just need to add a line $post = $current_post; just before calling setup_postdata( $post ). See my example below to have a clear idea:
$posts = get_posts(array(.......));

// Call global $post variable
global $post;

// Loop through sorted posts and display using template tags
foreach( $posts as $current_post ) :

    //the below line is what you missed!
    $post = $current_post; // Set $post global variable to the current post object

    setup_postdata( $post ); // Set up "environment" for template tags

    // Use template tags normally
    the_title();
    the_post_thumbnail( 'featured-image-tiny' );
    the_excerpt();
endforeach;
wp_reset_postdata();

For details please see this comment posted in the WP-Codex;


text:
Q: Magento and Wordpress Joint. How do i edit a page manually or the CSS? I am having problems trying to figure out how exactly i can edit a simple page of the website. I didn't initially create it so i am given the task of trying to understand someones code. So the problem is... i am trying to change the simple font colour on the front home page, but i cannot even find the CSS file on magento or Wordpress so i'm kind of confused. I want to change the white font colour to black.
Do i just log in with FTP and edit the pages manually on there? Please give me some information on how i can go about editing any pages at all.

A:
Wordpress
Wordpress have /wp-content/themes/ for a directory which stores all instaled themes (downloaded or created by you). You can edit everything of a theme there. The default stylesheet file in wp's /wp-content/themes/[yourtheme]/style.css. Attention: this CSS file can import another from somewhere else.
Finding the style
You can find the ids and classes statements just positioning the mouse over the element that you want to discover what is influencing it, right button click and select Inspect Element if in Chrome or Mozilla. An add-on to help is Web Developer.
Possibly useful links: http://ithemes.com/tutorials/ ; http://mcbuzz.wordpress.com/wordpress-tutorials-complete-list/ ; http://themeshaper.com/2009/06/22/wordpress-themes-templates-tutorial/ ; http://line25.com/articles/15-tutorials-to-help-you-build-wordpress-themes
Web developer
Mozilla | Chrome
@edit Yes, you can edit via FPT or SSH connection ;P

A: In wordpress you should check in settings->reading what the front page is set to and css changes can be done in the theme folder wp-content/themes/theme_name/ and for magento the css is usually in /skin/frontend/package/theme/css. or somewhere close depending on the template.


text:
Q: prefix for product attribute valu i have this code in an observer.php :
<?php

class Moh3n_Attvaluecopier_Model_Observer
{

public function  copyAttribute($observer){

    if(!$this->_processFlag):

        $this->_processFlag=true;
        $_product = $observer->getProduct();
        $_productid = $_product->getId();
        $productModel = Mage::getModel('catalog/product');
        $loadCurrentProduct = $productModel->load($_productid);
        $loadCurrentProduct->setGeneralWeight(intval($loadCurrentProduct->getWeight()));
        $loadCurrentProduct->save();
        endif;}
    }

it copies the weight attribute value into general_weight attribute without decimals.
i want to add a value like (KG) to general_weight right after copied value.
i want general_weight to show this way: 1000 KG
how to do that?

A: Assuming you are saving it as a string, just do this:
$weight = intval($loadCurrentProduct->getWeight());
$gw = (string)$weight. " KG";
$loadCurrentProduct->setGeneralWeight($gw);

If you need to save it as an integer for comparison or something, you could add the KG when outputting the value in the template, or write a custom getter for general_weight in your model that gives you
return $value . " KG";


text:
Q: Fit image or print image I am not able to extend the image to the edges of the paper. How to extend the edges of the image to the edges of the paper?

A: First, go to the layers panel. Right click export, save as. Then in the window 'Save Raster Layer as...' select under extent 'current layer extent.' Read the dimensions.
Go to the composer to make a layout. Fill in the dimensions correctly in under 'item properties, extents'(tip: look a rulers). Now go in 'item properties, position and size.' Change the page size.
Somehow it worked for me.

A: Change the scale until your data fills the whole map-canvas.


text:
Q: An error was encountered when setting batch_size to 1 in sequence_to_sequence_implementation.ipynb(when batch_size > 1,it 's ok) reference:
https://github.com/udacity/deep-learning/blob/master/seq2seq/sequence_to_sequence_implementation.ipynb
setting:
encoding_embedding_size=decoding_embedding_size = 200
error info:
    Traceback (most recent call last):
    File "my_encoder_decoder.py", line 369, in
    main(sys.argv[1])
    File "my_encoder_decoder.py", line 346, in main
    my_qa.train()
    File "my_encoder_decoder.py", line 298, in train
    model.build_graph()
    File "D:\vmware\share\test\chat\seq2seqmodel.py", line 197, in build_graph
    self._decoding_layer()
    File "D:\vmware\share\test\chat\seq2seqmodel.py", line 130, in _decoding_layer
    inference_decoder_output = tf.contrib.seq2seq.dynamic_decode(inference_decoder,impute_finished=False,maximum_iterations=self.max_target_sequence_length)[0]
    File "d:\Program Files\Anaconda3\lib\site-packages\tensorflow\contrib\seq2seq\python\ops\decoder.py", line 286, in dynamic_decode
    swap_memory=swap_memory)
    File "d:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2770, in while_loop
    result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
    File "d:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2599, in BuildLoop
    pred, body, original_loop_vars, loop_vars, shape_invariants)
    File "d:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 2580, in _BuildLoop
    _EnforceShapeInvariant(m_var, n_var)
    File "d:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\ops\control_flow_ops.py", line 575, in _EnforceShapeInvariant
    % (merge_var.name, m_shape, n_shape))
    ValueError: The shape for decode_1/decoder/while/Merge_5:0 is not an invariant for the loop. It enters the loop with shape (1, 200), but has shape (?, 200) after one iteration. Provide shape invariants using either the shape_invariants argument of tf.while_loop or set_shape() on the loop variables.
Does anyone know how to solve it?


text:
Q: how to compare string word to chat guess? I am currently working on a program (hangman) and am having problems comparing the user input (char) to the word to be guessed (string) to determine if the guessed letter is in the word or not.
#include <iostream>
#include <fstream>  // ifstream and ofstream
#include <iomanip>  // input/output manipulation
#include <cctype>   // toupper() function
#include <cstring>
#include <string>   // strings
using namespace std;
#include "MyFuncts.h" // programmer defined includes

//ASCII ART FROM: http://ascii.co.uk/art/hangman by Manus O'Donnell

int main()
{
    ifstream inFile;  // used to read from the file
    string stage0;
    string stage1;
    string stage2;
    string stage3;
    string stage4;
    string stage5;
    string stage6;
    string word; // convert this to array down the road
    char guess;
    int numWrong = 0;
    bool found = true;

    //STAGE0
    stage0 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||\n| |/\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n\"\"\"\"\"\"\"\"\"\"|_        |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";
    //STAGE1
    stage1 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||.-''.\n| |/         |/  _  \\\n| |          ||  `/,|\n| |          (\\\\`_.'\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n| |\n\"\"\"\"\"\"\"\"\"\"|_        |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";
    //STAGE2
    stage2 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||.-''.\n| |/         |/  _  \\\n| |          ||  `/,|\n| |          (\\\\`_.'\n| |         .-`--'.\n| |        /Y . . Y\\\n| |          |   |\n| |          | . |\n| |          |   |\n| |\n| |\n| |\n| |\n| |\n\"\"\"\"\"\"\"\"\"\"|_        |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";
    //STAGE3
    stage3 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||.-''.\n| |/         |/  _  \\\n| |          ||  `/,|\n| |          (\\\\`_.'\n| |         .-`--'.\n| |        /Y . . Y\\\n| |       // |   |\n| |      //  | . |\n| |     ')   |   |\n| |\n| |\n| |\n| |\n| |\n\"\"\"\"\"\"\"\"\"\"|_        |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";
    //STAGE4
    stage4 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||.-''.\n| |/         |/  _  \\\n| |          ||  `/,|\n| |          (\\\\`_.'\n| |         .-`--'.\n| |        /Y . . Y\\\n| |       // |   | \\\\\n| |      //  | . |  \\\\\n| |     ')   |   |   (`\n| |\n| |\n| |\n| |\n| |\n\"\"\"\"\"\"\"\"\"\"|_        |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";
    //STAGE5
    stage5 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||.-''.\n| |/         |/  _  \\\n| |          ||  `/,|\n| |          (\\\\`_.'\n| |         .-`--'.\n| |        /Y . . Y\\\n| |       // |   | \\\\\n| |      //  | . |  \\\\\n| |     ')   |   |   (`\n| |          ||'\n| |          ||\n| |          ||\n| |          ||\n| |         / |\n\"\"\"\"\"\"\"\"\"\"|_`-'     |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";
    //STAGE6 - GAME OVER
    stage6 = " ___________.._______\n| .__________))______|\n| | / /      ||\n| |/ /       ||\n| | /        ||.-''.\n| |/         |/  _  \\\n| |          ||  `/,|\n| |          (\\\\`_.'\n| |         .-`--'.\n| |        /Y . . Y\\\n| |       // |   | \\\\\n| |      //  | . |  \\\\\n| |     ')   |   |   (`\n| |          ||'||\n| |          || ||\n| |          || ||\n| |          || ||\n| |         / | | \\\n\"\"\"\"\"\"\"\"\"\"|_`-' `-' |\"\"\"|\n|\"|\"\"\"\"\"\"\"\ \       '\"|\"|\n| |        \\ \\        | |\n: :         \\ \\       : :\n. .          `'       . .\n\n\n";

    inFile.open("hangman.dat");
    if (!inFile)
    {
        cout << "Error opening file for reading\n";
        system("pause");
        return 1;
    }// end if
    inFile >> word; // convert these into an array as well
    while (!inFile.fail()) // .fail is better than .eof as it catches more issues
    {
        cout << "Word: " << word << endl;;
        inFile >> word;
    }
    inFile.close();

    word = caseChanger(word, true);

    //INPUT
    cout << "Word to Guess: " << word << endl << endl;

    //PROCESS & OUTPUT
    while (numWrong <= 6)
    {
        if (numWrong == 0)
            cout << stage0 << endl;
        else if (numWrong == 1)
            cout << stage1 << endl;
        else if (numWrong == 2)
            cout << stage2 << endl;
        else if (numWrong == 3)
            cout << stage3 << endl;
        else if (numWrong == 4)
            cout << stage4 << endl;
        else if (numWrong == 5)
            cout << stage5 << endl;
        else
            cout << stage6 << endl;

        cout << "Please enter a letter to guess: ";
        cin >> guess;
        guess = toupper(guess);
        cout << "You entered: " << guess << endl;

        for(int i = 0; i < word.length(); i++)
        {
            if(word[i] == guess)
                found = true;
            else
                found = false;
        }

        if (found)
        {
            cout << guess << " is in the word to guess." << endl;
        }
        else
        {
            cout << guess << " is NOT in the word to guess." << endl;
            numWrong = numWrong++;
        }
    }

    cout << "\n\n";
    system("pause");
    return 0;
}

For some reason, when I enter a letter that is part of the word, this still says it is not, and increments the number of incorrect guesses (numWrong).
Could use  afresh set of eyes, as I have no clue why this is not currently working.
Thanks!

A: The problem is in your loop to determine if the letter is correct. If it finds the correct letter, the loop doesn't end, and continues going through all the letters, which changes it back to false.
found = false; //Move this here to set it as false default before the loop starts
for(int i = 0; i < word.length(); i++)
    {
        if(word[i] == guess)
        {
            found = true;
            break; //Add this here to exit the loop if letter is found
        }
    }

A: Just make found = false once you done with your operation when it is true.
if (found)
{
    cout << guess << " is in the word to guess." << endl;
    found = false; // Get it reset for the next loop.
}


text:
Q: For loop to vector formation for performance in Matlab I have a some trouble with handling for loop to vector formation in Matlab.
That's image processing part.(about controling the light)
My orignal soruce code is bellow.
for i=1:1:p1
    for j=1:q1
        if A(i,j) <=25
            A(i,j) =0;
        end
    end
end

How can I change this code to vector for performance?
I already checked this url(https://mathworks.com/help/matlab/matlab_prog/vectorization.html).

A: You need to use logical indexing:
I = A<=25;

is a logical array that is true where A is smaller or equal to 25. You can use this array to index into A:
A(I) = 0;

sets the elements of A to 0 where I is true.
This can all be written as a single statement:
A(A<=25) = 0;

[I'm sure this has been asked before here, but I can't find any duplicates.]


text:
Q: PHP not sending mail I will admit I don't know much about PHP. I found this script to send emails and it works just fine for one of my other pages but now it isn't working and I don't know why. The only thing I changed was that I added the 'if' statements in the middle of the script to handle the emails so the emails were kept private. Anyone have any ideas?
<?php
/*if(!isset($_GET['submit']))
{
    //This page should not be accessed directly. Need to submit the form.
    echo "error; you need to submit the form!";
}*/ //This error seems to just get in the way. I am cutting it out.
$mailTo = $_GET['to'];
$subject = $_GET['subject'];
$name = $_GET['name'];
$visitor_email = $_GET['email'];
$message = $_GET['message'];

//Validate first
if(empty($name)||empty($visitor_email))
{
    echo "Name and email are mandatory!";
    exit;
}

if(IsInjected($visitor_email))
{
    echo "Bad email value!";
    exit;
}

//If statements to change value from html to actual email addresses
switch($mailTo) {
    case "ED":      $mailTo = "example@example.com";
                    break;
    case "AS":      $mailTo = "example@example.org";
                    break;
    case "OM":      $mailTo = "example@example.org";
                    break;
    case "VC":      $mailTo = "example@example.org";
                    break;
    case "Pres":    $mailTo = "example@example.com";
                    break;
    case "VP":      $mailTo = "example@example.net";
                    break;
    case "Sec":     $mailTo = "example@example.com";
                    break;
    case "Treas":   $mailTo = "example@example.com";
                    break;
    case "Dir1":    $mailTo = "example@example.com";
                    break;
    case "Dir2":    $mailTo = "example@example.com";
                    break;
    case "Dir3":    $mailTo = "example@example.net";
                    break;
    case "Dir4":    $mailTo = "example@example.com";
                    break;
    case "Dir5":    $mailTo = "example@example.com";
                    break;
    case "Dir6":    $mailTo = "example@example.gov";
                    break;
    case "Dir7":    $mailTo = "example@example.com";
                    break;
    case "Dir8":    $mailTo = "example@example.com";
                    break;
    case "Dir9":    $mailTo = "example@example.com";
                    break;
}

$email_from = $visitor_email;//<== update the email address
$email_subject = $subject;
if($subject==="Please sign me up for the example Newsletter")
{
    $email_body = "$name has requested to be subscribed to the example
Newsletter\n";
    $email_body .= "$name's email address is $visitor_email\n";
}
else
{
    $email_body = "*** The following message is from the user ***\n";
    $email_body = $message;
}
if($message!=="")
    $email_body .= "They have also added a custom message:\n $message";

$to = $mailTo;//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
if(mail($to,$email_subject,$email_body,$headers))
    echo "Mail submitted successfully";
else
    echo "Mail not sent";
//done. redirect to thank-you page.
//header('Location: thank-you.html');

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}

?>

In my console, I don't get any errors, I'm using AJAX and I don't get any errors, the return value is always that it was submitted successfully, and the query string that is being submitted is valid. I've narrowed it down to where it has to be something in the PHP that is messing up and making the email invalid.
Here is the JS for the AJAX function. My validation function calls the AJAX which then sends it over to the PHP. All the JS has been debugged and is working.
function ajaxFunction(caller)
{
    'use strict';
    console.log("1. *** BEGINNING AJAX FUNCTION ***");
    var ajaxRequest;

    try{
        // Real browsers
        ajaxRequest = new XMLHttpRequest();
    } catch(e) {
        // IE browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                // Something went wrong
                alert("Your browser broke");
                return false;
            }
        }
    }
    // Function that will recieve data sent from the server
    ajaxRequest.onreadystatechange = function() {
        console.log("2. The current ready state is: " + ajaxRequest.readyState);
        if(ajaxRequest.readyState === 4){
            var errorP = document.getElementById("errorP");
            console.log("Response Text is " + ajaxRequest.responseText);
            errorP.innerHTML = ajaxRequest.responseText;
        }
    }
    // Create the date object and send it to the server
    var to;
    var subject;
    var select = document.getElementById("select");
    var subj = document.getElementById("subject");
    var name = document.getElementById("name");
    var nameVal = name.value;
    var email = document.getElementById("email");
    var emailVal = email.value;
    var message = document.getElementById("message");
    var messageVal = message.value;
    if(caller==="newsletter")
        {
            to = "newsletter@al-van.org";
            subject = "Please sign me up for the Al-Van Newsletter";
        }
    else if(caller==="contact")
        {
            to = select.value;
            subject = subj.value;
        }
    var queryString = "?name=" + nameVal + "&email=" + emailVal + "&message=" + messageVal + "&to=" + to + "&subject=" + subject;
    console.log("6. The query string is: " + queryString);
    ajaxRequest.open("GET", "form-to-email.php" + queryString, true);
    ajaxRequest.send(null);
}

A: After pulling research from many different sources, I seem to have found the issue. It seems that BlueHost uses filters and blocks that prevent people using their servers for spamming or phishing. This means that the $from field in the PHP script must be a valid email on the server in order for it to send. It seems when I was using a different $from field the emails would either take hours to go through, or not go through at all. I did not need to add SMTP credentials or install any other packages to get this done. Thank you for your help folks, many of your suggestions and ideas were instrumental in helping me arrive at my own answer.


text:
Q: Wordpress pagination links with query args I have set some arguments to the paginate_links function and managed to do pagination with query args instead of path, but on the first page it does not rewrite my arguments, it just keeps the current page: if i'm on page 3 the first page url will be ?page=3 instead of empty. I need to clear it or set it as ?page=1. I used the following code
global $wp_query;
$current = $wp_query->query_vars['page'] > 1 ? $wp_query->query_vars['page'] : 1;
echo paginate_links(
    [
        'base' => '%_%',
        'format' => '?page=%#%',
        'total' => $wp_query->max_num_pages,
        'current' => $current,
        'show_all' => true,
        'type' => 'list',
    ]
);

A: Instead of 'base' => '%_%' Just change to below line. This will solve your problem.
'base' => get_pagenum_link(1) . '%_%',


text:
Q: validating name and value in array I have an array that looks like this:
$team = array("tom"=>"35",
"beck"=>"18",
"Gerald"=>"15");

I also am parsing data from a loop which gives me the following strings $name and $num

*

*The $name string returns a team members name from a database

*The $num string returns a team members number from a database

I would like to build a php if statement that will do the following:

*

*Check if the $name and $num exists in the array $team

*Check if the $num matches the assigned number for the name in the array

As an example, lets assume the following:

*

*$name = "tom";

*$num = "25";

I have this so far:
if (in_array($num, $team)) {
// do something
}

What's missing is for it to check the second condition mentioned above.
Following the above example, it should fail, since the $num value is "25", whereas it is "35" in the array.

A: You can try to check the $name key with value of $num -
$team = array("tom"=>"35",
"beck"=>"18",
"Gerald"=>"15");

if(isset($team[$name]) && $team[$name] == $num) {
     // Your code
}

in_array will check for the value's existence in the array without considering the key.


text:
Q: h5py: convert numpy data to native python types I am saving some data to HDF5 file via h5py. They are mixed-types data, some are proper numpy arrays, many are scalars or strings. Scalars and strings get "encoded" to numpy arrays by h5py automatically (that is very nice), but I would like to do the reverse now: when reading those data, get it converted to native python type, instead of seeing scalars as 0d shapes, strings as <HDF5 dataset "plots": shape (), type "|S207"> and such.
Is there an easy way to achieve that, without me having to check for array dtype manually?
It is fine that an extra object will be created for every conversion.

A: Not sure if it would make sense for your use-case, but you might think about storing single scalars or strings as attributes:
http://www.h5py.org/docs/intro/quick.html#attributes

A: Would it make sense for you to use h5pom? This might be overkill for you, but it should do what you describe, although you'd probably have to work with the whole ORM more than you'd wish (Caveat:I've played around with it but never used it in anger).


text:
Q: Expo pop-up notifications (floating notifications) don't work on android Notifications come but are displayed only in the status bar.
I use "expo": "~44.0.0" and "expo-notifications": "~0.14.0".
The code is completely copied from the documentation.

import * as app from 'app.json';
import * as Device from 'expo-device';
import { Subscription } from 'expo-modules-core';
import * as Notifications from 'expo-notifications';
import React, { useCallback, useEffect, useRef, useState } from 'react';

import { ScreenView } from '@shared/components/screenView';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

export const Login: React.FC = () => {
  const notificationListener = useRef<unknown>();
  const responseListener = useRef<unknown>();

  const [token, setToken] = useState('');
  const [notification, setNotification] = useState<Notifications.Notification>();

  useEffect(() => {
    void registerForPushNotificationsAsync().then((token) => setToken(token ?? ''));
  }, []);

  useEffect(() => {
    notificationListener.current = Notifications.addNotificationReceivedListener((notification) => {
      setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener((response) => {
      console.log(response);
    });

  return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return (
    <ScreenView alignItems="center">
    </ScreenView>
  );
};

async function registerForPushNotificationsAsync() {
  let token;

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
    });
  }

  return token;
}

I also added to app.json.
"useNextNotificationsApi": true

Previously with the "expo" versions: "~40.0.0" and "expo-notifications": "~0.8.2"  it worked
Status bar
Push notification

A: you need to implement in-app notification if the app is opened.
Check it out: https://docs.expo.dev/versions/latest/sdk/notifications/


text:
Q: Ionic 3: BackgroundLocation updates are too rare I'm currently facing a problem that is not so nice. I already created an issue but no response. I need every location change to update the camera center position. But this doesn't happen. The refresh is not definable with time. It's just very rare for my needs. Android and iOS is the same. The log is called every minute or something like that.
Also I tried the console log outside the ngZone but it's the same.
This is what my configuration code looks like:
let config = {
  desiredAccuracy: 0,
  stationaryRadius: 1,
  distanceFilter: 0,
  debug: true,
  interval: 2000,
  pauseLocationUpdates: false,
  activityType: "AutomotiveNavigation"
};

this.backgroundGeolocation.configure(config).subscribe((location) => {
  // Run update inside of Angular's zone
  this.zone.run(() => {
    if(this.map) {
      this.map.getMyLocation().then( (userLocation: MyLocation) => {
        console.log("INSIDE ZONE Google Maps Location \n LAT: " + userLocation.latLng.lat + "\nLNG: " + userLocation.latLng.lng);
        this.userLocation = userLocation.latLng;
        this.speed = userLocation.speed;
        this.bearing = userLocation.bearing;
        this.altitude = location.altitude;

        this.cameraFollow();
        this.notify(this.nearestReports[0]);
      }).catch( error => {
        alert("Background - NO GPS FOUND: " + error);
      });
    }
  });
});

// Turn ON the background-geolocation system.
this.backgroundGeolocation.start();

A: Consider using another Ionic Native plugin called Geolocation.
There is a very handy watchPosition() function in there that looks like what you are looking for. Here's an example:
let options = {
  enableHighAccuracy: true,
  timeout: Infinity, // don't return response until new ping is available from OS, to save battery
  maximumAge: 0
};

const subscription = this.geolocation.watchPosition(options)
  .filter((p) => p.coords !== undefined) //Filter Out Errors
  .subscribe(position => {
      console.log(position.coords.longitude + ' ' + position.coords.latitude);
});

Don't forget to stop the subscription when not needed in order to save battery:
subscription.unsubscribe();


text: Q: Why is log(p(x)) important in mathematics? I read many papers for Bayesian Learning, and I can see that in every probabilistic formula they use a logarithm of a distribution p(x) (i.e. log(p(x))) or the negative logarithm of p(x) (i.e. -log((p(x))). Why they do not just use the distribution p(x) ?


text:
Q: How do I show P(Z = z) if Z = X+Y, both random discrete variables. If Z = X+Y, and both are random discrete variables.
How do I show

A: This needs just two steps:

*

*split up into cases according to the possible values of $X$. (Whenever the goal formula involves a sum indexed by the values of $X$, you can guess this is probably involved.)

*then notice that the condition "$X = x$ and $Z = x$" is equivalent to "$X = x$ and $Y = z-x$".
$$
\begin{align*}
P(Z=z) & = \sum_x P(X=x\ \text{and}\ Z=z) \\
&= \sum_x P(X = x\ \text{and}\ Y = z-x)
\end{align*}
$$


text:
Q: Addition of spin angular momentum for massless particles How do I add the spin angular momentum of massless particles, like photons, where only the transverse polarizations are allowed?
If all three polarizations were allowed, this would be an easy exercise: you'd get $S=0,1,2$ states.  But some of these states clearly aren't allowed for purely transverse photons: For example, with two photons moving in the same direction as quantization axis, the state
$$\big|S=2,M=1\big\rangle=\frac{1}{\sqrt{2}}\big(|m_1=1,m_2=0\rangle+|m_1=0,m_2=1\rangle)$$
contains the $m=0$ state which is not allowed.
Edit:  In the spectroscopic notation, which states are allowed?

A: The situation is simpler than you think. Basically you don't need to do Clebsch-Gordan at all!
The massless irreducible representations of the (proper orthochronous) Lorentz group are $1$-dimensional, labelled by their helicity $h$. Since $h = \pm 1$ are related by parity we group them as the $\pm$ helicities of the photon.
To compute the helicity of multiparticle states you must take a tensor product of the possible helicity configurations. Then you should decompose these into irreducible representations, according to the Clebsch-Gordan procedure.
But in this case, the $+1$ and $-1$ irreps are $1$-dimensional. Therefore their tensor product is automatically an irrep! So there's no Clebsch-Gordan decomposition to do.
Thus we are left with four possibilities, namely
$$1 \otimes 1, \ 1\otimes -1,\ -1 \otimes 1,\  -1 \otimes -1$$
Considering the action of the helicity operator in each representation, you can verify that these have helicity $2,0,0,-2$ respectively.
Combining the $1\otimes -1$ and $-1\otimes 1$ representations symmetrically and antisymmetrically, you reproduce the two $0$ helicity states of Rob's answer.
Let me know if you want some more explicit detail of the calculation!

A: Here's the algorithm for finding Clebsch-Gordan coefficients:

*

*Start with a maximally aligned state like
$\big|S,M = 2,2\big> = \big| m_1,m_2 = 1,1\big>$

*Operate repeatedly with the lowering operator to generate the remaining states with the same $S$, such as
$$\big|S,M=2,1\big> = \frac{\left|1,0\right\rangle + \left|0,1\right>}{\sqrt2}$$

*Start the train for the next $S$ down by finding the remaining orthogonal combination of individual states.  Here that'd be
$$\big|S,M=1,1\big> = \frac{\left|1,0\right\rangle - \left|0,1\right>}{\sqrt2}$$

*Continue until exhausted.
The question is how to apply this algorithm to a system where one of the lowered states, $\left|0\right\rangle$, is not physical.
One possibility, given by KoObO, is that you use the standard Clebsch-Gordan coefficients but set the coefficients of all the $\left|0\right\rangle$ terms to zero, and renormalize.  However, without $\left|0\right\rangle$ there are not enough degrees of freedom to have distinct states for the $m=0$ projections of $S=0,1,2$.  In fact, without $\left|0\right\rangle$ there are only four two-photon states, three symmetric and one antisymmetric.
This makes me suspect that the four states with $|M|=1$ are unphysical, since they all require some $\left|0\right\rangle$ in every term.
For the states with $M=0$, we're now in a pickle.  For the usual spin-2 algebra, there are two symmetric states with $S=0$ and $S=2$, and one antisymmetric state with $S=1$.  But without the $\left|0\right\rangle$ projection for each photon there is nothing to distinguish between $S=0$ and $S=2$.  Is the symmetric, $M=0$ state a mixture of $S=0,2$?  That wouldn't make any sense: you can distinguish between states of different total $S$ by rotating your coordinate system.  We have already constructed states with $S=2,M=2$.  Maybe $S=0$ is forbidden?  That would be surprising.
The other way out of this pickle is to assert that the algebra of angular momentum addition is based on the multiplicity of of the states involved, rather than the total spins.  In that case the two-state photon should have the same Clebsch-Gordan coefficients as the two-state electron, with a factor of two difference in the total spin everywhere, and there will be no two-photon state with $S=1$.  This possibility seems more concordant with a scenario where there are no allowed states with $M=1$.
I don't know of a theoretical way to distinguish between these, so I turn to experimental data.  I know that two-photon wavefunctions must be even under exchange.  For now, assume that two-photon processes prefer to carry zero orbital angular momentum. Electromagnetic decays conserve parity, so negative-parity initial states should decay to photon pairs with antisymmetric spins, while positive parity initial states should decay to photon pairs with symmetric spins.
First let's look in the PDG meson table:

*

*The $\pi^0$, $\eta$, and $\eta'$, with $J^P=0^-$, decay predominately to two photons.  This suggests that the antisymmetric spin state carries no angular momentum.

*For the $f_0(600)$, with $J^P=0^+$, the two-photon decay is listed as "seen".  That would be consistent with a symmetric spin state with zero angular momentum.  However I note that the decay width $\Gamma$ for the $f_0$ is enormous, and there are people who believe that the $f_0$ is two-pion state and not a "real" particle.  I'll leave other very wide mesons and other mesons where the two-photon decay is described as "seen" without a branching ratio.

*For the $\rho$ and $\omega$ mesons, with $J^P=1^-$, there are no two-photon decays listed.  This is inconsistent with the existence of an antisymmetric two-photon state with $S=1$.

*The $b(1235)$ and $f_1(1285)$, with $J^P=1^+$, have no branching ratio for two photons.  This is inconsistent with the existence of a symmetric state with $S=1$.

*The $f_2(1270)$, with $J^P=2^+$, has a small but well-measured branching ratio to two photons, consistent with a symmetric two-photon wavefunction for $S=2$.

*In the strange sector, the $K^0$ ($J^P=0^-$) decays to two photons at least 1000 times more often than to three photons.
This list of decay modes is most consistent with a world where the two-photon spin wavefunction is symmetric for $S=2$, antisymmetric for $S=0$, and does not exist for $S=1$.
Let's leave the strongly-interacting world and look at positronium.
The positronium spin singlet may decay to two photons, suggesting that two photons may carry zero angular momentum.  The positronium spin triplet may decay only into three or five photons, suggesting that there is no way for two photons to carry unit spin.
Unfortunately for my argument here, both positronium states are even under parity, and the singlet is even under charge exchange as well (in order to be totally antisymmetric under exchange symmetry).  The symmetries involved then tell us that the photon wavefunction must be even under $C$, $P$, and therefore under exchange of spins.
We can weasel out of this conundrum if we relax our assumptions about orbital angular momentum.  If the positronium spin singlet decays to two photons with $L=2$, $S=2$, $\vec L+\vec S=\vec J=0$, we can still conserve $C$, $P$, angular momentum, and exchange symmetry, while still keeping good explanations for the symmetric and antisymmetric two-photon spin states.  The extra two units of $L$ might also serve as a handwavy reason why positronium decay is five orders of magnitude slower than the equivalent electromagnetic quarkonium decay in the $\pi^0$.
Based on this logic, I conclude that the photon is a two-state spin system with spin 1.  Pure photon states may combine antisymmetrically to make $S=0$, or symmetrically to make an $S=2$ triplet; I think that there is no pure two-photon spin state with $M=1$.  But I'd love to learn of a more authoritative source.

A: I think (but I'm not sure) that if you do it like if the photon has three physical polarization states then you get, as you said $S=0,1,2$. You can compute easily all of these states. But remember, you can express the states of the coupled basis in the uncoupled basis (via a Clebsch-Gordan decomposition). Then, you can delete the terms containing a non physical state (typically $\left|1,0\right>\times\left|1,m_2\right>$) and then you get all your physical states. Note that you will probably have to (re)normalize the states.


text:
Q: makefile with OS dependent compiler I have a set of C programs that are generally compiled using gcc in a makefile, but OSX Mavericks now uses clang.  What is a good way to test for existing compilers in a makefile and use the appropriate one?  Moreover, I would also like to use architecture-dependent optimization flags (e.g., for gcc on Linux, I would use -O3, but on OSX I would use -fast; for clang on OSX I would use -Ofast).
Kindest thanks,
Ryan

A: If you are compiling on MacOS X and Linux then you can put the following in your makefile:
UNAME := $(shell uname)

ifeq ($(UNAME), Darwin)
CFLAGS = -Ofast
endif

ifeq ($(UNAME), Linux)
CFLAGS = -O3
endif

# etc


text:
Q: How to delete image from sd card after sharing successfully I want to delete the image from sdcard after sharing the image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode)
{
case TAKE_IMAGE:
    try {
        if (resultCode == RESULT_OK) {

            // we need to update the gallery by starting MediaSanner
            // service.
            mScanner = new MediaScannerConnection(ProfilePicFromCamera.this,new MediaScannerConnection.MediaScannerConnectionClient()
            {
               public void onMediaScannerConnected() {
                   mScanner.scanFile(imageUri.getPath(),null /*mimeType*/);
            }

                public void onScanCompleted(String path, Uri uri) {
                    if (path.equals(imageUri.getPath())) {
                        mScanner.disconnect();
                        ProfilePicFromCamera.this.runOnUiThread(new Runnable() {
                                public void run() {
                                    updateUI();
                            }
                        });
                    }
                }
            });
            mScanner.connect();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    break;
case UPLOAD_IMAGES:
     if(requestCode==UPLOAD_IMAGES)
        {
            if(requestCode==UPLOAD_IMAGES && resultCode==Activity.RESULT_OK)
            {
                            if(file.exists())
                                file.delete();
                Toast.makeText(this, "Mail sent.", Toast.LENGTH_SHORT).show();
            }
            else if (requestCode==UPLOAD_IMAGES && resultCode==Activity.RESULT_CANCELED)
            {
                Toast.makeText(this, "Mail canceled.", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "Please try again.", Toast.LENGTH_SHORT).show();
            }
        }
    break;

}
}


text:
Q: Serilog middleware not working properly with error handling I create middleware about logging the errors with Serilog. And I love it because it's simple and maintainable. Here it is:
public class LogContextMiddleware
{
    private readonly RequestDelegate next;

    public LogContextMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public Task Invoke(HttpContext context)
    {
        LogContext.PushProperty("UserName", context.User.Identity.Name);
        LogContext.PushProperty("ApiPath", context.Request.Path);
        return next(context);
    }
}

Then I thought that I can put an error handling mechanism here. And this class turned into:
public async Task Invoke(HttpContext context)
{
    try
    {
        await next(context);
    }
    catch (Exception ex)
    {
        var isAdmin = context.User.Identity.Name == "Admin" ? true : false;
        var errorId = Guid.NewGuid();
        var problemDetails = new ProblemDetails
        {
            Title = "An error has occurred",
            Status = 500,
            Detail = isAdmin ? ex.InnerException.ToString() : "Please contact us for details",
            Instance = Guid.NewGuid().ToString()
        };

        LogContext.PushProperty("UserName", context.User.Identity.Name);
        LogContext.PushProperty("ApiPath", context.Request.Path);
        LogContext.PushProperty("ErrorId", errorId);

        _emailService.SendMail(new EmailDto
        {
            To = new List<string>() { "mail@mail.com" },
            Body = ex.InnerException != null ? ex.InnerException.ToString() : ex.ToString(),
            Subject = "Error!" + context.Request.ToString()
        });

        context.Response.StatusCode = 500;
        context.Response.WriteJson(problemDetails, "application/problem+json");
    }
}

But when I run the application, I see that the application does not write the logs to the database.
Here is Serilog configuration:
var appSettings = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();

var sinkOpts = new SinkOptions { TableName = "_Log", AutoCreateSqlTable = true, BatchPostingLimit = 10 };
var columnOptions = new ColumnOptions
{
    AdditionalColumns = new Collection<SqlColumn>
    {
        new SqlColumn
            {ColumnName = "UserName", PropertyName = "UserName", DataType = SqlDbType.NVarChar, DataLength = 64},

        new SqlColumn
            {ColumnName = "ApiPath", PropertyName = "ApiPath", DataType = SqlDbType.NVarChar, NonClusteredIndex = true},

        new SqlColumn
            {ColumnName = "ErrorId", PropertyName = "ErrorId", DataType = SqlDbType.NVarChar,DataLength = 36 }
    }
};
columnOptions.Store.Remove(StandardColumn.MessageTemplate);
columnOptions.Store.Remove(StandardColumn.Properties);

    Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.MSSqlServer(
    connectionString: appSettings.GetConnectionString("DB"),
    sinkOptions: sinkOpts,
    columnOptions: columnOptions,
    restrictedToMinimumLevel: LogEventLevel.Error
).CreateLogger();

I can't find where I made a mistake and I need your help.


text:
Q: No Startup folder in Microsoft Office for Mac 2011 I'm trying to save a new default worksheet in Excel for Mac 2011. Instructions say to save it in the Startup folder at this location:
/Applications/Microsoft Office 2011/Office/Startup/Excel

There is no Startup folder here. Instructions on the Microsoft website do not include the 2011 version. Is this a problem with my installation, Excel for Mac 2011, or something else?

A: Microsoft Excel for Mac uses a default workbook, but you can use your own.
Your Startup folder by default is:
HD:Applications:Microsoft Office 2011:Office:Startup:Excel
(You can change this in Preferences if you want).

*

*Create your work with all the settings you want.

*Save the workbook as a template (.xltm) with a name of Workbook (without quotes)

*Navigate to your Startup folder

*Select the file and choose Get Info

*Delete the extension (.xltm) on the file.

Excel will now use that workbook as your default workbook.

A: I removed the file linkCreation.dotm
From my HD:Applications:Microsoft Office 2011:Office:Startup:Word folder and it fixed the problem


text:
Q: The left -hand and right hand side of an arithmetic operation must be of type 'any', 'number' or an enum type I am getting the following error. I am not able to find out where exactly i went wrong.Can someone help me out with the solution

The code
 function() {
    this.devices.forEach(device => {
      let lastConnect = device.lastConnection.split('+');
      lastConnect = lastConnect[0] + 'Z';
      let diff = Math.abs(new Date() - new Date(lastConnect));//getting error here
}

A: Another great way:
Math.abs((new Date() as any) - (new Date(lastConnect) as any));

A: Typescript seems to have problems with implicit conversions, so we can just make them explicit:
Math.abs(+new Date() - +new Date(lastConnect));

Note that we don't need any parentheses because the new operator binds tighter than the (unary) + operator. After all, (+new) wouldn't make any sense. The + after the - is needed as well.
I'd use any only as a last resort since it basically disables typechecking.
Modifying a piece of code too much just to appease Typescript is not always safe as one may introduce errors because of wrong assumptions. This happens especially when one decides to convert some old .js files into .ts files. I think that making an implicit conversion explicit is the safest approach, in general.

A: Needless to say, Your code works correctly in Javascript, If you want to get the same result in Typescript, You have 3 options
(1) - With the help of  valueOf
let diff = Math.abs(new Date().valueOf() - new Date(lastConnect).valueOf());

(2) - With the help of  getTime
let diff = Math.abs(new Date().getTime() - new Date(lastConnect).getTime());
// or
let diff = new Date().getTime() - new Date(lastConnect).getTime();

(3) - With the help of  any
let diff = Math.abs(<any>new Date() - <any>new Date(lastConnect))

A: I have found out the issue.
The code you have written works only in Javascript
Math.abs(new Date() - new Date(lastConnect)) .

In order to make it work in Typescript, update the code as shown below:
Math.abs(new Date().getTime() - new Date(lastConnect).getTime());

A: The simplest answer would be
Math.abs(<any>new Date() - <any>new Date(lastConnect));

A: No need for Math.abs() to answer this question...
Just using getTime() method converts a Date into a number (Date.prototype.getTime()) so you can make the operation without that error
Check on this example

A: I got same issue with *ngIf="event && +event.enableSomething", as sometimes I'm receiving "0" data so parsing is needed but event interface was created for enableSomething: boolean so in that case I was retriving that error.
To fix this make sure that backend return boolean and leave enableSomething: boolean in interface or modify an interface to to enableSomething: any
I hope it helps someone with the same problem as occurred on my side.

A: In my case I add .valueOf() after input of Math.abs()
Math.round(valA.valueOf() / 20)

according to de doc:

The valueOf() method returns the primitive value of the specified object.


text:
Q: How to create empty data frame with column names specified in R?
Possible Duplicate:
Create an Empty Data.Frame

I need to create an empty data frame in R with specified column names. Any simplest way ?

A: Just create a data.frame with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num
##  $ y: int
##  $ z: Factor w/ 0 levels:

or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

A: Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)


text:
Q: Get result of future without blocking This question has been asked before and if I am not wrong, the only way to read the result of a future is either to call get() and block until it is ready or using wait_for() with zero duration as mentioned in the answer - Get the status of a std::future
But, if I just want a worker thread to return me a result that I want it to compute and not wait or block myself for it to complete, can I not just pass it a callback that the worker thread can call when it has computed the result for me? Something like below -
#include <iostream>
#include <thread>
#include <functional>

void foo(std::function<void(int)> callback)
{
    int result = 5;
    callback(result);
}

int main()
{
    int result = 0;
    std::thread worker(foo, [](int result)
    {
        std::cout << "Result from worker is " << result << std::endl;
    });
    worker.join();
}

Here, the worker thread would just execute the callback when it has computed the result for me. I don't have to wait for it to finish or block or check in a loop to know when it's ready.
Please advice is this is a good approach to be used as currently there is no way to do this without blocking or checking for it in a loop?

A: You can certainly create your own thread with a callback, but as soon as you move away from a toy example you will notice that you have potentially created a synchronization problem.  This is because your callback is being invoked from a separate thread.  So you may want to have the worker thread instead post a message to a queue which you will read later, unless there is no shared state or a mutex is already in place.
In your specific example, let's add one line of code:
int main()
{
    std::thread worker(foo, [](int result)
    {
        std::cout << "Result from worker is " << result << std::endl;
    });
    std::cout << "I am the main thread" << std::endl; // added
    worker.join();
}

You might think that there are only two possible outputs:
I am the main thread
Result from worker is 5

and
Result from worker is 5
I am the main thread

But in fact there are other possible outputs, such as:
Result from worker is I am the main thread
5

So you have created a bug.  You either need synchronization on your shared state (which includes I/O), or you need to orchestrate everything from the main thread (which is what blocking or checking for a future result gives you).


text:
Q: unir 4 consultas de una misma tabla en mysql Hola comunidad necesito de su apoyo como dice el titulo necesito unir 4 consultas de una misma en una sola consulta, tengo la siguiente tabla 'productos' :

id
codigo
marca
modelo
calidad
estado_merma
fecha
estado_vendido

123
000001
lg
xpro
alta
1
m/d/a
0

324
000002
lg
xpro
alta
0
m/d/a
1

345
000003
lg
xpro
baja
0
m/d/a
1

347
000004
lg
xpro
baja
1
m/d/a
0

348
000005
xiaomi
poco
alta
1
m/d/a
1

*

*estado_merma: hace referencia si el producto esta defectuoso o no ( 1=optimo, 0=defectuoso).

*estado_vendido: hace referencia si el producto a sido vendido o no (1=disponible, 0=vendido).
NECESTO AGRUPARLOS POR marca,modelo,calidad  DE ACUERDO A ESO mostrar la cantidad, vendidos, merma y stock.
CONSULTA PARA MOSTRAR marca,modelo,calidad y cantidad:
SELECT marca,modelo,calidad, COUNT(*) AS cantidad
FROM productos
GROUP BY marca,modelo,calidad;

CONSULTA para mostrar vendidos:
SELECT marca,modelo,calidad, COUNT(*) AS vendidos
FROM productos
WHERE estado_logico=0
GROUP BY marca,modelo,calidad;

CONSULTA PARA MOSTRAR MERMA:
SELECT marca,modelo,calidad, COUNT(*) AS merma
FROM productos  WHERE estado=0
GROUP BY marca,modelo,calidad;

CONSULTA PARA MOSTRAR STOCK:
SELECT marca,modelo,calidad, COUNT(*) AS stock
FROM productos WHERE estado_logico=1 AND estado=1 GROUP BY marca,modelo,calidad;

UNIENDO LAS 4 CONSULTAS obtendria algo como esto :

marca
modelo
calidad
cantidad
vendidos
merma
stock

lg
xpro
alta
2
1
1
0

lg
xpro
baja
2
1
1
0

xiaomi
poco
alta
1
0
0
1

Gracias de antemano.

A: Puedes agrupar las 4 consultas en una sola utilizando la sentencia CASE. En cada caso si se cumple la condición especificada el resultado será 1, null en caso contrario; luego sumas o cuentas los 1.
SELECT marca,
       modelo,
       calidad,
       COUNT(*) AS cantidad,
       COUNT(CASE WHEN estado_vendido = 0 THEN 1 END) AS vendidos,
       COUNT(CASE WHEN estado_merma = 0 THEN 1 END) AS merma,
       COUNT(CASE WHEN estado_vendido = 1 AND estado_merma = 1 THEN 1 END) AS stock
FROM productos
GROUP BY marca, modelo, calidad;


text:
Q: Finding exact number of a given symbol at the beginning of a string I'm trying to solve a Ruby problem using as less code as possible :). I want to check if a given string starts with a varying number of symbols, lets say between one and three 'a'. That's easy using reg exp, I can write string.match(\^a{1,3}.*\). But then I have to make changes on the string depending of the exact number of a's. How can I detect them without using three if's like that:
do_string_manipulation1 if string.match(/^a.*/)
do_string_manupulation2 if string.match(/^aa.*/)
...

Thanks in advance :)

A: Why not use a modified version of the first regexp and then simply count the a's it returns? A la
m = string.match(/^(a{1,3})/)
case m[1].size
  when 1
  when 2
  when 3
end

Of course you can also use an array to store routines to call, depending on the number:
routines = [nil, method(:do_string_manipulation1), method(:do_string_manipulation2), ...]
routines[m[1].size].call

A: Depends on what your string manipulations are.
You can determine the number of consecutive a's by doing:
string.match(/^(a{1,3}).*/)[1].size

You haven't defined the rules, so mine are:
"a"   - downcase
"aa"  - reverse
"aaa" - swapcase

So my code is:
string.send([:downcase, :reverse, :swapcase][string.match(/^(a{1,3}).*/)[1].size-1])

If your rules are more complicated, then you can define them as methods on a class and call them depending on the number returned.


text:
Q: fsolve from scipy.optimize fails I am trying to compute the roots of a vectorvalued functions, but the solution I get from fsolve is entirely wrong. I do get the warning: 175: RuntimeWarning: The iteration is not making good progress, as measured by the improvement from the last ten iterations.
warnings.warn(msg, RuntimeWarning)
Here comes the working example:

import numpy as np
from scipy.optimize import fsolve

def AMOC(amoc_state,
         gamma= 1/0.34,
         theta = 1,
         mu = 7.5,
         sigma = 0.85):
    T = amoc_state[0]
    S = amoc_state[1]
    dT = -gamma * (T-theta) - T * (1+ mu*np.abs(T-S))
    dS = sigma-S*(1+mu*np.abs(T-S))
    return (dT, dS)

test = fsolve(AMOC, (0.8,0.3), 2.3,xtol = 1e-7, factor = 0.1, maxfev = 1000)

this gives me test = array([0.57372733, 0.47660354]) which is obviously no root of the AMOC function since
AMOC((0.57372733, 0.47660354), gamma = 2.3)
returns (-0.01121948095040759, 0.026224895476309684)
any help is very much appreciated!

A: As already mentioned in the comments, the abs function is not differentiable and so is your function AMOC. This is important since fsolves underlying algorithm uses the derivative information in order to solve F(x) = 0 and thus, assumes that the function F is differentiable.
However, as a workaround you can replace abs(x) by the smooth approximation sqrt(x**2 + 1.0e-4):
def AMOC(amoc_state, gamma= 1/0.34, theta = 1, mu = 7.5, sigma = 0.85):
    T, S = amoc_state
    smooth_abs = np.sqrt((T-S)**2 + 1.0e-4)
    dT = -gamma * (T-theta) - T * (1+ mu*smooth_abs)
    dS = sigma-S*(1+mu*smooth_abs)
    return np.array((dT, dS))

Next, you can try another initial guess as Warren already mentioned. Otherwise, you can solve the problem as equivalent minimization problem by means of scipy.optimize.minimize. In my experience, the solvers are a bit more robust:
from scipy.optimize import minimize

res = minimize(lambda x: np.sum(AMOC(x, 2.3)**2), x0=(0.8,0.3))

yields the solution array([2.25836418e-01, 1.38576534e-06]).


text:
Q: Parametrizing curve for complex analysis integral I'm trying to show that
$$
\int_{|z-z_0| = R} (z-z_0)^m \, dz = \begin{cases}0, & m \neq -1 \\ 2\pi i, & m =- 1. \end{cases}
$$
Here's my attempt at a solution:
We parametrize the curve at $z(\theta) = z_0 + Re^{i\theta}$ and therefore $dz = iRe^{i\theta} \, d\theta$. Substituting, we have
$$
\int_0^{2\pi} R^me^{im\theta} \, iRe^{i\theta} \, d\theta.
$$
However, I feel that this is wrong since there will be a dependence on $R$. Anyone have a suggestion?

A: No, your work is correct. Factoring out constants, you simply need to evaluate
$$i R^{m + 1} \int_0^{2\pi} e^{i(m + 1) \theta} d\theta$$
Now if $m = -1$, then $R$ has exponent $0$ and will simply become $1$; if $m \ne -1$, then the integral vanishes and kills the dependence on $R$ anyways.

A: Use the cauchy integral formula
$\int_{|z-z_0| = R} \frac{f(z)}{(z-z_0)^{n+1}}dz=2\pi i\frac{f^{(n)}(z_0)}{n!}$
For $m=-1$, if we choose $f(z)=1$, then by cauchy integral formula
$\int_{|z-z_0| = R} (z-z_0)^{-1}dz =2\pi i$
For $m\in\{-2,-3,-4,....\}$
Take $f(z)=1$
Then by cauchy integral formula we have
$\int_{|z-z_0| = R} (z-z_0)^{m}dz=2\pi i\frac{f^{(-m-1)}(z_0)}{(-m-1)!}=0\hspace{0.02cm} $$\hspace{0.02cm}$because derivatives of constant function are zero.
For $\hspace{0.05cm}m\in\{0,1,2,3,4,......\}$ $\hspace{0.02cm}$ you can use Cauchy Goursat Theorem to prove that
$\int_{|z-z_0| = R} (z-z_0)^{m}dz=0$
So in general
$$
\int_{|z-z_0| = R} (z-z_0)^m \, dz = \begin{cases}0, & m \neq -1 \\ 2\pi i, & m = -1. \end{cases}
$$

A: For $m\geqslant 0, f(z) = (z - z_{0})^{m}$ is analytic on $\mathbb{C}$.  Thus the line integral is 0 ( by FTOC ).
For $m = -1, f(z) = 1$ is analytic on the closed disc $\rvert z - z_{0}\rvert\leqslant R$, so by Cauchy's integral formula this implies that $$1 = \frac{1}{2\pi i}\int_{\rvert z - z_{0}\rvert = R}\frac{1}{z - z_{0}}\,\mathrm{d}z.$$  Therefore the integral is $2\pi$.
For $m < -1$, take the derivative.. so $$0 = \frac{1}{2\pi i}\int_{\rvert z - z_{0}\rvert = R}(z - z_{0})^{m}\,\mathrm{d}z$$.


text:
Q: Period of a holomorphic $1$-form and the period matrix. Let $\omega$ be a holomorphic $1$-form on a complex curve $C$ of genus $g$.
I want to make sure that I have the correct notion of the period of a holomorphic $1$-form in terms of the period matrix in mind.
I am a bit confused about this because in Griffiths and Harris he defines periods as the columns of the period matrix but I can't find a definition of the period of an arbitrary $1$-form $\omega$.
I think the period of $\omega$ could be described by the following row  vector
$\begin{bmatrix} \int_{\gamma_1} \omega &  \int_{\gamma_2} \omega & \cdots & \int_{\gamma_{2g}} \omega \end{bmatrix} $
where $\gamma_i$ are a basis of $H^1(C, \mathbb{Z})$. Now suppose that $\omega_1, \dots, \omega_g$ is a basis for $H^0(C, \Omega^1)$ so that
$\omega= m_1 \omega_1 + \dots + m_g \omega_g$ where $m_i \in \mathbb{C}$.
Then I think we could write the period of $\omega$ in terms of the period matrix with some extra coefficients, i.e,
$\begin{bmatrix} m_1\int_{\gamma_1} \omega_1 &  m_1 \int_{\gamma_2} \omega_1 & \cdots & m_1 \int_{\gamma_{2g}} \omega_1 \\
m_2\int_{\gamma_1} \omega_2 &  m_2 \int_{\gamma_2} \omega_2 & \cdots & m_2 \int_{\gamma_{2g}} \omega_2 \\
\vdots \\
m_g\int_{\gamma_1} \omega_g &  m_g \int_{\gamma_2} \omega_g & \cdots & m_g \int_{\gamma_{2g}} \omega_g
 \end{bmatrix} $
and then define the period of $\omega$ to be the sum of the column vector of the above matrix.

*

*Is my definition of the period of $\omega$ correct?

Now let $\Lambda$ be the lattice formed by the columns of the period matrix which are known to be linearly independent via the Riemann bilinear relations.
It would be great if  elements of this lattice are periods of holomorphic $1$ forms on $C$. However, the lattice is defined over $\mathbb{Z}$ and unfortunately the coefficients in the above matrix are in $\mathbb{C}$.
Are periods of arbitrary $\omega$ not elements of the lattice $\Lambda$ ?


text:
Q: Exim, hot to route local mail to other adress I have setuped an Exim4 server on my debian wheezy server. This mail server only sends mail coming from localhost. The purpose is sending mail for my website.
I have cron tasks and other services generating mails for root user.
These mails are not stored in /var/mail as before, but sent by exim to root@mydomain.com.
I try to make exim send mails for root to mypersoaddress@gmail.com rather than root@mydomain.com.
I tried adding a .forward in /root with mypersoaddress@gmail.com as content. I tried also changing /etc/aliases with root: mypersoaddress@gmail.com. The fact is that routing works for root@localhost but not for root which is resolved as root@mydomain.com
I tested how routing is resolved with exim -bt :
root@srv02:~# exim -bt root@localhost
R: system_aliases for root@localhost
R: dnslookup for mypersoaddress@gmail.com
mypersoaddress@gmail.com
    <-- root@localhost
  router = dnslookup, transport = remote_smtp
  host gmail-smtp-in.l.google.com      [173.194.67.27] MX=5
  host alt1.gmail-smtp-in.l.google.com [74.125.143.27] MX=10
  host alt2.gmail-smtp-in.l.google.com [74.125.25.27]  MX=20
  host alt3.gmail-smtp-in.l.google.com [173.194.64.27] MX=30
  host alt4.gmail-smtp-in.l.google.com [74.125.142.27] MX=40
root@srv02:~# exim -bt root
R: dnslookup for root@mydomain.com
root@mydomain.com
  router = dnslookup, transport = remote_smtp
  host aspmx.l.google.com      [173.194.78.27] MX=1
  host alt1.aspmx.l.google.com [74.125.143.27] MX=5
  host alt2.aspmx.l.google.com [74.125.25.27]  MX=5
  host alt4.aspmx.l.google.com [74.125.142.27] MX=10
  host alt3.aspmx.l.google.com [173.194.64.27] MX=10

I bet this is a matter of how my server is configured (rather than how exim is configured). But to understand well I would like to have a solution for both :

*

*how to have root resolved as root@localhost ?

*how to have root@mydomain.com routed to mypersoaddress@gmail.com ?

A: The debug output you are using indicates you're using a Debian style configuration system.  I'm going to refer to this as exim4 in order to make it clear that there is some extra configuration magic occurring beyond the default exim config that comes in the source.  Anybody reading this later needs to clearly understand that some of this suggestion does not apply unless they are running Debian style exim configs.
The difference in your -bt output gives a clue:
root@srv02:~# exim -bt root@localhost
R: system_aliases for root@localhost
R: dnslookup for mypersoaddress@gmail.com
mypersoaddress@gmail.com

root@srv02:~# exim -bt root
R: dnslookup for root@mydomain.com
root@mydomain.com

In the first one, it knew to look in the system_aliases router because "localhost" is configured to be one of the domains that is allowed to look in the aliases file.  But in the second one, it skipped over that aliases file because "mydomain.com" is not in that list.  In exim4, that list is the MAIN_LOCAL_DOMAINS macro.
By my estimation, one of these things is probably going to solve your problem.  Items 2 and beyond are potential adjustments to your exim.conf.  Since you run exim.4, you need to be adjusting Debian mail configuration files in /etc/exim/ and then run exim4-conf.conf or something like that to have those changes read in and generate the new configuration file (/var/lib/exim4/config.autogenerated*) that exim4 actually uses.:

*

*Make sure that the /root/.forward file is readable by the exim user.

*Add mydomain.com to the list of domains called +local_domains which should then make exim4 look for the $HOME/.forward file.  It does sound like you already have this set correctly.

*Move the userforward router to occur before the dnslookup router (which it already does, but maybe you have changed the default router layout?)

*Add mydomain.com to the list of domains allowed to search the aliases file. (likely this will break other things)


text:
Q: Fade bottom text while scroll to down with linear gradient I have list of news articles so user know that there is some text in bottom. How i tried like this style="background: linear-gradient(360deg, rgba(135, 135, 135, 0) 0%, #878787 20%)"
but i am not getting what i want to achieve.
Here is screen how i want to get it

Now i am getting like this

A: Just apply it on an ::after pseudoelement. I create a snippet to illustrate. Create a wrapper with relative and ::after on it, and inside the scroll layer and the articles. Just easy.

.wrapper {
  position: relative;
}
.scroll {
  position: relative;
  height: 150px;
  overflow: auto;
}
.article {
  height: 80px;
  background: blue;
  margin: 10px;
}
.wrapper::after {
  content: " ";
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 1111;
  background-image: linear-gradient(transparent, #ccc);
  height: 50px;
}

a

b

c

A: You need to just update your .scss file like:
  .item-md{
    background: #878787;
    padding-right:15px !important;
    color: #fff !important;
  }

I think its solve your problem


text:
Q: Which way is a normal pointing/facing when i calculate it using triangle vertices? I know from online research that to calculate a normal that is the same for the entire triangle surface is to simply compute the cross product of two edges, however, what I did not understand is that when you calculate this normal which way is it exactly pointing? Is it pointing outward towards me or inward? This entire time I have been assuming that it was outward which is not correct way of thinking. Can someone explain to me how to tell? Is this dependent on which edges I use to compute the normal?

A: If you label your edges $a$ and $b$, and you compute $a\times b$, then point your index finger along $a$, your middle finger along $b$, your thumb is the normal vector.

A: A surface has two normal vectors which point to opposite direction. Your can use the right-hand rule to determine the direction of a normal vector:

Cite: this image comes from wikipedia, https://en.wikipedia.org/wiki/Cross_product.


text:
Q: Simplest sed to remove all duplicating anywhere in document How is sed simplest code to remove all duplicating lines anywhere in document
This reference script, I guess, do only such if it's consecutive only isn't it?
sed -E '$q; N; /^(.*)\n\1$/!{ P; D }; :L $d; s/.*\n//; N; /^(.*)\n\1$/bL; D

Please help out... will highly gratified

A: This might work for you (GNU sed):
sed -E 'H;x;s/((\n[^\n]*).*)\2$/\1/;x;$!d;x;s/.//' file

Append each line to the hold space and remove it if it has occurred before.
At the end of file, remove the first introduced newline.

A: Using sed, assuming your input file looks like;
$ cat input_file
one
one
two
one
three
four
three
three
five
two
five
four
three
four
four
five

$ sed -n 'G;/^\(.*\n\).*\n\1$/d;H;P' input_file
one
two
three
four
five

A: If I'm understanding correctly, you want to remove all but the first instance of any duplicated lines in a file, right?
So that
alpha
beta
beta
gamma
beta
delta
alpha
delta

becomes
alpha
beta
gamma
delta

So don't use sed.  Use Perl to walk through the file line by line and only print the lines it has not seen before:
perl -ne'print unless $seen{$_}++' input.txt > output.txt


text:
Q: ¿Cómo enviar formulario HTML con una combinación de teclas? Tengo un formulario, el cual lleva en conjunto un onclick de javascript, lo que quiero es que si el usuario por ejemplo hace la combinación de teclas Crtl+S, fse realize la acción de como si diera click a enviar
EDICIÓN: Por si sirve para darme una ayuda, el inicio del formulario
<form name="myForm" method="post" action="upload.php"  onsubmit="return validateForm()" autocomplete="off">

A: ¿Porque me autorespondo?
Como ninguna respuesta me ayudó a solucionar mi problema, he estado bastante tiempo buscando por internet, y he encontrado la solución correcta a mi problema:
No marco ningun Verified, porque probé los links o soluciones dadas y ninguna me funciona
<script>
$(document).keydown(function(e) {

    var key = undefined;
    var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];

    while (key === undefined && possible.length > 0)
    {
        key = possible.pop();
    }

    if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
    {
        e.preventDefault();
        document.getElementById( "id de boton submit" ).click();
        return false;
    }
    return true;
});
</script>

Esto me funciona, dando a CRTL+S y me envía al upload.php y si que revisa el validateForm()

A: Aunque como te comentan hay una pregunta similar cuya respuesta propone utilizar un plugin de jQuery, esto también se puede hacer sin utilizar ninguna librería.
Cuidado con la combinación de teclas que eliges. Ctrl+S, por ejemplo, la captura Chrome para permitir al usuario guardar la página actual en un fichero html.
He preparado un ejemplo utilizando Ctrl+I.
Según lo que quieras conseguir podrías hacer submit directamente del form para lo que tendrías que ejecutar tú mismo la función de validación:

document.addEventListener('keypress', checkHotkeys);

function checkHotkeys(e){
  if (e.code === 'KeyI' && e.ctrlKey){
    if (validateForm())
      document.getElementById('myForm').submit();
  }
}

function validateForm(){
  console.log('validateForm llamado');
  return false;
}
<form name="myForm" id="myForm" method="post" action="upload.php"  onsubmit="return validateForm()" autocomplete="off">
  <input type="submit" id="submitButton" value="Enviar" />
</form>

O provocar un click sobre el botón submit con lo que se ejecutaría la función asociada al onsubmit:

document.addEventListener('keypress', checkHotkeys);

function checkHotkeys(e){
  if (e.code === 'KeyI' && e.ctrlKey){
    document.getElementById('submitButton').click();
  }
}

function validateForm(){
  console.log('validateForm llamado');
  return false;
}
<form name="myForm" id="myForm" method="post" action="upload.php"  onsubmit="return validateForm()" autocomplete="off">
  <input type="submit" id="submitButton" value="Enviar" />
</form>

A: Puede ponerle el evento a la pagina para la combinación y así sabría que debe enviar el formulario, seria así:
$(document).keydown(function (ev) {
            if (ev.keyCode == 17) { //al presionar Ctrl(17) ,preguntaría  si luego se presiona nuevamente por ejemplo A
                $(document).keydown(function (ev) {

                   if (ev.keyCode == 65) { //al presionar A(65)
                     $('#id_formulario').submit() //al producirse la combinación se envía el formulario
                      return false;
                   }

                });
            }
    });

Este código respondería a la combinación Ctrl-A.
Te dejo los códigos para que elijas la combinación con el código que desees

Saludos y espero te resuelva.

A: Agregas un listener y verificas si las teclas presionadas corresponden a las que deseas.

window.addEventListener("keydown", e => {
  var keyCode = 'which' in e ? e.which : e.keyCode;
  if(e.ctrlKey && keyCode === 83) {
  e.preventDefault();
  enviar.click();
  }
});
<input type="button" id="enviar" value="Enviar" onclick="alert('Enviado!')"/>


text:
Q: Can I mirror all my Google Chrome extensions into Microsoft Edge in 19H2? I understood that after 19H2 upgrade for Windows 10, Microsoft's Edge engine will be changed from EdgeHTML to Blink (of Google Chrome).
For those using test versions of 19H2,
Can I "pump" all my Google Chrome extensions into Microsoft Edge in 19H2 instead re-installing all of them on Edge and re-configure each one on Edge?
This will save me from making each change in each extension on both browsers.

A: Edge has not yet changed although I have Edge with Chromium rendering running on Windows Insider (19H2) and the main browser applications are still different so what you want is not at all likely to work. Only the rendering engine is part of Edge. It otherwise looks and works the same as it did.
The applications are different enough so you would need to get your Edge Extensions from the Store


text:
Q: Linux - configure TI AM335X MDIO when connected to Marvell's switch I have a board with Sitara AM3352 - the networking is not via Ethernet PHY, but with a switch (Marvell 88E6341) that is connected to the CPU with MII. the switch has a port that is connected to a PHY and RJ45 connector.
My Linux version is 4.14
I configured the dts file correctly for having a network, but I also want the MDIO driver to be active so I will be able to manage the switch.
It looks like I can interact the Sitara MDIO controller with "devmem" commands, but I prefer to do it the "normal" way with the kernel devinci-mdio driver.
My dts looks like this:
&cpsw_emac0 {
phy_id = <&davinci_mdio>, <0>;
fixed-link = <1 1 100 0 0>;
phy-mode = "mii";
};

&mac {
slaves = <1>;
pinctrl-names = "default", "sleep";
pinctrl-0 = <&cpsw_default>;
pinctrl-1 = <&cpsw_sleep>;
status = "okay";
};

&davinci_mdio {
compatible = "ti,cpsw-mdio";
pinctrl-names = "default", "sleep";
pinctrl-0 = <&davinci_mdio_default>;
pinctrl-1 = <&davinci_mdio_sleep>;
status = "okay";
};

This what I get in the dmesg:
[ 0.975182] mdio_bus fixed-0: GPIO lookup for consumer reset
[ 0.975195] mdio_bus fixed-0: using lookup tables for GPIO lookup
[ 0.975202] mdio_bus fixed-0: lookup for GPIO reset failed
[ 0.975223] libphy: Fixed MDIO Bus: probed
[ 0.994386] mdio_bus 4a101000.mdio: GPIO lookup for consumer reset
[ 0.994398] mdio_bus 4a101000.mdio: using lookup tables for GPIO lookup
[ 0.994405] mdio_bus 4a101000.mdio: lookup for GPIO reset failed
[ 1.047323] davinci_mdio 4a101000.mdio: davinci mdio revision 1.6, bus freq 1000000
[ 1.055025] davinci_mdio 4a101000.mdio: no live phy, scanning all
[ 1.061484] davinci_mdio 4a101000.mdio: mdiobus_register ret=-5

I think it is rather common such design - so if anybody managed to handle this issue, I will much appreciate it if he will share the knowledge.
Thanks

A: Active the devinci_mdio kernel driver for a network switch is not trivial, but it must in order to use the Marvell software package to manage the switch.
So instead of using the kernel driver - it is possible to access the MDIO controller physical addresses from the Linux userspace with the"mmap" command:

*

*In am3352 the MDIO controller address is 0x4a101000 - map this address, the length should be 0x90 bytes.

*Enable the controller in the address 0x4a101004 with the data 0x410000ff (the ff is for the clock speed, so another value is possible)

*Read and write will be with address 0x4a101080.

Now you can implement the MDIO read and write functions that are required for Marvell's software package (or for other software packages)


text:
Q: Ipython jupyter_client get python object I am working on a custom implementation of IPython and I would like to know if it is possible to get python raw objects from the kernel (and not just the str outputs sent from the kernel). I was not able to find any magic command to pass to the kernel to get raw object
Thank you for any comment on this question


text:
Q: how to calculate derivative in python using sympy I have the function (x ** 2 - 612),
Its derivative is (2*x), in which sympy.
However, I would like to assign a value for x.
example: (2*10)
import sympy as sp

x = sp.Symbol('x')

func = (x**2 - 612)
dx = (sp.diff(func,x))

print(dx)

A: resolution
from sympy import *

x = Symbol('x')
f = (x**2 - 612)

dx = (diff(f,x))
r = dx.subs({x:10})

print(r)


text:
Q: Making a table of content for LaTeX I have to write a paper for UNI, as a requirement I have to respect the template and the rules set by the supervisors for writing the paper in LaTeX.
There is a requirement stating: After the abstract add your local table of contents with the commands
\bigskip\par\hrule\smallskip\par\setcounter{minitocdepth}{2} \dominitoc.
Since my experience with LaTeX is very slim, I fail to understand what is happening there, and how a table of content can be created with those lines.
Would you please explain what's happening there in a simple fashion, understandable for someone inexperienced.
additional info from the rules:
Your header must look as follows:
\documentclass{svmult}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{makeidx}
\usepackage{graphicx}
\usepackage{multicol}
\usepackage[bottom]{footmisc}
\usepackage{amsmath, amssymb, amsfonts, amscd}
\usepackage{algpseudocode}
\usepackage{algorithm}
\usepackage{listings}
\usepackage{verbatim}
\makeindex

SOLUTION:
OK seemed to work like this:
Didn't do much, just had to refresh the FNDB (filename database) and then it worked... Well I use MikTeX on windows, I think the equivalent of refresh FNDB in Linux is $ texhash
To explain the workflow.

*

*Just pasted the line \bigskip\par\hrule\smallskip\par\setcounter{minitocdepth}{2} \dominitoc

*then added \usepackage{minitoc} to the header, so it gets installed to the Miktex, then had to remove it because it gave some error.

*after removing that line and refreshing FNDB everything worked fine. There is no need to write \tableofcontents or something, the table of content is generated automatically
Thanks for the patience!
Peace!

A: The OP forgot to load the package minitoc After adding it works well.


text:
Q: Can you make http client connections from a web app(flash, java)? Before I jump both feet in and waste my time learning something that I can't use for my needs, I have to ask:
Can I make a http connection to another website from within a java applet or a flash file?
Say I have a java applet that wants to load results from google. Will the JVM give me access to such a call? What about Flash? I've read about URLLoader but am confused with the this:
"    *  Data loading is not allowed if the calling file is in the local-with-file-system sandbox and the target resource is from a network sandbox.
    * Data loading is also not allowed if the calling file is from a network sandbox and the target resource is local."
Anyway if it isn't possible, will it fail on the user silently or will it ask for permission?
Thanks a lot.

A: Of course you can do that in Java, and also flash. However some browsers and environments may restrict by forcing security levels.
The warnings you found were related to local<->remote. For web applications which is hosted on network, you can usually access other network resources. (well, some may restrict you for "other" domains - you'll need to check the security models)
But modern technology usually suggest you to do that with the combination of JavaScript. Google for "Ajax" and search for some frameworks that best fits your requirement - that would save a lot of time.

A: Yes, but the problem is that for security reasons, many browsers only allow the application to connect to the domain from which the application came from.
so for example, if I go to website A and my app is trying to make an access to website B, it could sometimes be blocked (e.g., to avoid spamming, attacks, etc.). A work-around, if you control website A, is to create a "pass-through" script on website A that will send the request to B.

A:
Can I make a http connection to another website from within a java applet or a flash file?

From Flash, yes. You do need to read up on the Flash Security Model to be sure what you can and what you cannot ask. Most of the time this is to stop unauthorized access and/or XSS or similar attacks. Flex (a related technology), for example, does not give you access to your disk, whereas AIR does. Take your pick.
As for applets, you'll have to wait for someone else to explain it to you. But AFAIK, it also has a security model to pose the least threat to its users.

A: Not with ease. By definitions Java sandbox won't let your applet call other than the origin it came from. You will have to sign your applet properly. Then users will either trust your applet and let it call elsewhere, or deny it - it's up to user. You can self-sign your applet, but I would personally never allow such thingy on my computer. It's good for testing and stuff like that. So you'd probably need to buy a certificate from reputable source. Same to the Flash, I believe the idea is identical.

A: Java, JavaScript, Flash, etc., implement some form of "same origin" policy which only allows untrusted code to read from the site it was downloaded from. One way around this, supported to some extent by recent versions of Flash and Java since 6u10 is crossdomain.xml (Google it). This allows sites to permit access via code downloaded by other sites. Note, this requires the site you want to access to grant you permission to do so.