text:
Q: Cell click event in table layout.. I want to know how to get the cell click(ex:I want to click in the 3rd colomn of the 2nd row i.e. in 2x3 cell) event in a dynamic table view.I know about row click. But I want the particular cell click..
 Is it possible in list view if list view contains rows along with colomns??
Please help
Thanks

A: Using TableLayout dynamically you can do this thing.
   TableLayout table = new TableLayout(getApplicationContext());
   TableLayout.LayoutParams tab_lp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
   table.setLayoutParams(tab_lp);

  TableRow row = new TableRow(this);

  final TextView tvProduct = new TextView(getApplicationContext());

  LinearLayout.LayoutParams lp_l3 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, (LayoutParams.WRAP_CONTENT));
    tvProduct.setLayoutParams(lp_l3);
    tvProduct.setText(product);
    tvProduct.setClickable(true);

    row.addView(tvProduct,  new TableRow.LayoutParams(1));
    table.addView(row, new TableLayout.LayoutParams());

    tvProduct.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            Intent i = new Intent(Beers.this,BeerDetails.class);
            i.putExtra("Product_Name",tvProduct.getText().toString());
            startActivity(i);
         }
    });

    LinearLayout linearMain = (LinearLayout) findViewById(R.id.linearmainLayout);
    linearMain.addView(table);
    linearMain.postInvalidate();

A: You can use GridView for this kind of UI instead of TableLayout or ListView. In GridView you can set OnItemClickListener. Read more about GridView here.


text:
Q: What are the red lines in Neighbors screen on map? When choosing a place to embark, there is a screen that shows all the neighbors. Sometimes, I see:
Goblins     ~~~~~~~~ with ~ being red.
What does this mean?

A: The red ~~~~~~~ by a neighbor listing means that you are at war with that neighbor. Dwarves are almost always at war with any goblin neighbor, and less commonly with human or elven civilizations.
When an enemy civilization sends trade missions, goblins and humans will mostly deliver goblinite weapons and armor, while elves will bring largely useless wooden equipment. These trade missions will be heavily guarded, and you will probably have to capture or kill the guards to access the goods.

A: Goblins are you neighbors if you settle in that area.
Goblins are at war with you. Always. The red wavy line denotes "war".
You will have to deal with frequent goblin attacks and kobold thieves. On the plus side, you should be able to harvest a lot of goblinite.
If you do not want to deal with the extra trouble, settle in a different area.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JupyterLite not running anything I'm using JupyterLite as it is very comfortable to do so, but sometimes it simply won't work. To be clear, once I set the kernel (usually Pyodide) then it may happen that it will not run even the first line:
%pylab inline

being my first one. Yes I know that pylab is now deprecated but the problem is that no line will run, at this point I guess the problem is with the kernel itself? I tried changing it, with no results.


text:
Q: Async task class won't work on newer Android verison I want to parse xml so i wrote code it works upto 2.3 but on latest version it doesn't work so i read about asynctask and I modified my code but my imageview still is blank and I dont get any errors on logcat that means there is a problem in the implimentation of the Asynctask .
{
    setContentView(R.layout.actionbar);
    String URL = "http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=ricky_martin&api_key=97855e265470056987425832aa9aa81&limit=" + 1 + "&page=" + 1;
    new FetchXMLAsyncTask().execute(URL);
    icon = (ImageView) findViewById(R.id.icon);
}

class FetchXMLAsyncTask extends AsyncTask<String, Void, Void> {
    String name;
    @Override
    protected Void doInBackground(String... params) {
        try {
            // TODO Auto-generated method stub
            final String Artist = "artist";
            final String KEY_NAME = "name";
            final String API = "b25b959554ed76058ac220b7b2e0a026";
            final String KEY_IMAGE ="image";
            //final String KEY_COST = "cost";
            //final String KEY_DESC = "description";
            String URL = params[0];
            XmlParser parser = new XmlParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr;
            expr = xpath.compile("//image[@size=\"large\"]");
            NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                Element e = (Element) nl.item(i);
                String name = parser.getValue(e, KEY_NAME);// name child value
                image = parser.getValue(e, KEY_IMAGE);
                // Toast.makeText(this, "name"+name+"url"+image, Toast.LENGTH_SHORT).show();
            } }catch (XPathExpressionException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        //do something after parsing is done
        URL thumb_u;
        try {
            thumb_u = new URL(image);
            Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
            icon.setImageDrawable(thumb_d);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

A: Starting Honeycomb AsyncTasks are launched one at the time by default. Maybe you have some other task pending and blocking this one from running (new is waiting for old to finish, because it will woun't run in paralell).
Starting android 3.0 you should launch tasks in THREAD_POOL_EXECUTOR
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
    task.execute(params);
}


text:
Q: Derive the formula for the sum I have a problem with deriving the formula for the sum: $cos(\phi) + cos(3\phi) + \dots + cos((2n+1)\phi)=\dots $  Any hint of which series should be used here?

A: $$\underbrace{cos(\phi) + cos(3\phi)}_{3\phi-\phi=2\phi}+ \dots + cos((2n+1)\phi)$$ so  multiply/divide by half of deffernce betwen angles $\frac{2\cos(\phi)}{2\cos(\phi)}$ then use product to sum formulas
$$\frac{2\cos(\phi)}{2\cos(\phi)}(cos(\phi) + cos(3\phi) + \dots + cos((2n+1)\phi))=\\\frac{1}{2\cos(\phi)}(2\cos(\phi)\cos(\phi)+2\cos(\phi)\cos(3\phi)+2\cos(\phi)\cos(5\phi)+...+2\cos(\phi)cos((2n+1)\phi))=
\frac{1}{2\cos(\phi)}\begin{cases}\cos(\phi-\phi))-\cos(\phi+\phi)\\\cos(\phi-3\phi))-\cos(\phi+3\phi)\\\cos(\phi-5\phi))-\cos(\phi+5\phi)\\\vdots\\\cos(\phi-(2n-1)\phi))-\cos(\phi+(2n+1)\phi)\end{cases}
$$simplify
$$=\frac{1}{2\cos(\phi)}\begin{cases}\cos(\phi-\phi)-\cos(\phi+(2n+1)\phi)\}\end{cases}$$


text:
Q: Optimization problem - rectangular aquarium Find the dimensions that will minimize the surface area (and hence the cost) of a rectangular fish aquarium, open on top with a volume of 32 cubic feet.
$S(x,y,z)=xy+2xz+2yz$
$z=\frac{32}{xy}$
$S(x,y)=xy+\frac{64}{y}+\frac{64}{x}$
$y=\frac{64}{y^2}$
$x=\frac{64}{x^2}$
How do they get $64y-y^4=0$ ?

A: Going from your line
$S(x,y) = xy + \frac{64}{y} + \frac{64}{x}$
Now we take the partial derivatives:
$\frac{\partial S}{\partial x} = y-\frac{64}{x^{2}}$
$\frac{\partial S}{\partial y} = x-\frac{64}{y^{2}}$
At the stationary point we have:
$\frac{\partial S}{\partial y} = \frac{\partial S}{\partial x} = 0$
$\Rightarrow y-\frac{64}{x^{2}} = x-\frac{64}{y^{2}} = 0$
$\Rightarrow x = \frac{64}{y^{2}}$
Substituting into $\frac{\partial S}{\partial y} =0$:
$y - \frac{64}{x^{2}} = y -\frac{y^{4}}{64} = 0 \Rightarrow 64y-y^{4} = 0$ as required.


text:
Q: Kibana search preference My Elasticsearch cluster is split in fast and slow nodes. If I am manually querying by REST, I'll use the preference query parameter (https://www.elastic.co/guide/en/elasticsearch/reference/7.17/search-search.html#search-preference) to specify that I'd like the search to occur on a fast node.
I can't do the same in Kibana so how can I setup such that Elasticsearch/Kibana will search on the fast nodes if they are available, falling back to the replicas on the slow nodes as required?

A: You can change the way Kibana specifies the preference parameter by configuring this in Stack Management > Advanced Settings and then changing the following settings:

*

*courier:setRequestPreference = Custom (instead of SessionID)

*courier:customRequestPreference = _only_nodes:

Then it should work the way you expect.


text:
Q: When two processes read the same file simultaneously, will Linux kernel save one device I/O? I have a generic question about Linux kernel's handling of file I/O. So far my understanding is that, in an ideal case, after process A reads a file, data is loaded into page cache, and if process B reads the same page before it is reclaimed, it does not need to hit the disk again.
My question is related to how the block device I/O works. Process A's read request will eventually be queued before the I/O actually happens. Now if device B's request (a bio struct) is to be inserted into the request_queue, before A's request is executed, elevator will consider whether to merge B's bio into any existing request. Now, if A and B try to read the same file offset, i.e. same device block, they are literally the same I/O, (or A and B's requests are not exactly the same but they overlap for some blocks), but so far I have not seen this case being considered in kernel code. (The only relevant thing I saw is a test on whether bio can be glued to an existing request contiguously.)
kernel 2.6.11
inline int elv_try_merge(struct request *__rq, struct bio *bio)
{
    int ret = ELEVATOR_NO_MERGE;

    /*
     * we can merge and sequence is ok, check if it's possible
     */
    if (elv_rq_merge_ok(__rq, bio)) {
        if (__rq->sector + __rq->nr_sectors == bio->bi_sector)
            ret = ELEVATOR_BACK_MERGE;
        else if (__rq->sector - bio_sectors(bio) == bio->bi_sector)
            ret = ELEVATOR_FRONT_MERGE;
    }

    return ret;
}

kernel 5.3.5
enum elv_merge elv_merge(struct request_queue *q, struct request **req,
        struct bio *bio)
{
    struct elevator_queue *e = q->elevator;
    struct request *__rq;
    ...
    /*
     * See if our hash lookup can find a potential backmerge.
     */
    __rq = elv_rqhash_find(q, bio->bi_iter.bi_sector);
    ...
}

struct request *elv_rqhash_find(struct request_queue *q, sector_t offset)
{
    struct elevator_queue *e = q->elevator;
    struct hlist_node *next;
    struct request *rq;

    hash_for_each_possible_safe(e->hash, rq, next, hash, offset) {
        ...
        if (rq_hash_key(rq) == offset)
            return rq;
    }

    return NULL;
}

#define rq_hash_key(rq)     (blk_rq_pos(rq) + blk_rq_sectors(rq))

Does that mean kernel will just do two I/Os? Or (very likely) I missed something?
thanks!


text:
Q: How to make optimize ajax or request from cache I have server from amazon with cloud and have around 20K visitor at a time, but the problem is, I introduced a section to my site , which load content depend upon the height of page.
e.g. if a page have 2000px height , it request around 40 post's , Its ok for small number of visitor but not good with more than 1000 visitor (at a particular time).
Its halt my server and crashed mysql when i activate it , So is there any way i can smoothly get post without loosing visitor ?
Then i request post in 5-5 group using
function sfpside_bar_post_request(sfpnumber_of_post) {
        iCountI = 1;
        numbverofrequest = Math.floor(sfpnumber_of_post / 3);
        remainderpost = sfpnumber_of_post % 3;
        spi = setInterval(function() {
            if (iCountI > numbverofrequest)
            {
                handle_sidepost(remainderpost,iCountI);
                clearInterval(spi);
            }else{
              handle_sidepost(3,iCountI);
            }
            iCountI++;
        }, 1000);
    }
    function handle_sidepost(num_post,count) {
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var data = {
            wp_nonce: '<?php echo wp_create_nonce('sfp_forum_secret_no_one_knows_LATEST_SIDEBAR'); ?>',
            action: 'sfp_sidebar_random_sidebar',
            post_num: num_post,
        };

        jQuery.ajax({
            'async': true,
            'type': 'POST',
            'url': ajaxurl,
            'data': data,
            'success': function(data)
            {
                var sidepost = jQuery.parseJSON(data);
                sidepostcontent = '
';
                for (icount = 0; icount < sidepost.length; icount++) {
                    sidepostcontent += '

';
                    sidepostcontent += sidepost[icount].image;
                    sidepostcontent += '

';
                    sidepostcontent += sidepost[icount].like;
                    sidepostcontent += '

';
                    sidepostcontent += sidepost[icount].title;
                    sidepostcontent += '

';
                    sidepostcontent += sidepost[icount].greybutton;
                    sidepostcontent += '

';
                    sidepostcontent += sidepost[icount].circle;
                    sidepostcontent += '

';
                }
                sidepostcontent += "
";
                jQuery("#sfppost_sidebar_extra_post").append(sidepostcontent);
                jQuery(function() {
                    jQuery("#sidesfppost"+count+" img.imgload").css("width", "54px");
                    jQuery("#sidesfppost"+count+" img.imgload").css("height", "55px");
                    jQuery("#sidesfppost"+count+" img.imgload").lazyload({
                        load: image_loaded_page,
                        effect: "fadeIn",
                        failure_limit: 10,
                        threshold: 200
                    });
                });
            },
            contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15"
        });
    }

But it still crashes mine MySql
The WP which i used to request post
if ($_POST['action'] == 'sfp_sidebar_random_sidebar' && wp_verify_nonce($_POST['wp_nonce'], 'sfp_forum_secret_no_one_knows_LATEST_SIDEBAR')):

        $args = array('posts_per_page' => $_POST['post_num'], 'orderby' => 'rand', 'post_type' => 'sfp_forum');
        $rand_posts = get_posts($args);
        $iCount = 0;
        $postdata = array();
        foreach ($rand_posts as $post_data) :
            setup_postdata($post_data);
            $postdata[$iCount]['image'] = get_post_home_picture($post_data->post_content, $post_data->ID, $post_data->post_title, $author_username, 'category-small-thumb', 275, 416, true, true);
            $postdata[$iCount]['like'] = sfp_like_disklike_arrows("poplr", $post_data->ID, true);
            $postdata[$iCount]['title'] = "ID) . "'>" . sfp_strip_content($post_data->post_title, 50) . "";
            $postdata[$iCount]['greybutton'] = sfp_get_grey_button($post_data->ID, $post_data->post_title, true);
            $postdata[$iCount]['circle'] = sfp_home_postCircle($post_data->ID, $post_data->comment_count, true);
            $iCount++;
        endforeach;
        wp_reset_postdata();
        echo json_encode($postdata);
    endif;
    die;

A: I have little thought about optimize ajax request,
Here is my code:--
var oldSearchData = new Array();
function handle_sidepost(num_post,count)
{
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    var data = {
            wp_nonce: '<?php echo wp_create_nonce('sfp_forum_secret_no_one_knows_LATEST_SIDEBAR'); ?>',
            action: 'sfp_sidebar_random_sidebar',
            post_num: num_post,
        };
    if(oldSearchData[num_post])
    {
        data = oldSearchData[num_post];
    } else {
        jQuery.ajax({
            'async': true,
            'type': 'POST',
            'url': ajaxurl,
            'data': data,
            'success': function(data)
            {
                oldSearchData[num_post] = data;
                //do your action.
            }
        });
    }
}

you can save state in ajax array...
Hope it help you little....
Another solution is :- Use WP Super Cache plugin...


text:
Q: convert ssom to csom of Adding Document Librarty to Sharepoint 2013 I am trying to convert below code SSOM to CSOM of adding adding Document Library to SharePoint 2013 page.
SSOM
SPFile ofile = web.Getfile("Pages/Home.aspx");
using(SPLimitedWebPartManager wpm = ofile.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
    SPList oList = web.Lists["TestDocument"];
    SPView oView = oList.Views["WebPart"];
    XsltListViewWebPart aWp = new XsltListViewWebPart
    {
        ListName = oList.ID.ToString("B").ToUpper(),
        Title = "Practice Announcements",
        ViewContentTypeId = oView.ContentTypeId.ToString(),
        ViewGuid = oView.ID.ToString("B").ToUpper(),
        Width = "400px",
        ChromeType = PartChromeType.TitleOnly
    };
    wpm.AddWebPart(aWp,"CenterLeftColumn",1);
    oList.Update();
}

Any article, link can be helpful

A: You should use the Webpart XML content for the document library,below XML schema worked with me while I was adding listviewwebparts to a page in CSOM
<?xml version="1.0" encoding="utf-8" ?>
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="ListUrl" type="string">Shared%20Documents</property>
        <property name="MissingAssembly" type="string">Cannot import this Web Part.</property>
      </properties>
    </data>
  </webPart>
</webParts>

Sample code:
            var wpXML = @"<?xml version='1.0' encoding='utf-8' ?>
<webParts>
  <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
    <metaData>
      <type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name='ListUrl' type='string'>Shared%20Documents</property>
        <property name='MissingAssembly' type='string'>Cannot import this Web Part.</property>
      </properties>
    </data>
  </webPart>
</webParts>";

            var page = ctx.Web.GetFileByServerRelativeUrl("/sites/test/SitePages/wiki1.aspx");

            var wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ctx.Load(wpm);
            ctx.ExecuteQuery();

            var importedWebPart = wpm.ImportWebPart(wpXML);
            var webPart = wpm.AddWebPart(importedWebPart.WebPart, "mainContent", 0);
            ctx.ExecuteQuery();


text:
Q: Summing sales across different currencies in SQL This is a follow-up to a previous questions I asked: Using a GROUP BY statement to sum rows. I have a table with sales of different currencies, and I am using a GROUP BY  statement to sum up the numbers per title.
mysql> SELECT
       title,
       SUM(us_earnings_usd) AS usd,
       SUM(cad_earnings_cad) AS cad,
       SUM(uk_earnings_gbp) AS gbp,
       SUM(swedish_earnings_skk) AS skk
       FROM raw_financials
       WHERE date="2012-12-01"
       GROUP BY title

+--------+-----------------+------------------+------------------+------------------+
| title  | us_earnings_usd | cad_earnings_cad |swedish_earnings_ |  uk_earnings_gbp |
+--------+-----------------+------------------+------------------+------------------+
| Gamers |          7.7500 |           4.0000 |           1.0000 |           2.0000 |
+--------+-----------------+------------------+------------------+------------------+

Finally, I need to sum up the fields to get the total sales in USD. For this, I have an additional table called exchange_rates. This is how it can be queried:
mysql> SELECT currency, conversion_to_usd FROM exchange_rates WHERE date="2011-12-01";

+----------+-------------------+
| currency | conversion_to_usd |
+----------+-------------------+
| AUD      |           0.98542 |
| CAD      |           0.95940 |
| CHF      |           1.05235 |
| DKK      |           0.17372 |
| EUR      |           1.29400 |
| GBP      |           1.54223 |
| NOK      |           0.16579 |
| NZD      |           0.74442 |
| SEK      |           0.14190 |
| USD      |           1.00000 |
+----------+-------------------+

How would I combine these using SQL to get:
total_earnings_in_usd = 7.75 (earnings in usd) *1.00 (conversion from usd to usd)
                        + 4.00 (earnings in cad) *0.95 (conversion from cad to usd)
                        + 1.00 (earnings in sek) *0.14 (conversion from sek to usd)
                        + 2.00 (earnings in gbp) *1.54 (conversion from gbp to usd)
                      = $14.77 USD

Update: I have updated the SQL in the question.

A: UPDATED FOLLOWING COMMENT
SELECT  title,
        partner_share_currency,
        SUM(us_earnings_usd) AS usd,
        SUM(cad_earnings_cad) AS cad,
        SUM(us_earnings_usd) + SUM(cad_earnings_cad*CAD) +
        SUM(uk_earnings_gbp*GBP) + SUM(swedish_earnings_skk*SEK) total_earnings_in_usd
FROM raw_financials rf
LEFT JOIN ( SELECT  date,
                    MIN(CASE WHEN  currency = 'CAD' THEN conversion_to_usd END) CAD,
                    MIN(CASE WHEN  currency = 'GBP' THEN conversion_to_usd END) GBP,
                    MIN(CASE WHEN  currency = 'SEK' THEN conversion_to_usd END) SEK
            FROM exchange_rates
            WHERE currency IN ('CAD','GBP','SEK')
            GROUP BY date) er
ON rf.date = er.date
WHERE title LIKE '%Gamers%' AND rf.date= '2012-12-01'
GROUP BY title

A: I tested the SQL(T-SQL in SQL Server) below. It returns 11.5876 as grand_total. Is this okay for you?
create table #raw_financials (
    title varchar(20)
    ,partner_share_currency varchar(20)
    ,us_earnings_usd decimal(15, 5)
    ,cad_earnings_cad decimal(15, 5)
    ,date datetime
)
insert into #raw_financials values ('Gamers', 'USD', 3.25, 0, '2012-12-01')
insert into #raw_financials values ('Gamers', 'CAD', 0, 4, '2012-12-01')
insert into #raw_financials values ('Gamers', 'USD', 4.5, 0, '2012-12-01')

create table #exchange_rates (
    currency varchar(20)
    ,conversion_to_usd decimal(15, 5)
    ,date datetime
)
insert into #exchange_rates values ('CAD', 0.95940, '2012-12-01')
insert into #exchange_rates values ('USD', 1, '2012-12-01')

SELECT
rf.title,
--partner_share_currency,
SUM((rf.us_earnings_usd + rf.cad_earnings_cad) * er.conversion_to_usd) AS grand_total
FROM #raw_financials rf
INNER JOIN #exchange_rates er
ON er.currency = rf.partner_share_currency
AND er.date = rf.date
WHERE rf.title LIKE '%Gamers%' AND rf.date='2012-12-01'
GROUP BY rf.title

But I have never used MySQL, so the result might be different.
Update: Here is another query for GBP and SEK. It returns 14.81396 in my T-SQL:
create table #raw_financials (
    title varchar(20)
    ,partner_share_currency varchar(20)
    ,us_earnings_usd decimal(15, 5)
    ,cad_earnings_cad decimal(15, 5)
    ,uk_earnings_gbp decimal(15, 5)
    ,swedish_earnings_skk decimal(15, 5)
    ,date datetime
)
insert into #raw_financials values ('Gamers', 'USD', 3.25, 0, 0, 0, '2012-12-01')
insert into #raw_financials values ('Gamers', 'CAD', 0, 4, 0, 0, '2012-12-01')
insert into #raw_financials values ('Gamers', 'USD', 4.5, 0, 0, 0, '2012-12-01')
insert into #raw_financials values ('Gamers', 'GBP', 0, 0, 2, 0, '2012-12-01')
insert into #raw_financials values ('Gamers', 'SEK', 0, 0, 0, 1, '2012-12-01')

create table #exchange_rates (
    currency varchar(20)
    ,conversion_to_usd decimal(15, 5)
    ,date datetime
)
insert into #exchange_rates values ('CAD', 0.95940, '2012-12-01')
insert into #exchange_rates values ('USD', 1, '2012-12-01')
insert into #exchange_rates values ('GBP', 1.54223, '2012-12-01')
insert into #exchange_rates values ('SEK', 0.14190, '2012-12-01')

SELECT
rf.title,
SUM((rf.us_earnings_usd +
     rf.cad_earnings_cad +
     rf.uk_earnings_gbp +
     rf.swedish_earnings_skk
    ) * er.conversion_to_usd) AS grand_total
FROM #raw_financials rf
INNER JOIN #exchange_rates er
ON er.currency = rf.partner_share_currency
AND er.date = rf.date
WHERE rf.title LIKE '%Gamers%' AND rf.date='2012-12-01'
GROUP BY rf.title

A: SELECT
    t.title,
    t.usd,
    t.cad,
    t.gbp,
    t.skk,
    t.usd + t.cad*er_cad.conversion_to_usd + t.gbp*er_gbp.conversion_to_usd + t.skk*er_skk.conversion_to_usd AS total
FROM
(
    SELECT
        title,
        SUM(us_earnings_usd) AS usd,
        SUM(cad_earnings_cad) AS cad,
        SUM(uk_earnings_gbp) AS gbp,
        SUM(swedish_earnings_skk) AS skk,
        FROM raw_financials
        WHERE date="2012-12-01"
        GROUP BY title
) t
INNER JOIN exchange_rates er_cad ON er_cad.date = t.date and er_cad.currency = 'CAD'
INNER JOIN exchange_rates er_gbp ON er_gbp.date = t.date and er_gbp.currency = 'GBP'
INNER JOIN exchange_rates er_skk ON er_skk.date = t.date and er_skk.currency = 'SKK'

Anyways, I think that there is something wrong with your sales table. You should have only one earnings column (not a separate one for each currency). As you see, for each row you have to fill only one column with an actual value and the rest are zero. It will be enough to have the partner_share_currency column and a generic earnings column.


text:
Q: Showing that these two rings $\frac{R[T]}{(aT-1)}, R[a^{-1}]$ are isomorphism. Let $R$ be an integral domain and $0 \neq a \in R$. I need to show that:
$$\frac{R[T]}{(aT-1)} \cong R[a^{-1}].$$
My Works:
Let us define the ring homomorphism $\phi: R[T] \to R[a^{-1}]$ which is defined by $T \mapsto a^{-1}$. It is easy to show that $\phi$ is an epimorphism and $(aT-1) \subset \mathrm{ker} (\phi)$. I do not know how to get the inverse inclusion. In the case that $R$ is a field, we may use the Euclidean algorithm to show that every $g \in \mathrm{ker} (\phi)$ is a multiple of $aT-1$. But since $R$ is not a field, I do not know how to show that $g$ must be a multiple of $aT-1$.
Thanks for your help.


text:
Q: Convert Shell script to json how do i save shell script output to a json file? I need to convert to json to be able to send to WooCommerce.

username=USER
passwd=PASS
dominio=DOMAIN

json=$(curl -s -X POST \
  --data-urlencode "client_id=modulo-retaguardaview" \
  --data-urlencode "client_secret=bd82bd01-e543-4531-bb53-794196595426" \
  --data-urlencode "username=${username}" \
  --data-urlencode "password=${passwd}" \
  --data-urlencode "grant_type=password" \
https://auth.cliente.com.br/auth/realms/GERA/protocol/openid-connect/token) \
&& token=$(echo $json | sed "s/{.*\"access_token\":\"\([^\"]*\).*}/\1/g") \
&& echo "Token gerado com sucesso!"

curl --location --request GET "https://${dominio}.cliente.com.br/pdvcore/api/v1/ecommerce/produtos" \
--header "Authorization: Bearer ${token}"```


text:
Q: How would one convert a UUID type to ULID type? Theres a bit documentation out there how to convert ULID to UUID but not so much when you need to convert UUID to ULID.
I'm looking at this UUID / ULID generator / converter https://www.ulidtools.com/
but I'm not quite sure how I would replicate the UUID to ULID conversion, the source is too obfuscated for me to understand.
I'm not sure where to even begin, is this conversion even safe ? will it guarantee a unique conversion ?

A: Pure Javascript Method for conversion:
Converting a UUID to a ULID guarantee a unique code. ULIDs are unique 128-bit identifiers that are generated based on a combination of the current timestamp.
function convertUUIDtoULID(uuid) {
  const uuidBinary = uuid.split("-").map((hex) => parseInt(hex, 16));
  return uuidBinary
    .slice(0, 8)
    .map((byte) => byte.toString(32))
    .concat(uuidBinary.slice(8).map((byte) => byte.toString(32)))
    .join("");
}

const uuid = "454391df-b950-42ea-a2c0-92d62c215d67";
const ulid = convertUUIDtoULID(uuid);
console.log(ulid);

*

*The function takes in a string of UUID format as an input

*It splits the UUID string at each "-" character and converts each
resulting hexadecimal string into a decimal number using the
parseInt() function with base 16.

*It creates a new array of the first 8 decimal numbers from the UUID
and converts each number to a base-32 string using the toString()
function with base 32.

*It concatenates this array with a new array of the remaining decimal
numbers from the UUID, also converted to base-32 strings.

*The resulting array of base-32 strings is joined together into a
single string, which is returned as the ULID.

*The example UUID string is passed into the function and the resulting
ULID string is logged to the console.

You can also use [https://www.npmjs.com/package/ulid] for converting UUID to ULID

A: I've had the same issue and I took a look at ulidtools.com then after digging into its source code for a while I found that it uses this package behind the seen.
import pkg from "id128";
const { Ulid, Uuid4 } = pkg;

const ulid = Ulid.generate();
const ulidToUuid = Uuid4.fromRaw(ulid.toRaw());
const uuidToUlid = Ulid.fromRaw(ulidToUuid.toRaw());

console.table([
  {
    generated_ulid: ulid.toCanonical(),
    converted_to_uuid: ulidToUuid.toCanonical(),
    converted_back_to_ulid: uuidToUlid.toCanonical(),
  },
]);


text:
Q: Avoid Initializing New ComponentDesigner in System.Windows.Forms I'm currently trying to build a non visual Component with its custome Component Designer, and wonder if there is any way to detect if the component already added to the design surface (i.e Form) and also how to force the component not added itself again in Design Time, here is what i did so far.
Public Class TestComponentDesigner
Inherits ComponentDesigner

Private Sub DoNotAllowInitializingNewComponent()
    Dim testComp As TestComponent = CType(MyBase.Component, TestComponent)
    Dim host As IDesignerHost = TryCast(testComp.Site.GetService(GetType(IDesignerHost)), IDesignerHost)
    Dim testComponentType As Type = GetType(TestComponent)
    If host IsNot Nothing AndAlso host.Container Is testComp.Owner Then
        Dim designer As ComponentDesigner = TryCast(host.GetDesigner(testComp.Owner), ComponentDesigner)
        If designer IsNot Nothing Then

            ' The Problem ?????????????????????????????????????????????????????????
            ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            ' get the owner associated component collection
            For Each currentComponent As IComponent In designer.AssociatedComponents
                If currentComponent.Site IsNot Nothing Then
                    ' Allow to Add a new session of Test Component
                    ' Example Only
                    ' ?????????????????????????????
                    testComp.Owner.AllowDrop = False
                Else
                    ' Do not allow to added a new session of TestComponent
                    ' Example Only
                    ' ?????????????????????????????
                    testComp.Owner.AllowDrop = True
                End If

            Next

            ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        End If
    End If
End Sub

End Class

A: Using a designer to enforce this rule is the wrong way to go about it.  It is not that you can't do it, just iterate the IDesignerHost.Container.Components collection and count the number of components that are of the type of your class.  And throw an exception when you are unhappy.  For example:
Public Overrides Sub InitializeNewComponent(defaultValues As IDictionary)
    Dim testComp = DirectCast(MyBase.Component, TestComponent)
    Dim host = DirectCast(Me.GetService(GetType(IDesignerHost)), IDesignerHost)
    Dim count = 0
    For Each comp As Component In host.Container.Components
        If comp.GetType() = GetType(TestComponent) Then
            count += 1
            If count > 1 then Throw New Exception("Sorry, only one TestComponent permitted")
        End If
    Next
    MyBase.InitializeNewComponent(defaultValues)
End Sub

But the message the programmer sees is very ugly.  You should get involved earlier and prevent the component instance from being created in the first place.  You need your own ToolBoxItem so you can display your own message and simply not create the component in an overload for the CreateComponentsCore() method.
No need for me to show you how to do this, the MSDN article for ToolBoxItem already has all the code you need for that.


text:
Q: size of time_t and its max value #include <stdio.h>
#include <time.h>

int main()
{
     printf("Size of time_t is %lu bytes.\n", sizeof(time_t));
     time_t biggest = 0x7fffffffffffffff;   // line 1
     printf("time_t's wrap around will be a second after %s.\n", asctime(gmtime(&biggest)) );

     return 0;
}

In time.h is this the definition of time_t ?
typedef  __darwin_time_t   time_t

How to interpret it ? Since I don't have any idea, I used the sizeof function to find that time_t = 8 bytes.
Why line 1 is giving error then ?
I'm getting this error
Segmentation fault: 11

A: Your call to gmtime() is probably returning NULL (it does on my Mac OS X system). When you pass this value to asctime(), you get an exception (since it expects a non-NULL pointer).
Not all time_t values can be represented in a struct tm, which is why gmtime() returns NULL in this case.

A: Although the size of time_t is 8, on a 64 bit platform there are implementation-defined limits hard-coded into the runtime that cannot be exceeded. When those limits are exceeded gmtime will return NULL with errno set to indicate the nature of the error. Your code fails to check for NULL return from gmtime, therefore asctime fails when it tries to dereference that null pointer. This is the hazard you risk when using idiomatic C and not checking return values from functions that can fail.
The Microsoft C gmtime on Windows 10 returns NULL with errno set to EINVAL when passed 32535291600. Even though one might think the theoretical maximum limit ought to be LLONG_MAX. Microsoft explicitly sets the limit to _MAX__TIME64_T + _MAX_LOCAL_TIME.
From ctime.h in Microsoft Visual Studio 2010 CRT sources:
#define _MAX__TIME64_T 0x793406fffi64 /* number of seconds from 00:00:00, 01/01/1970 UTC to 23:59:59. 12/31/3000 UTC */

Apple's gmtime function returns NULL and errno set to EOVERFLOW when it's passed 67768036191676800. The Apple implementation exhibits undefined behavior for all times where asctime() returns a string with more than 4 digits in the year because the C standard requires the function to return no more than 26 characters.

A: I looked into the Linux header files and found the following things:
/usr/include/time.h:
    typedef __time_t time_t;

/usr/include/bits/types.h:
    __STD_TYPE __TIME_T_TYPE __time_t

/usr/include/bits/typesizes.h
    #define __TIME_T_TYPE       __SLONGWORD_TYPE

/usr/include/bits/types.h:
    #define __SLONGWORD_TYPE    long int

So the size of time_t is long int. On a 64 bit machine, you probably get 8 bytes.
Then I found that on my FreeBSD, which is 32 bit, it looked like this:
/usr/include/machine/_types.h:
    typedef __int32_t   __time_t;

So the size is 32 bits.

A: The underlying type of time_t can be anything. It greatly depends on your system. Please refer to a similar question: What primitive data type is time_t?.
There is a link in the thread to the description of sys/types.h where it's stated that

time_t and clock_t shall be integer or real-floating types.

One more link to a good answer: https://stackoverflow.com/a/471287/276274


text:
Q: Using Optional to avoid NPE I'm trying to avoid checking (if ... != null) or try{...}catch(NullPointerException e) {...}
Let's take an example to understand my issue :
I have a class Park containing List<Car>
I have a class Car containing a Motor object
I have a class Motor containing a Name String value
I want to return the first String motor name from my Park class :
I want to avoid :
if (park != null) {
    if (park.getCars() != null) {
        for (Car car : park.getCars() {
              if (car.getMotor() != null) {
                  return car.getMotor().getName();

I was thinking of something like this :
Optional.ofNullable(park).map(Park::getCars).ifPresent(cars -> {
    return cars.stream().map(Car::getMotor).map(Motor::getName).findFirst().orElse(null);
});

but it does not compile. Any ideas ??

A: Assuming you are limited to java 8, you can use this:
    public String findFirstMotorName(Park park) {
        return Optional.ofNullable(park)
            .map(Park::getCars)
            .map(
                cars -> cars.stream().map(Car::getMotor).map(Motor::getName).findFirst().orElse(null)
            )
            .orElse("No Motors Found");
    }

In later versions you can also turn an Optional to a Stream, which makes things a tad more fluent.

A: Optional.ifPresent() has void as return type, so you can not return a result in the function. You can use Optional.stream() and Stream.flatMap() instead:
return Optional.ofNullable(park) // Optional<Park>
        .map(Park::getCars).stream() // Stream<List<Car>>
        .flatMap(List::stream) // Stream<Car>
        .map(Car::getMotor) // Stream<Motor>
        .filter(Objects::nonNull) // Stream<Motor>
        .map(Motor::getName) // Stream<String>
        .findFirst() // Optional<String>
        .orElse(null);

Alternatively (if you can not use Optional.stream()) you can use Optional.flatMap() with the code you already have:
return Optional.ofNullable(park) // Optional<Park>
        .map(Park::getCars) // Optional<List<Car>>
        .flatMap(cars -> cars.stream() // Stream<Car>
                .map(Car::getMotor) // Stream<Motor>
                .filter(Objects::nonNull) // Stream<Motor>
                .map(Motor::getName) // Stream<String>
                .findFirst()) // Optional<String>
        .orElse(null);


text:
Q: Create a Empty Wish-list Button in magento 1.9 i want to create a empty wishlist button in wishlist page, so that when user click the button all the items from the wishlist are removed. how can i do that please help.

A: Example of adding button in wishlist, change button as per your need
<wishlist_index_index>
    <reference name="customer.wishlist.buttons">
        <block type="wedding/customer_wishlist_button" name="customer.wishlist.button.gifts" template="wedding/button/gifts.phtml" />
    </reference>
</wishlist_index_index>

You need to add separate controller action on this button click

Code of empty Wishlist

if (Mage::getSingleton('customer/session')->isLoggedIn()) {
 $customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();

$itemCollection = Mage::getModel('wishlist/item')->getCollection()
                    ->addCustomerIdFilter($customerId);
    foreach($itemCollection as $item) {
            $item->delete();
    }
}

I hope this will help


text:
Q: The value of . (dot) in the Maven Antrun plugin In Ant, the . can be used to reference a base directory. I have a legacy project with one Ant file in the /build directory calling an Ant file in the /src directory (in this post I use /for relative directories to the project directory).
Now when I execute the Ant file in the /build directory, . is /build and when the process flows to the Ant file in /src the value of . in that file is /src.
Now I try to wrap the whole build in Maven. I put a pom.xml into the main directory and called the build file by
<ant antfile="cbuild.xml" dir="./build" target="all" />

In cbuild.xml, the value of . is /build, but in the build file in /src  the . now evaluates to /build as well.
How does this happen? Can I do anything about it?


text:
Q: Query group sum with cross apply Running this query:
select rpid, SUM(AMOUNT) AS AMOUNT, MIN(p.oid) as HomeID from LEDGER
cross apply
(select top 1 p.oid
from dbo.patient as p
where p.rpid = ledger.rpid
order by p.oid) AS p
group by RPID
order by rpid

I pieced this together from two different queries, that work individually but when combined returns no results.
I want to group PATID and SUM(AMOUNT) from the ledger table, but add the OID from the patient table to the result that matches on the RPID column. I am fine taking ANY matching OID (between RPID in ledger and RPID in patient tables) as RPID only exists once in the patient table - this is why I used the MIN function but it could be anything.
EXAMPLE:
LEDGER TABLE

RPID    AMOUNT
100      25
100      30
100      30
110      50
110      50

PATIENT TABLE

RPID    OID
100     10
110     20

RESULT

RPID    AMOUNT    OID
100     85        10
110     100       20

A: If the result you want is:
RPID    AMOUNT    OID
100     85        10
110     100       20

then a simple join between the tables and a sum of amount would get you that:
select
    l.rpid,
    sum(l.amount) as amount,
    p.oid as HomeID
from ledger as l
join dbo.patient as p on p.rpid = l.rpid
group by l.RPID, p.OID

There's no need to use apply at all.

A: You can change CROSS APPLY to JOIN: http://sqlfiddle.com/#!6/5273c/4
select l.rpid, sum(l.amount) as amount, min(p.oid) as HomeID
from ledger l
join patient p on l.rpid = p.rpid
group by l.rpid
order by l.rpid

But version with CROSS APPLY also works:  http://sqlfiddle.com/#!6/5273c/1


text:
Q: Creating .eps file with spplot in R I'm trying to create high resolution figures from maps I created in R. Whenever I try creating an .eps file with spplot it creates a relatively large file (~13,040 KB) that I cannot open with Adobe Illustrator. Here is an example of something I've tried that produced such a file:
postscript("60plot789.eps",horizontal = TRUE, onefile = TRUE, paper =
           "special")
 print(spplot(mi.ok.15.7[c('pred15.9','pred18.9','pred24.9','pred36.9','pred48.9','pred72.9',
                 'pred15.8','pred18.8','pred24.8','pred36.8','pred48.8','pred72.8',
                 'pred15.7','pred18.7','pred24.7','pred36.7','pred48.7','pred72.7')],
    col.regions=RHCols(20), sp.layout=list(pts, border), names.attr=names789,
    par.strip.text = list(cex = 0.75),
    scales=list(draw = FALSE), layout=(mat),
    main=paste("RH OK Results (60% RH): 15,18,24,36, 48, 72 hours, Biweeks 7,8,9"),
    colorkey = list(at = c(0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100),
                    labels = list( at =  c(0,10,20,30,40,50,60,70,80,90,100),
                                   labels = c('0','10','20','30','40','50','60','70','80','90','100')
                    ))))
dev.off()

Is there a way I can create .eps files using spplot that can be opened in Adobe Illustrator? Or would it be better to use a different file type for high resolution images? (300, 600 dpi)?
Thanks!


text:
Q: Warning: task "JSHint" not found I am new to programming and have been working through Steven Foote's book "Learning to Program." I am on chapter 4 and have installed Node, npm, and grunt (I think).
I am at the point where I should be running JSHint to test that everything has been installed correctly but I am getting the following error:
command line error
Here you can see my files:
Gruntfile.js
module.exports = function(grunt) {
    // Project Configuration
    grunt.initConfig({
        concat: {
            release: {
                src: ['js/values.js', 'js/prompt.js'],
                dest: 'release/main.js'
            }
        },
        copy: {
            release: {
                src: 'manifest.json',
                dest: 'release/manifest.json'
            }
        },
        jshint: {
            files: ['js/values.js', 'js/prompt.js']
        }
    })

    // Load Grunt Pluggins
    grunt.loadNpmTasks['grunt-contrib-concat'];
    grunt.loadNpmTasks['grunt-contrib-copy'];
    grunt.loadNpmTasks['grunt-contrib-jshint'];

    // Register Tasks
    grunt.registerTask('default', ['jshint', 'concat', 'copy']);

};

package.json
{
    "name": "KittenBook",
    "version": "0.0.1",
    "devDependencies": {
        "grunt": "~0.4.2",
        "grunt-contrib-concat": "~0.3.0",
        "grunt-contrib-jshint": "~0.6.3",
        "grunt-contrib-copy": "~0.5.0"
    }
}

As I said, I am still new to programming, so I don't know what else I need to provide, however I have seen another post similar to what I am wanting to know, but the answers didn't help me. Here is a link to this post: Grunt/JSHint installation error

A: I found a solution after all. I followed the instructions at http://www.codereadability.com/jshint-with-grunt/
I also found the preferences tab and now I know how to copy/past from the cmd line, woohoo.


text:
Q: Razer Blade | Glitchy Screen & Horizontal Lines & Black Screen When There's No Input TL;DR: This Razer Blade's screen goes all glitchy, followed by a black screen if there is no input. 100% Hardware problem that started slowly occuring over time. Check out the images and the videos.
The issues with the display started at least 2 years ago but it was only a few horizontal lines on the screen that were visible on certain colors like orange, so it wasn't a big deal. With time, they basically multiplied, some of them were more visible than others and they were everywhere on the screen. I found an image that is very similar to mine posted by someone else.
A couple of months ago I started having another issue: The screen would go all glitchy and then black unless there was something moving in the screen like a pointer or a movie playing. Though, it didn't take me long to find a solution to that, which was to hit Ctrl+Shift+Win+B, restarting the graphics driver and effectively resolving the issue. The lines were still there. It occured a few times a day but the key combination was quick to solve it, so I didn't bother much with it either, plus these were the busiest times of my life.
A few days ago, I saw a new line on the screen but this time it was green and thicker, which was visible regardless of the background color. Hours, or might even be minutes, later I started seeing the glitch effects, leading to a completely black screen. This time moving something on the screen or pressing keys on the keyboard did not help at all, in fact, it just brought back the glitches. I was still seeing tiny bits on the screen well enough to log in but 2 seconds after I stopped typing, the screen would go back to black. This is how it is at the moment.
I am writing this post on my laptop plugged into an external monitor via HDMI. The screen works as expected for a few seconds after I plug it out, but it soon goes back to its faulty state. I can confirm that it has to do with either the laptop's screen or the Intel GPU (which I doubt) as I don't see any lines when I connect it to an external display and I still had the same issues on both Windows and 2 different Linux distributions.
Video 2
The laptop is a Razer Blade 14" (2017) with no touchscreen. It has a dedicated Nvidia GTX 1060 GPU and an integrated Intel 630 GPU. Only the Nvidia GPU's output goes through HDMI. I am not sure whether it is the monitor that's faulty or the integrated GPU but I did some tests where I set the dedicated GPU to be used globally in Nvidia Control Panel and ran Adobe After Effects: I'd still be getting same glitches followed by a black screen.
I unscrewed the laptop's back panel and noticed a few things there. One of them being that the laptop's battery is bloated at this point. Take a look at the pictures in this post and please let me know if you think you know what's wrong wtih it. I myself found a wire that was, I'm guessing, supposed to be soldered but it's hanging out. I also have to add that it's strange when the screen isn't always glitchy but it takes a few seconds either after a reboot or plugging out the HDMI cable (just counted and it took 30 seconds this time).
Overall
Wire
There are more images but it does not allow me to individually link them here because I don't have enough reputation. Please do take a look at this album.
I had issues with charging before, it didn't charge at all. Apparently a piece inside had burned. I took it to a repair shop and I don't know what the guy did but you can see that there's something different between the two images:
before repair
I think I found a related iFixit thread that says it is the DC-IN socket. Would it affect the screen? Is there any way I can make sure the GPU works fine?


text:
Q: Facebook Customer Chat Plugin not showing when using mobile data I've been using Wordpress Facebook Customer Chat Plugin and it was working perfectly until we tried checking using mobile data and it didn't show, we tried it on different devices using both WiFi and mobile data and it only shows when using WiFi is there a way to avoid this issue?
this is my current code:

A: There is no relation between using wifi or mobile data so your issue is most likely related to requests being blocked on mobile (firewall/proxy, ad blocker apps or similar) or the mobile browser you try to test this with. Customer Chat Plugin only works on latest mobile browsers and does not work on Facebook's in-app-browser.


text:
Q: WPF How do I setup proper data binding (XPath) on a textbox with an XML element or attribute? Good day,
I've been trying to crack this for several days now to no avail.
I have a xml file and I'm trying to bind it's elements and attributes in a dynamic way to various textbox controls. I've tried different ways of going at this and but they've all failed.
This last attempt is with
<UserControl x:Class="L5RCharacterManager.CharacterHeaderControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:L5RCharacterManager"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="800">

    <Grid>
        <Grid>
            <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
            <Grid.Resources>
                <XmlDataProvider x:Key="data" Source="myXmlFile"/>
            </Grid.Resources>
            <Label Content="Clan" Grid.Column="0" Grid.Row="0" />
            <TextBox Grid.Column="1" Grid.Row="0">
                <TextBox.Text>
                    <Binding Source="{}" XPath="root/element/attribute" />
                </TextBox.Text>
            </TextBox>

Thanks for you time.
Edit: a quick sample of the xml document I'm trying to bind.
<?xml version="1.0" encoding="utf-8"?>
<root>
  <element1 attr11="Scorpion" attr12="" attr13="" attr14="" />
  <elements2>
    <element21 name="twentyone" value="21">
      <subElement1a name="twentyoneA" />
      <subElement2b name="twentyoneB" />
    </element21>
    <element22 name="twentytwo" value="22">
      <subElement1a name="twentytwoA" />
      <subElement2b name="twentytwoB" />
    </element22>
   </elements2>
</root>

A: Examples:
        <StackPanel.Resources>
            <XmlDataProvider x:Key="xmlData" Source="myXmlFile.xml"/>
        </StackPanel.Resources>
        <TextBox Text="{Binding XPath=root/element1/@attr11, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
                 Source={StaticResource xmlData}}"/>
        <TextBox Text="{Binding XPath=root/element1/@attr12, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
                 Source={StaticResource xmlData}}"/>

    <StackPanel>
        <StackPanel.DataContext>
            <XmlDataProvider Source="myXmlFile.xml"/>
        </StackPanel.DataContext>
        <TextBox Text="{Binding XPath=root/element1/@attr11, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox Text="{Binding XPath=root/element1/@attr12, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </StackPanel>

But the editing results will not be automatically saved.
To do this, when you close the Window, get the XmlDataProvider and explicitly save it XML.
An example that implements the saving of editing results.
    public static class Handlers
    {
        public static EventHandler SaveXmlOnClosed { get; } = (s, e) =>
        {
            Window window = (Window)s;

            XmlDataProvider provider = (XmlDataProvider)window.Resources["xmlData"];

            string file = provider.Source.OriginalString;

            provider.Document.Save(file);
        };
    }

<Window ----------------------
        ----------------------
        Closed="{x:Static local:Handlers.SaveXmlOnClosed}">
   <Window.Resources>
            <XmlDataProvider x:Key="xmlData" Source="myXmlFile.xml"/>
    </Window.Resources>
    <StackPanel>
        <TextBox Text="{Binding XPath=root/element1/@attr11, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
                 Source={StaticResource xmlData}}"/>
        <TextBox Text="{Binding XPath=root/element1/@attr12, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,
                 Source={StaticResource xmlData}}"/>
    </StackPanel>
</Window>


text:
Q: Remove duplicates using column value with some ignore condition I have two columns in my excel file and I want to remove duplicates from 'A' column with an ignore condition. The columns are as follow:
A B
1 10
1 20
2 30
2 40
3 10
3 20

Now, I want it to turn into this:
A B
1 10
2 30
2 40
3 10

So, basically I want to remove all duplicates except when column 'A' has value 2 (I want to ignore 2). My current code is as follows but it does not work for me as it removes duplicates with value '2' too.
df = pd.read_excel(save_filename)
df2 = df.drop_duplicates(subset=["A", "B"], keep='first')
df2.to_excel(save_filename, index=False)

A: You can use two conditions:
df[~df.duplicated(subset="A") | df["A"].eq(2)]

   A   B
0  1  10
2  2  30
3  2  40
4  3  10


text:
Q: Characterisation of reflexive modules Let $A$ be a semiperfect noetherian ring.
A module $M$ is called reflexive in case the canonical map $f_M: M^{**} \cong M$ is an isomorphism, when $(-)^{*}:=Hom_A(-,A)$. This is equivalent to say that $Ext_A^i(Tr(M),A)=0$ for $i=1,2$ when $Tr$ denotes the Auslander-Bridger duality.
Question: Assume $M$ is finitely presented. Is $M$ reflexive iff $M^{**} \cong M$? (You are welcome to give example for any kind of ring, I know none)
This should be true for Artin algebras:
Assume $M^{**} \cong M$. We have $M^{**} \cong \Omega^2 Tr \Omega^2 Tr(M)$ and thus $M \in \Omega^1(mod-A)$ and thus $M$ is torsionfree, which is equivalent to $f_M$ being injective. But $M^{**} \cong M$ gives us that the modules have the same length and thus $f_M$ is even an isomorphism and $M$ is relfexive.
In the book of Auslander and Bridger I found that this should also be true in case the ring is additionally commutative Gorenstein (we dont need semiperfect here).
Remark with regards to the previous (deleted) thread:
I decided to split up the bigger confusing thread into smaller questions to make things less confusing.

A: This is true even with weaker assumptions (finitely generated modules for Noetherian rings, or for non-Noetherian semiperfect rings).
If $M\cong M^{**}$ then $M$ is a dual, and for any dual the natural map $M\to M^{**}$ is a split monomorphism, so if $M$ is not reflexive then $M\cong M\oplus N$ for some non-zero $N$.
This is not possible if $M$ is a Noetherian module, since $M$ would have an increasing chain of submodules $N< N\oplus N<N\oplus N\oplus N<\dots$.
It's also not possible if $M$ is finitely generated and $A$ is semiperfect, since then $M/MJ(A)\cong M/MJ(A)\oplus N/NJ(A)$ are finite direct sums of simple modules, so Krull-Schmidt can be applied.


text:
Q: How to set a default value to a column in .Net 3.1 when I create my column So I am using .Net 3.1, and I have the following class:
public Addresses{
        public int AddressID { get; set; }
        public String Name {get; set;}
}

and I want to add a new Column to it like this
public Addresses{
        public int AddressID { get; set; }
        public String Name {get; set;}
        public bool IsAddrLocal {get; set;}
}

but I want the new column IsAddrLocal to have a default value of True for all columns that have already been created in the database.
I tried adding doing this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CompanyShippingAddress>(entity =>
            {
                entity.Property(x=>x.IsAddrLocal).HasDefaultValue(true);

            });
}

however it would cause my values to be always true (even the new ones being entered) so I tried to make the field nullable
public Addresses{
        public int AddressID { get; set; }
        public String Name {get; set;}
        public bool? IsAddrLocal {get; set;}
}

Which would cause old addresses to have the value NULL assigned to them and only new ones have the True value assigned to them.
I tried adding a constructor to the class and making the field non-nullable again
        public Addresses()
        {
            IsAddrLocal= true;
        }

but this would cause old addresses to get a value of False and new ones a value of True.
How can I make the default value of this field True for new and old values unless later on a User sends a request to update the field for a specific row to false?

A: From your description, your question is that when adding the IsAddrLocal property, you want to set the default value to true, then the new address without set the IsAddrLocal property and the existed Address in the database should also set the default value. But if the new address has the IsAddrLocal property, it should store its value.
To solve this issue, you can try to use the following method:
Assume you have create the Address table with two columns: AddressID and Name, and insert some value.

*

*Add the IsAddrLocal property in the Addresses model.
 public class Addresses
 {
     [Key]
     public int AddressID { get; set; }
     public string Name { get; set; }

     public bool IsAddrLocal { get; set; } = true; //set the default value.
 }

[Note]There is no need to use the HasDefaultValue to set the default value. Remove this part of code from the OnModelCreating method.

*Execute the Add-Migration adddefaultvaluerul command to generate the migration file.

*Open the adddefaultvaluerul migration file, in the Up method, change the defaultvalue from false to true.

*Execute the update-database comment, then you can see the existed Address has been set the default value.

*Then, when you insert new address, like this:
     var items = new List<Addresses>()
     {
         new Addresses(){ Name="A1", IsAddrLocal=false },
         new Addresses(){ Name="A2"},
         new Addresses(){ Name="A3" ,IsAddrLocal=false },
     };
     _dbcontext.Addresses.AddRange(items);
     _dbcontext.SaveChanges();

the output as below:


text:
Q: How do I perform a XOR calculation of two binary numbers in excel 2007 I wanted to perform a XOR calculation of two Binary numbers for example: on Sheet 1
Range A1 = 10101010
Range A2 = 11100010

Now I need to perform XOR of A1, A2 result in A3. I tried different formula's two perform XOR calculations like: A1^A2, (BITXOR (A1, A2)) but unfortunately it didn't worked I think because I am using excel 2007 "XOR" doesn't support.
I'm expecting a result of 1001000.

A: First, you should note that Excel pre-Excel2013 has no bitwise operators or functions built-in (Excel's OR() function is logical even if the operands are numeric). Excel 2013 finally adds this glaringly missing functionality.
Using VBA
The simplest way is to create a User Defined Function that does it. Formulae can work if you are prepared for either a decimal output, or helper columns, or a very repetitive Concatenate formula but VBA gets around these limitations - I recommend it if you are able to have code in the workbook.
Decimal Input, Decimal Output
The below examples just expose the built-in bitwise operators to use as functions in Excel formulae. I assume an integral type, although you could change it to accept decimals etc.
You can convert your string binary numbers (e.g. "1010") to decimals (10, for the previous example) using the BIN2DEC() function built-in to Excel, although this only handles 9 bits + sign bit, alternatively you can use an array formula to convert it for you (see my section on "Using Formulas" below).
Public Function BITWISE_OR(operand1, operand2)
   BITWISE_OR = CLng(operand1) Or CLng(operand2)
End Function
Public Function BITWISE_AND(operand1, operand2)
   BITWISE_AND = CLng(operand1) And CLng(operand2)
End Function
Public Function BITWISE_XOR(operand1, operand2)
   BITWISE_XOR = CLng(operand1) Xor CLng(operand2)
End Function

Converting the numeric results back to binary strings is pretty annoying with formulas - if you need more than the range covered by DEC2BIN() (a paltry -512 to +511) function built in to Excel then I would suggest either using VBA (see below), or building up your binary string bit by bit using columns or rows (see my Using Formulas section below).
Binary string input, Binary string output
The below essentially iterates through a string setting each bit in turn based on the corresponding bits in the input strings. It performs the bit changes on the string in-place using Mid$ statement. Bit strings can be arbitrary length.
The below looks complicated but really it is the same basic stuff repeated 3 times for each of And, Or and XOr.
'str1, str2: the two bit strings. They can be different lengths.
'significantDigitsAreLeft: optional parameter to dictate how different length strings should be padded. Default = True.
Public Function Bitstr_AND(str1 As String, str2 As String, Optional significantDigitsAreLeft As Boolean = True)
    Dim maxLen As Long, resStr As String, i As Long
    If Len(str1) > Len(str2) Then maxLen = Len(str1) Else maxLen = Len(str2) 'get max length of the two strings
    str1 = getPaddedString(str1, maxLen, significantDigitsAreLeft) 'pad left or right to the desired length
    str2 = getPaddedString(str2, maxLen, significantDigitsAreLeft) 'pad left or right to the desired length
    resStr = String$(maxLen, "0") 'prepare the result string into memory (Mid$ can operate without creating a new string, for performance)
    For i = 1 To maxLen
        If Mid$(str1, i, 1) = "1" And Mid$(str2, i, 1) = "1" Then
            Mid$(resStr, i, 1) = "1" 'in-place overwrite of the existing "0" with "1"
        End If
    Next i
    Bitstr_AND = resStr
End Function
'For explanatory comments, see Bitstr_AND
Public Function Bitstr_OR(str1 As String, str2 As String, Optional significantDigitsAreLeft As Boolean = True)
    Dim maxLen As Long
    Dim resStr As String
    Dim i As Long
    If Len(str1) > Len(str2) Then maxLen = Len(str1) Else maxLen = Len(str2)
    str1 = getPaddedString(str1, maxLen, significantDigitsAreLeft)
    str2 = getPaddedString(str2, maxLen, significantDigitsAreLeft)
    resStr = String$(maxLen, "0")
    For i = 1 To maxLen
        If Mid$(str1, i, 1) = "1" Or Mid$(str2, i, 1) = "1" Then
            Mid$(resStr, i, 1) = "1"
        End If
    Next i
    Bitstr_OR = resStr
End Function
'For explanatory comments, see Bitstr_AND
Public Function Bitstr_XOR(str1 As String, str2 As String, Optional significantDigitsAreLeft As Boolean = True)
    Dim maxLen As Long
    Dim resStr As String
    Dim i As Long
    If Len(str1) > Len(str2) Then maxLen = Len(str1) Else maxLen = Len(str2)
    str1 = getPaddedString(str1, maxLen, significantDigitsAreLeft)
    str2 = getPaddedString(str2, maxLen, significantDigitsAreLeft)
    resStr = String$(maxLen, "0")
    For i = 1 To maxLen
        If Mid$(str1, i, 1) = "1" Then
            If Not Mid$(str2, i, 1) = "1" Then
                Mid$(resStr, i, 1) = "1"
            End If
        ElseIf Mid$(str2, i, 1) = "1" Then 'Save an If check by assuming input string contains only "0" or "1"
            Mid$(resStr, i, 1) = "1"
        End If
    Next i
    Bitstr_XOR = resStr
End Function
'Helper to pad string
Private Function getPaddedString(str As String, length As Long, padLeft As Boolean) As String
    If Len(str) < length Then
        If padLeft Then
            getPaddedString = String$(length - Len(str), "0") & str
        Else
            getPaddedString = str & String$(length - Len(str), "0")
        End If
    Else
        getPaddedString = str
    End If
End Function

Using Formulas
You can do an XOR operation using Text functions or Sumproduct. This may be more appropriate if you do not want to use VBA but formulas are painful to ensure they covers all situations, like negatives or different length binary strings. I refer you to the superb blog post http://www.excelhero.com/blog/2010/01/5-and-3-is-1.html for examples using Sumproduct, and http://chandoo.org/wp/2011/07/29/bitwise-operations-in-excel/ for examples using Text functions.
I cooked up my own formulae that handles certain cases and I explain them below to guide you.
Binary string Input, Decimal Output
In the below, A2 and B2 refer to the two binary numbers in up to 32-bits string form. The strings can be variable length, as the formula will pad with 0's to the necessary length. It should be obvious how to increase it to more bits. They must be entered using Ctrl+Shift+Enter.
The most significant bit is on the left. To make it least significant bit on the left, you can remove the little subtraction in the powers of 2 part, and make it pad to the right.
Bitwise And:
=SUM((((MID(REPT("0",32-LEN($A$2))&$A$2,ROW($1:$32),1)="1")+(MID(REPT("0",32-LEN($B$2))&$B$2,ROW($1:$32),1)="1"))=2)*(2^(32-ROW($1:$32))))
Bitwise Or:
=SUM((((MID(REPT("0",32-LEN($A$2))&$A$2,ROW($1:$32),1)="1")+(MID(REPT("0",32-LEN($B$2))&$B$2,ROW($1:$32),1)="1"))>0)*(2^(32-ROW($1:$32))))
Bitwise Xor:
=SUM((((MID(REPT("0",32-LEN($A$2))&$A$2,ROW($1:$32),1)="1")+(MID(REPT("0",32-LEN($B$2))&$B$2,ROW($1:$32),1)="1"))=1)*(2^(32-ROW($1:$32))))
Binary string input, Binary string Output
A single cell solution would be arduous because there is no array concatenation formula in Excel. You could do it using the CONCATENATE function glueing together each bits, with each bit being the result of an If comparing each binary string returning 1 or 0 as appropriate. As I said, though easy (just build it up like =IF(Mid(A1,1,1) = "1",...), this would be boring so I personally won't do it for you ;)
Alternatively, you could do it more simply using columns or rows to build up the string, like:
If A1 and B1 have your binary strings, then in C1 put (for AND, or for OR change the =2 at the end to >0 and for XOR change it to =1):
=IF((MID($A1,1,1)="1")+(MID($B1,1,1)="1"))=2,"1","0")
Then in D1 put:
=C1 & IF((MID($A1,COLUMN()-COLUMN($C1),1)="1")+(MID($B1,COLUMN()-COLUMN($C1),1)="1"))=2,"1","0")
Then drag this across as many columns as bits


text:
Q: Using Prophet or Auto ARIMA with Ray There is something about Ray that I could not find a clear answer. Ray is a distributed framework for dataprocessing and training. In order to make it work in a distributed fashion Modin or some other distributed data analysis tool supported by Ray must be used so the data can flow on the whole cluster, but what if I want to use a model like Facebook's Prophet or ARIMA that takes pandas dataframe as input? When I use pandas dataframe as the arguments of the model functions will it work on just a single node or is there a possible workaround for it to work on the cluster?

A: Ray is able to train models with pandas dataframes as inputs!
Currently, there is a slight work-around needed for ARIMA, since it typically uses the statsmodels library behind the scenes.  In order to ensure the models are serialized correctly, an extra pickle step is needed.  Ray might eliminate the need for the pickle work-around in the future.
See explanation of pickle work-around:  https://alkaline-ml.com/pmdarima/1.0.0/serialization.html
Here is an excerpt of code for python 3.8 and ray 1.8.  Notice that the inputs to train_model() and inference_model() functions are pandas dataframes. The extra pickle step is embedded within those functions. https://github.com/christy/AnyscaleDemos/blob/main/forecasting_demos/nyctaxi_arima_simple.ipynb
import ray
import pandas as pd
import pmdarima as pm
from pmdarima.model_selection import train_test_split

# read 8 months of clean, aggregated monthly taxi data
filename = "https://github.com/christy/MachineLearningTools/blob/master/data/clean_taxi_monthly.parquet?raw=true"
g_month = pd.read_parquet(filename)

# Define a train_model function, default train on 6 months, inference 2
def train_model(theDF:pd.DataFrame, item_col:str
                , item_value:str, target_col:str
                , train_size:int=6) -> list:

    # split data into train/test
    train, test = train_test_split(theDF.loc[(theDF[item_col]==item_value), :], train_size=train_size)

    # train and fit auto.arima model
    model = pm.auto_arima(y=train[target_col]
                          ,X=train.loc[:, (train.columns!=target_col)
                                          & (train.columns!=item_col)]
                         )
    # here is the extra pickle step to handle statsmodel objects
    return [train, test, pickle.dumps(model)]

# Define inference_model function
def inference_model(model_pickle:bytes, test:pd.DataFrame
                    , timestamp_col:str, item_col:str, target_col:str) -> pd.DataFrame:

    # unpickle the model
    model = pickle.loads(model_pickle)

    # inference on test data
    forecast = pd.DataFrame(model.predict(n_periods=test.shape[0]
                         , X=test.loc[:, (test.columns!=target_col) & (test.columns!=item_col)]
                         , index=test.index))

    return forecast

# start-up ray on your laptop for testing purposes
import ray
NUM_CPU = 2
ray.init(
    ignore_reinit_error=True
    , num_cpus = NUM_CPU
)

###########
# run your training as distributed jobs by using ray remote function calls
###########

# Convert your regular python functions to ray remote functions
train_model_remote = ray.remote(train_model).options(num_returns=3)
inference_model_remote = ray.remote(inference_model)

# Train every model
item_list = list(g_month['pulocationid'].unique())
model = []
train = []
test = []

for p,v in enumerate(item_list):
    # ray remote eval
    temp_train, temp_test, temp_model = \
        train_model_remote.remote(g_month
                                  , item_col='pulocationid', item_value=v
                                  , target_col='trip_quantity'
                                  , train_size=6)
    train.append(temp_train)
    test.append(temp_test)
    model.append(temp_model)

# Inference every test dataset
result=[]
for p,v in enumerate(item_list):
    # ray remote eval
    result.append(inference_model_remote.remote(model[p], test[p]
                                                , timestamp_col='pickup_monthly'
                                                , item_col='pulocationid'
                                                , target_col='trip_quantity'))

# ray.get() means block until all objectIDs requested are available
forecast = ray.get(result)


text:
Q: Error creating aws_s3_notification with Terraform I'm currently having an issue with my aws_s3_notification resource creation. Whenever I attempt to deploy this resource, I receive this error
Error putting S3 notification configuration: InvalidArgument: Unable to validate the following destination configurations
I've tried setting depends_on parameters and adjusting permissions. One interesting thing is in my main.tf file, I'm creating two lambda functions. Both are extremely similar (just vary by code). My "controller" configuration deploys with no issue but my "chunker" function seems to have an issue creating the s3_notification.. I have included both configs for comparison.
#S3
resource "aws_s3_bucket" "ancb" {
  for_each = toset(var.ancb_bucket)

  bucket = format("ancb-%s-%s-%s",var.env,var.product_name,each.value)
  acl = "private"

  versioning {
    enabled = true
  }

  tags = {
      Environment = var.env
      Terraform = true
  }
}
#Chunker
resource "aws_lambda_function" "ancb_chunker" {

  function_name = format("ancb-chunker-%s-%s",var.env,var.product_name)

  s3_bucket = aws_s3_bucket.ancb["config"].id
  s3_key = var.lambda_zip_chunker

  handler = "handler.chunk"
  runtime = "nodejs8.10"

  role = aws_iam_role.lambda_exec.arn

  environment {
      variables = {
          ORIGINAL_BUCKET = aws_s3_bucket.ancb["original"].id
          TO_PROCESS_BUCKET = aws_s3_bucket.ancb["to-process"].id
          ENVIRONMENT = var.env
          CHUNK_SIZE = 5000
      }
  }
  tags = {
      Environment = var.env
      Terraform = true
  }
  depends_on = [
    aws_s3_bucket_object.ancb["chunker.zip"],
    aws_s3_bucket.ancb["chunker"]
  ]
}
resource "aws_lambda_permission" "ancb_chunker_s3" {

  statement_id = "AllowExecutionFromS3Bucket-Chunker"
  action = "lambda:InvokeFunction"
  function_name = aws_lambda_function.ancb_controller.arn
  principal = "s3.amazonaws.com"
  source_arn = aws_s3_bucket.ancb["original"].arn
}
resource "aws_s3_bucket_notification" "chunker" {
  bucket = aws_s3_bucket.ancb["original"].id

  lambda_function {
    lambda_function_arn = aws_lambda_function.ancb_chunker.arn
    events = ["s3:ObjectCreated:*"]
  }
  depends_on = [
    aws_lambda_permission.ancb_chunker_s3,
    aws_lambda_function.ancb_chunker,
    aws_s3_bucket.ancb["original"]
  ]
}
#Controller
resource "aws_lambda_function" "ancb_controller" {

  function_name = format("ancb-controller-%s-%s",var.env,var.product_name)

  s3_bucket = aws_s3_bucket.ancb["config"].id
  s3_key = var.lambda_zip_controller

  handler = "handler.controller"
  runtime = "nodejs8.10"

  role = aws_iam_role.lambda_exec.arn

  environment {
      variables = {
          DESTINATION_BUCKET = aws_s3_bucket.ancb["destination"].id
          ENVIRONMENT = var.env
          ERROR_BUCKET = aws_s3_bucket.ancb["error"].id
          GEOCODIO_APIKEY = <insert>
          GEOCODIO_ENDPOINT = <insert>
          GEOCODIO_VERSION = <insert>
          ORIGINAL_BUCKET = aws_s3_bucket.ancb["original"].id
          SOURCE_BUCKET = aws_s3_bucket.ancb["source"].id
          TO_PROCESS_BUCKET = aws_s3_bucket.ancb["to-process"].id
          WORKING_BUCKET = aws_s3_bucket.ancb["working"].id
      }
  }
  tags = {
      Environment = var.env
      Terraform = true
  }
  depends_on = [
    aws_s3_bucket_object.ancb["controller.zip"]
  ]
}
resource "aws_lambda_permission" "ancb_controller_s3" {

  statement_id = "AllowExecutionFromS3Bucket-Controller"
  action = "lambda:InvokeFunction"
  function_name = aws_lambda_function.ancb_controller.arn
  principal = "s3.amazonaws.com"
  source_arn = aws_s3_bucket.ancb["source"].arn
}
resource "aws_s3_bucket_notification" "controller" {
  bucket = aws_s3_bucket.ancb["source"].id

  lambda_function {
    lambda_function_arn = aws_lambda_function.ancb_controller.arn
    events = ["s3:ObjectCreated:*"]
  }
  depends_on = [
    aws_lambda_permission.ancb_controller_s3,
    aws_s3_bucket.ancb["source"]
  ]
}

UPDATE: If I manually create the trigger and run terraform apply again, terraform is able to move forward with no problem....


text:
Q: How to run tensorflow.contrib.layers.conv2d in tensorflow 2.x? I am trying to migrate Tensorflow 1.13 code to TF 2.x using the automated script found in the link: https://www.tensorflow.org/guide/migrate/upgrade
The script shows no issues that require attention, however; when I run the generated code file, I get the following exception:
TypeError: Got an unexpected keyword argument 'inputs'
The error refers to the convolution layers defined in the following code block:
    with tf.compat.v1.variable_scope('conv_block1'):
        conv1 = conv2d(inputs=image_tf, num_outputs=64, kernel_size=3, rate=1, activation_fn=tf.nn.relu)
        conv1 = conv2d(inputs=conv1, num_outputs=64, kernel_size=3, rate=1, activation_fn=tf.nn.relu)

What method replaces tf.contrib.layers.conv2d the best? and what arguments should I pass to it in order to get the same results?


text:
Q: Local index formula for >ungraded< elliptic operators Let $P\colon E \to F$ be an elliptic pseudodifferential operator over $M$. Assuming that $P$ defines a finitely summable Fredholm module, we may apply the Chern-Connes character to it to get a cyclic cocycle and this may then be mapped into the homology of $M$, i.e., we have $ch_\ast(P) \in H_\ast(M)$.
On the other hand, we may do the clutching construction using the symbol $\sigma(P)$ of $P$ to get an element $[\sigma_P] \in K_{cpt}^0(TM)$, apply the usual cohomological Chern character, integrate over the fiber, and finally multiply with the Todd genus of $M$, to get the index class $ind(P) = \pi_! ch^\ast [\sigma_P] \wedge Td(M) \in H^\ast(M)$. (I think I forgot here some sign $(-1)^?$.)
If $P$ is a graded operator (so that $E$ and $F$ are the positive and negative parts, respectively, of the vector bundle on which $P$ acts) we have $ch_\ast(P) \in H_{ev}(M)$ and Connes and Moscovici proved in Cyclic Cohomology, The Novikov Conjecture And Hyperbolic Groups that this is the Poincare dual of $ind(P)$ (up to some constants that only depend on the degree $q$ in which we compare these classes).
But if $P$ is an ungraded operator (in this case we would have $E=F$) we get $ch_\ast(P) \in H_{odd}(M)$ since now $P$ itself defines an odd $K$-homology class. But the Poincare dual of $ind(P)$ still lives in $H_{ev}(M)$, i.e., we can not compare them.

What is the correct formulation of the local index formula in the case of ungraded operators? Is it in the literature somewhere?

I expect somehow a small fix to the construction of the index class $ind(P)$ such that it lives then in the correct degrees (maybe something like taking a suitable product with $S^1$ similarly as the trick used by Connes and Moscovici in their above cited paper where they reduced from the case of odd-dimensional manifolds to even-dimensional ones).

A: Meanwhile I found the answer to my question in the literature, concretely in:
Baum, Douglas, K-Homology and Index Theory, Proceedings of Symposia in Pure Mathematics, vol. 38 (1982), Part 1.
If $P\colon E \to E$ is elliptic and self-adjoint, then its symbol $\sigma(P) \colon \pi^\ast E \to \pi^\ast E$ is a self-adjoint automorphism, where $\pi\colon SM \to M$ denotes the unit sphere bundle. So we have a splitting $\pi^\ast E = E^+ \oplus E^-$, where $E^+$ and $E^-$ are fiber wise spanned by the positive, resp. negative, eigenvalues of $\sigma(P)$, and we define the symbol class $\sigma_P$ of $P$ as $\sigma_P := [E^+] \in K^0(SM)$. To get the index class, we do now the same as in the graded case: $ind(P) := (-1)^{n(n+1)/2} \pi_! ch^\ast [\sigma_P] \wedge Td(M) \in H^\ast(M)$.


text:
Q: Swagger - Why is Swagger creating a request body field when I have not written an annotation for one? I have written a swagger ui for a GET request that doesn't need a request body. I haven't used the @RequestBody annotation so why is Swagger bringing up a request body field on the ui? Even if I leave it empty, it is causing my API requests to fail with the following error: TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
I understand why this error exists, the curl that swagger creates has a -d option. But how can I switch this off?
The only annotations I've used are @Get, @Path, @Operation, @ApiResponses, and @Parameters.
Put simply, how can I tell swagger that I don't need a request body?

A: If you hadn't annotated some parameter of your method it is automatically considered request body. If you don't want it to, you have to explicitly annotate it as something else or annotate it to ignore param with something like @ApiParam(hidden = true):
  // example usage of Swagger with Akka HTTP
  @ApiOperation(
    httpMethod = "GET",
    response   = classOf[ApiResponseX],
    value      = "docs"
  )
  @ApiImplicitParams(
    Array(
      new ApiImplicitParam(
        name      = "id",
        dataType  = "string",
        paramType = "query",
        value     = "id docs"
      )
    )
  )
  def fetchX(
    // even if this value has custom handling I have to explicitly ignore it,
    // to not make it into a request body
    @ApiParam(hidden = true) id: UUID
  ): Route = ...


text:
Q: How to configure route in zend framework 2? I am beginner working with Zend Framework 2.3.3. I'm trying to do some routing,but it's always not working. I added a new module called Manager, the following code in the file \module\Manager\config\module.config.php
'router' => array(
    'routes' => array(
        'auth' => array(
            'type'    => 'Literal',
            'options' => array(
                'route'    => '/tologinpage',
                'defaults' => array(
                    'controller' => 'Manager\Controller\Auth',
                    'action'     => 'show-login',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'login'  => array(
                    'type' => 'Literal',
                    'options' => array(
                        'route'    => '/login',
                        'defaults' => array('action' => 'login'),
                    ),
                    'may_terminate' => true,
                ),
            ),
        ),
    ),
),

the following code in the file \module\Manager\view\manager\auth\login.phtml
<form class="form-horizontal" role="form" method="post" action="/login">
    <!-- code -->
    <div class="col-md-offset-2 col-md-8">
        <button type="submit" class="btn btn-block btn-primary">Login</button>
    </div>
</div>

If I try to access the first route (/tologinpage), it works,
but when i submit the form to controller AuthController\login, it is always show A 404 error occurred Page not found
Here is my controller
namespace Manager\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AuthController extends AbstractActionController
{

     public function showLoginAction()
     {
           $view = new ViewModel();

           $view->setTemplate('manager/auth/login');
           $view->setTerminal(true);  // close layout

           return $view;
      }

      public function loginAction()
      {
            var_dump($_POST);
            exit;
      }
}

A: URL of loginAction isn't /login but /tologinpage/login, because login route is define as child of tologinpage route.
Btw, you shouldn't write URL by hand, but use URL view helper:
<form class="form-horizontal" role="form" method="post" action="<?php echo $this->url('auth/login'); ?>">

If you want make those roles on same level, put them on same level in configuration array:
    'router' => array(
        'routes' => array(
            'auth' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/tologinpage',
                    'defaults' => array(
                        'controller' => 'Manager\Controller\Auth',
                        'action'     => 'show-login',
                    ),
                ),
            ),
            'login'  => array(
                'type' => 'Literal',
                'options' => array(
                    'route'    => '/login',
                    'defaults' => array(
                        'controller' => 'Manager\Controller\Auth',
                        'action' => 'login',
                    ),
                ),
            ),
        ),
    ),


text:
Q: How to prevent a property from being set through model binding in ASP.NET Core Web API? I've the following ZapScan class with a TargetUrl property whose purpose is to return the concatenation of the Url and Path properties.
The ZapScan class is also used as a parameter in a controller action, and thus is subject to model binding:
[HttpPost, FormatFilter]
    [Consumes("application/json", new string[]{"application/xml"})]
    public ActionResult<ZapScan> OnPost([FromBody] ZapScan scan)
    {
        return HandleRequest(scan);
    }

How can I prevent the TargetUrl property from being subject to model binding? Is it sufficient that it's a read-only property? What about the general case, where the property is also set-able?
public class ZapScan
{
   private string _url;
   private string _path;

   [XmlElement(IsNullable = true)]
   public string Url
   {
       get
       {
           return _url;
       }
       set
       {
           if (value is null)
           {
               throw new ArgumentNullException();
           }

           _url = value.EndsWith("/", StringComparison.Ordinal) ? value.Remove(value.Length - 1) : value;
       }
   }
   [XmlElement(IsNullable = true)]
   public string Path
   {
       get
       {
           return _path;
       }
       set
       {
           if (value is null)
           {
               _path = "";
           }
           else
           {
               _path = value.StartsWith("/", StringComparison.Ordinal) ? value : value.Remove(value.Length - 1);
           }
       }
   }
   public ScanType Type { get; set; } = ScanType.Active;

   public string TargetUrl
   {
       get
       {
           return Url + Path;
       }
   }

   public override string ToString() {
       return JsonSerializer.Serialize(this).ToLower();
   }
}

[Bind] attribute:
I've been looking at the Bind attribute, but it doesn't appear to have a an Exclude property in ASP.NET Core Web API?
[Bind(Exclude = "Height, Width")]

A: Maybe a private setter on TargetUrl can help :
public string TargetUrl
{
    get
    {
        return Url + Path;
    }

    private set;
}

On the other hand, given that you are saying the framework to consume json, maybe just a JsonIgnore will do the trick
[JsonIgnore]
public string TargetUrl
{
    get
    {
        return Url + Path;
    }
}

A: If the property is settable you can use [BindNever] on it. Like so:
using Microsoft.AspNetCore.Mvc.ModelBinding;

public class ZapScan
{
    // ...

    [BindNever]
    public string TargetUrl { get; set; }

    // ...
}

Here are the Microsoft docs explaining it.


text:
Q: Tabs com tamanhos diferentes (ViewPager) Eu preciso criar um APP com varias tabs, igual ao intagram e o WhatsApp. E que quando passe pra uma Tab especifica, ela fique em fullScreem, ou pelomenos que desapareça a ActionBar, e quando passar pra outras Tabs tudo volte ao normal.
PS: É exatamente igual ao WhatsApp que quando arrasta pra Tab da câmera, a tela fica em fullScreem.
Activity Main
public class MainActivity extends AppCompatActivity {

private final int PERMISSAO_REQUEST = 2;

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

    //deixa em FullScreem
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    //IMPORTANTE: aqui verifica as permiçoes
    permicoes();

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}

private void permicoes() {
    //USUARIA DAR A PERMISSAO
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PERMISSAO_REQUEST);
        }
    }

    //USUARIA DAR A PERMISSAO
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSAO_REQUEST);
        }
    }
}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        switch(pos) {
            //IMPORTANTE: Ao adicionar ou retirar case's, ATUALIZE o getCount() abaixo
            case 0: return CameraFragment.newInstance("CameraFragment, Instance 1");
            default: return TelaPrincipalFragment.newInstance("TelaPrincipalFragment, Default");
        }
    }

    @Override
    public int getCount() {
        //IMPORTANTE representa o numero de telas (la no switch)
        return 2;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == PERMISSAO_REQUEST) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // A permissão foi concedida. Pode continuar
        } else {
            // A permissão foi negada. Precisa ver o que deve ser desabilitado
        }
        return;
    }
}

}
Fragment 1 (so um trecho)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_camera, container, false);

    surfaceView = v.findViewById(R.id.surfaceView);
    surfaceHolder = surfaceView.getHolder();

    //Instalamos uma surfaceHolder.Callback então nós notificamos quando o underlying surface é criado e destroido.
    surfaceHolder.addCallback(this);
    //APARENTEMENTE essa linha nao foi necessaria
    //surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    return v;
}

Fragment 2
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_tela_principal, container, false);

    lvListaMaterias = (ListView) v.findViewById(R.id.lvListaMaterias);

    return v;
}

Basicamente é isso, quero que durante o fragment 1 a tela fique fullscreem, e quando passa pro fragment 2 a tela volte ao normal, com action bar, etc.

A: Encontrei a resposta:
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
actionBar = getSupportActionBar();
actionBar.hide();