text:
Q: Remove quality losing, after scale applied I have UIView ancestor - let say MyView, which overrides method -drawInRect to display an image
override func draw(_ rect: CGRect) {
    super.draw(rect)

    image?.draw(in: rect)

    /*some code here*/
}

This view is scaling in both directions at some point. After enlarging, displayed image loses it's quality. Saying, if I create MyView with size 20*20, bounds property remains the same after scaling, but transformed image I'm trying to display is low quality, because I'm trying to paint it with the same 20x20 size. Is there any way to draw an image respectively to my view scaling?

A: First, strongly consider using a UIImageView as a subview rather than trying to implement even modestly complicated image drawing yourself. UIImageView is optimized for many of the problems you can face. It's not perfect, and sometimes it's possible to do better by hand if you know what you're doing, but it does its job well.
To your specific problem, your contentMode is almost certainly scaleToFill (that's the default). The simplest solution is to change it to redraw to force a full redraw when the bounds change. That's not highly efficient, but may be ok for your problem (it often is fine). Making it both high quality and highly efficient is a bit more complicated, and often requires a lot of special knowledge how your app behaves. For the easy cases, making this high quality and efficient is what UIImageView does for you.
If you're reliably scaling from 20x20 to some other specific size, and you don't have too many views, another trick is to draw at your full size and then scale down to 20x20. This is very inefficient if you have a lot of views and the size of the final images is large, but can be very fast and high quality, so is something to at least consider. I've done this to deal with small zooms (for example to 110% size). It probably wouldn't be a good way to turn thumbnails into full-screen images, though.


text:
Q: Is it possible to get the reference of a file in firebase storage with the download URI in React Native Firebase? I'm storing an image in the firebase storage and I get the download URL once it is uploaded. Is it possible to get the reference of the image that I've uploaded using the download URL later?
I'm using Firebase in React Native.

A: You can use the refFromURL method to get the reference.
https://firebase.google.com/docs/reference/js/firebase.storage.Storage#reffromurl
const ref = await storage().refFromURL(url);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make Spring Boot only scan and validate imported entities? I have separated my project in multiple modules using Maven. On of the modules is used as a 'common' module which shares entities and other code between modules. I have imported this module within the other modules. A problem arises when launching a module which uses the 'common' module. The module seems to scan for all entities in the common package and tries to validate the schema. This module does not have the SQL permission to access some tables, which results in a validation error.
Is there a way to disable this feature and only validate the schema based on the actually used entities in the code (based on imports)?

A: A somewhat vague explanation, I would like to see an immediate problem.
But the first thing that comes to mind: exclude auto jpa support. For your application class:
@SpringBootApplication(exclude = {JpaRepositoriesAutoConfiguration.class})

Possible, you can exclude also class DataSourceAutoConfiguration.


text:
Q: Create JSON from an array of int I have a django model called ServiceSubCategory and I want to create a JSON list of its primary key values using Python.
I have tried this:
idDic=[obj.as_json for obj in ServiceSubCategory.objects.values_list('id',flat=True)]

But I'm getting this error:

int object has no attribute as_json

I'm doing this because I'm gonna append another JSON to this later.
So how could I create a JSON out of my models primery Keys?
Update
I tried
id_json = json.dumps(ServiceSubCategory.objects.values_list('id',flat=True))

And I'm getting a new error:

[1,2,3,4,5,6,7,8,9,10] is not JSON serializable

And this is the traceback:

Traceback: File
  "/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg/django/core/handlers/base.py"
  in get_response
    111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/salimi/salimi/views.py" in service
    61.     idDic=json.dumps(ServiceSubCategory.objects.values_list('id',flat=True))
  File "/usr/lib/python2.7/json/init.py" in dumps
    243.         return _default_encoder.encode(obj) File "/usr/lib/python2.7/json/encoder.py" in encode
    207.         chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python2.7/json/encoder.py" in iterencode
    270.         return _iterencode(o, 0) File "/usr/lib/python2.7/json/encoder.py" in default
    184.         raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /service/1/ Exception Value: [1, 2, 3, 4,
  5, 6, 7, 8, 9, 10] is not JSON serializable

A: This should do the trick:
import json
json.dumps(list(ServiceSubCategory.objects.values_list('id', flat=True)))

values_list returns an instance of django.db.models.query.ValuesListQuerySet which does not have a default JSON serializer (it's just a QuerySet, no database request is made so far). However, you can transform it into a list object before.
import json
values_list_object = ServiceSubCategory.objects.values_list('id', flat=True))
list_object = list(values_list) # querying the database
json.dumps(list_object)

A: You can simply write the following:
import json

id_json = json.dumps(list(ServiceSubCategory.objects.values_list('id',flat=True)))

A: Update
It looks like ServiceSubCategory.objects.values_list('id', flat=True) might return a generator. In that case you can consume the generator using list():
import json
json.dumps(list(ServiceSubCategory.objects.values_list('id', flat=True)))

Wouldn't this do the trick?
import json
json.dumps(ServiceSubCategory.objects.values_list('id', flat=True))

Since ServiceSubCategory.objects.values_list is already a list it can be dumped directly to JSON. There is no need to use a list comprehension.


text:
Q: Find the missing date ranges Table 1
code        StartDate        EndDate
A           01/01/2011        06/15/2011
A           06/25/2011        06/30/2011
B           01/12/2011        07/31/2011
B           08/3/2011         12/31/2011

Table 2
code        StartDate        EndDate
A           01/01/2011       06/30/2011
B           01/12/2011        07/31/2011
B           08/3/2011         12/25/2011

I need find what is in Table1 and not in Table2 which  is
code        StartDate        EndDate
B           12/26/2011        12/31/2011

And the Converse of what is in Table2 and not in Table1
code        StartDate        EndDate
A           06/16/2011       06/29/2011

There is no time component in the date field and T-SQL (SQL Server 2000 ) is preferred.

A: This is a bit tedious in SQL Server 2000. It uses a numbers table to expand out the ranges of dates into individual rows. Then NOT EXISTS for the anti semi join then uses an "islands" approach I stole from an MSDN article to collapse the result back into ranges again.
SET DATEFORMAT MDY

DECLARE @Numbers TABLE (N INT PRIMARY KEY)

INSERT INTO @Numbers
SELECT number
FROM master..spt_values
WHERE type='P' AND number >= 0

DECLARE @Table1 TABLE
(
code CHAR(1),
StartDate DATETIME,
EndDate DATETIME
)
DECLARE @Table2 TABLE
(
code CHAR(1),
StartDate DATETIME,
EndDate DATETIME
)
INSERT INTO @Table1
SELECT 'A','01/01/2011','06/15/2011' UNION ALL
SELECT 'A','06/25/2011','06/30/2011' UNION ALL
SELECT 'B','01/12/2011','07/31/2011' UNION ALL
SELECT 'B','08/3/2011',' 12/31/2011'

INSERT INTO @Table2
SELECT 'A','01/01/2011','06/30/2011' UNION ALL
SELECT 'B','01/12/2011','07/31/2011' UNION ALL
SELECT 'B','08/3/2011',' 12/25/2011'

DECLARE @Results TABLE
(
code CHAR(1),
StartDate DATETIME
)

INSERT INTO @Results
SELECT T1.code,
       DATEADD(DAY, N, StartDate)
FROM   @Table1 T1
       INNER JOIN @Numbers N1
         ON N <= DATEDIFF(DAY, StartDate, EndDate)
WHERE  NOT EXISTS (SELECT *
                   FROM   @Table2 T2
                          INNER JOIN @Numbers N2
                            ON N2.N <= DATEDIFF(DAY, T2.StartDate, T2.EndDate)
                   WHERE  DATEADD(DAY, N1.N, T1.StartDate) =
                          DATEADD(DAY, N2.N, T2.StartDate)
                          AND T1.code = T2.code)

/*SQL Server 2000 gaps and islands approach from here
http://msdn.microsoft.com/en-us/library/aa175780%28v=sql.80%29.aspx*/
SELECT t1.code,
       t1.StartDate,
       MIN(t2.StartDate) AS EndDate
FROM   (SELECT StartDate,
               code
        FROM   @Results tbl1
        WHERE  NOT EXISTS(SELECT *
                          FROM   @Results tbl2
                          WHERE  tbl1.StartDate = tbl2.StartDate + 1
                                 AND tbl1.code = tbl2.code)) t1
       INNER JOIN (SELECT StartDate,
                          code
                   FROM   @Results tbl1
                   WHERE  NOT EXISTS(SELECT *
                                     FROM   @Results tbl2
                                     WHERE  tbl2.StartDate = tbl1.StartDate + 1
                                            AND tbl1.code = tbl2.code)) t2
         ON t1.StartDate <= t2.StartDate
         AND t1.code = t2.code
GROUP  BY t1.code,
          t1.StartDate


text:
Q: XAML Designer - default zoom? I feel very much annoyed by default zoom of XAML Designer in VS2015 (not sure if version is relevant), which is Fit all by default.
Is there a way to set it to 100% by default? Disabling zoom feature is also an option. But there is nothing related in VS Settings - XAML Designer.
P.S.: tagging it with languages to be visible to peoples like me, who only look at tagged questions (in my case C#).

A: Visual Studio 2015 (at least Professional with Update 1) remembers your XAML Designer's zoom setting.
Start just one instance of VS2015 and create a new WPF Application. Open the MainWindow.xaml and select the designer. In my case it opens up with 100% zoom:

Now change the zoom to Fit all and then create a new WPF Application. Again open MainWindow.xaml and select the designer. The zoom should show something like 229.4% (which is the % for Fit all in this case):

Restart VS2015 and create new WPF project and again check the zoom. It should till default to your last selection.
Note: Selecting 400% didn't have this same behavior. The designer opened with 100% instead.

A: With VS2015 the default option became "fit all", however, VS remembers your zoom settings for every XAML element. Once you set it to 100%, it stays there, even after closing project or solution. I couldn't find a way to change this default behavior.
The annoying thing is, when you have a large existing project created with VS2013 or below and start using 2015. Every XAML element previously showing at 100% is now fitted to the designer size.
After three month on VS2015, I'm still stumbling over "not-yet-touched" XAML elements popping up at 1360% zoom level.

A: If you're looking for a quick keyboard way of zooming to 100% do this ...

*

*open a xaml file. I use a split window, it also works with just the design surface. The design surface needs to have focus for the next step to work

*alt-G (opens the Design menu, only available if you are in the designer

*alt-S selects "Actual Size" from that menu.

I added a keyboard shortcut shift-alt-0 (zero). In the options -> Environment -> Keyboard search for "Actual" and set a your keyboard shortcut in the "XAML Designer" ... or Global if you like and it's not killing another shortcut. The Designer needs to have focus for it to work so it can be fiddly at times.
But that whole "any default zoom you like as long as it is zoom to extents" is dumb


text:
Q: Bijective proof involving fixed points and symmetric group on $n$ letters? There is the following question here:
If $S=\{1,2,\dots,n\}$ and $P_n(k)$ be the number of permutations of $S$ having $k$ fixed points, then $\sum_{k=0}^nk.P_{n}(k)=n!$:

Let $S = \{1,2,\dots,n\}$. Then $i \in S$ is said to be a fixed point of a permutation $p$ or $S$ if $p(i) = i$. Let $P_n(k) $ be the number of permutations of $S$ which have $k$ fixed point.
Prove that $\sum_{k=0}^nk\cdot P_{n}(k) = n!$.

There were some beautiful probabilistic proofs given. However, I'm wondering if there is a proof by coming up with an explicit bijection from the left-hand side to the symmetric group on $n$ letters.

A: Let $[n]=\{1,\dots,n\}$.
$\sum_{k=0}^nk\cdot P_n(k)$ enumerates ordered pairs $(\pi,x)$, such that $\pi:[n]\to [n]$ is a bijection, $x\in [n]$, and $\pi(x)=x$.
For any fixed $x$, there is a bijection between permutations $\pi$ for which $\pi(x)=x$, and permutations $\pi$ for which $\pi(n)=n$. Simply consider the permutation $\pi$ becomes when you rename $n$ to $x$, and $x$ to $n$.
Therefore, $\sum_{k=0}^n kP_n(k)$ enumerates ordered pairs $(\pi,x)$ where $\pi:[n]\to [n]$ is a permutation, $\pi(n)=n$ and $x\in [n]$.
It is obvious now that the number of such ordered pairs is $(n-1)!\cdot n$; there are $(n-1)!$ choices for a permutation which fixes $n$, and $n$ choices for $x$. Furthermore, it is easy to use a permutation $\pi$ of $[n-1]$, together with an $n$-way choice of $x$, to make bijectively permutation of $[n]$; simply insert the number $n$ at position $x$ in $\pi$. This completes the bijection from ordered pairs $(\pi,x)$ for which $\pi(x)=x$ to all permutations of $[n]$.

Here is an illustration of the bijection. We can think of $\sum_{k=0}^n kP_k(n)$ as counting permutations $\pi$ where one of the fixed points of $\pi$ is circled. We want a bijection between these "annotated permutations" and regular permutations. The bijection is this; with the annotated permutation written in one-line notation,

*

*Delete the circled element, $x$.

*Decrease all remaining numbers greater than $x$ by one, so all numbers are between $1$ and $n-1$,

*Insert $n$ at spot $x$ in the permutation.
Here is an example, where $n=5$:
$$
[3,\;\boxed{2},\;5,\;4,\;1]\to [3,\;5,\;4,\;1]\to [2,\;4,\;3,\;1]\to [2,\;\color{red}5,\;4,\;3,\;,1]
$$

A: I think that this bijection is easier (it is actually the most elementary way of proving that the average number of fixed points is 1 regardless of $n$):
For any pair $(i,p)$ of a fixed point $i$ in a permutation $p$, let $p'$ the resulting permutation when you move $i$ to the last place. Conversely, for any permutation $p$, modify it by moving the last term $i$ to the $i$-th place, and if $p'$ is the resulting permutation consider the pair $(i,p')$.
It is clear that they are inverse maps.


text:
Q: Running Jupyter Notebook on AWS Lambda I am trying to run Jupyter Notebook on AWS Lambda, created a layer with all the dependencies, the jupyter notebook is a simple code which pulls a csv file from amazon S3 and displays the data as bar graph. Below is the lambda function written to download the .ipynb file and execute the notebook with papermill. Not sure why its failing with boto3 module not found.
import json
import sys
import os
import boto3
# papermill to execute notebook
import papermill as pm
import pandas as pd
import logging
import matplotlib.pyplot as plt

sys.path.append("/opt/bin")
sys.path.append("/opt/python")
os.environ["PYTHONPATH"]='/var/task'
os.environ["PYTHONPATH"]='/opt/python/'
os.environ["MPLCONFIGDIR"] = '/tmp/'
# ipython needs a writeable directory
os.environ["IPYTHONDIR"]='/tmp/ipythondir'
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    s3 = boto3.resource('s3')
    s3.meta.client.download_file('test-boto', 'testing.ipynb', '/tmp/test.ipynb')
    pm.execute_notebook('/tmp/test.ipynb', '/tmp/juptest_output.ipynb', kernel_name='python3')
    s3_client.upload_file('/tmp/juptest_output.ipynb', 'test-boto', 'temp/juptest_output.ipynb')
    logger.info(event)

Error o/p:
START RequestId: c4da3406-c829-4f99-9fbf-b231a0d3dc06 Version: $LATEST
[INFO]  2020-08-07T17:55:16.602Z    c4da3406-c829-4f99-9fbf-b231a0d3dc06    Input Notebook:  /tmp/test.ipynb
[INFO]  2020-08-07T17:55:16.603Z    c4da3406-c829-4f99-9fbf-b231a0d3dc06    Output Notebook: /tmp/juptest_output.ipynb

Executing:   0%|          | 0/15 [00:00<?, ?cell/s][INFO]   2020-08-07T17:55:17.311Z    c4da3406-c829-4f99-9fbf-b231a0d3dc06    Executing notebook with kernel: python3
OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k

Executing:   7%|▋         | 1/15 [00:01<00:14,  1.06s/cell]
Executing:   7%|▋         | 1/15 [00:01<00:20,  1.46s/cell]
[ERROR] PapermillExecutionError:
---------------------------------------------------------------------------
Exception encountered at "In [1]":
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-9c332490c231> in <module>
      1 import pandas as pd
      2 import os
----> 3 import boto3
      4 import matplotlib.pyplot as plt
      5 client = boto3.client('s3')

ModuleNotFoundError: No module named 'boto3'

Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 28, in lambda_handler
    pm.execute_notebook('/tmp/test.ipynb', '/tmp/juptest_output.ipynb', kernel_name='python3')
  File "/opt/python/papermill/execute.py", line 110, in execute_notebook
    raise_for_execution_errors(nb, output_path)
  File "/opt/python/papermill/execute.py", line 222, in raise_for_execution_errors
    raise errorEND RequestId: c4da3406-c829-4f99-9fbf-b231a0d3dc06
REPORT RequestId:c4da3406-c829-4f99-9fbf-b231a0d3dc06
    Duration: 1624.78 ms    Billed Duration: 1700 ms    Memory Size: 3008 MB    Max Memory Used: 293 MB

Jupyter Notebook:
import pandas as pd
import os
import boto3
import matplotlib.pyplot as plt
client = boto3.client('s3')

path = 's3://test-boto/aws-costs-Owner-Month-08.csv'
monthly_owner = pd.read_csv(path)
plt.bar(monthly_owner.Owner.head(6),monthly_owner.Amount.head(6))
plt.xlabel('Owner', fontsize=15)
plt.ylabel('Amount', fontsize=15)
plt.title('AWS Monthly Cost by Owner')
plt.show()

A: It looks like papermill kernel is not able to detect boto3 package even though your lambda handler is able to find it. I see you are overriding (not appending) PYTHONPATH in your lambda handler. This will remove other directories from PYTHONPATH to look for packages. Papermill child process will use this python path subsequently.
You might also find this useful. It allows you to directly deploy Jupyter Notebooks as serverless functions. It uses papermill behind the scene.
Disclaimer: I work for Clouderizer.


text:
Q: Precise clicking with overlapping divs I'm sorry if the title doesn't explain it well enough, but it's the best title i could think of to represent my question.
So I've got two divs:
.div-arrow
{
    position: absolute;
    float: left;
    cursor: pointer;
    display:block;
    width: 136px;
    height: 54px;
    vertical-align: middle;
    border-radius: 4px;
    background: url(ImagePathHere) no-repeat scroll 0px 0px transparent;
    zoom: 50%;
}

.div-diamond
{
    position: absolute;
    float: left;
    cursor: pointer;
    display: block;
    width: 83px;
    height: 54px;
    vertical-align: middle;
    border-radius: 4px;
    background: url(ImagePathHere) no-repeat scroll -272px 0px transparent;
    zoom: 50%;
}

And I use them to make a layout like this: http://i.stack.imgur.com/htFRd.png
Clicking where the red mark is will activate the green diamond, instead of the diamond it looks like you're clicking.  I was wondering how I go about trimming those unseen sections of the image/div, so that you actually click the divs it looks like you're clicking.

A: All elements on a web page are essentially blocks - so although you may create the look of a circle or a diamond etc it's still really a four sided block element.
For your problem you could consider either using an image map:
http://www.w3.org/TR/html401/struct/objects.html
Or possibly using the HTML5 CANVAS method:
https://developer.mozilla.org/en-US/docs/HTML/Canvas


text:
Q: DataGridView prevent adding newrow after newrow I have datagridview datasource set to datatable source. At the end there is newrow so user can fill it in. However i have one issue. When user for instance fill first column and click enter then new row is not anymore new row and 'next' new row is added. What i want to achieve is if user starts to write something in new row then when he hit Enter before creating new row to check whether all columns has been firstly filled if not cancel adding new row. How to achieve that?

A: You could do something like this:
public void checkIfRowIsEmpty()
{
    foreach (DataGridViewRow rw in this.dataGridView1.Rows)
    {
        for (int i = 0; i < rw.Cells.Count; i++)
        {
           if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString())
           {
           dataGridView1.AllowUserToAddRows = false;
           break;
           }
           else
           {
           dataGridView1.AllowUserToAddRows = true;
           }
        }
    }
}

Call the methode when the user pushs "Enter".
Here is an example:
Enter key pressed event handler


text:
Q: Magnific popup on button click for the life of me I can't get this to work. I just want to click a video button to pull up my video gallery.
HTML
{{-- Button for video gallery --}}

    <button class="button--video button video-gallery" data-mfp-src="video-gallery">

        Videos
    </button>

{{-- Video gallery, hidden because the user doesn't need to see this --}}

        Video #2

        Video #3

        Video #4

Javascript
$( ".button--video" ).click(function() {
    $('.video-gallery').magnificPopup({
            delegate: 'a',
            type: 'iframe',
            tLoading: 'Loading video #%curr%...',
            mainClass: 'mfp-iframe',
            gallery: {
                enabled: true
            },
            iframe: {
                tError: 'This video #%curr% could not be loaded.',
                titleSrc: function (item) {
                    return '';
                }
            }
        }
    );
});

Would be very grateful if someone could help me.

A: If the problem is the event, you can set id to container:

    <button class="button--video button video-gallery" data-mfp-src="video-gallery">

        Videos
    </button>

And the event:
$( "#container--video" ).click(".button--video", function() {...}

A: Well my first mistake was targeting the video gallery container, that isn't going to launch Magnific popup, I needed to target a link that Magnific Popup could read and open inside the video container. My second mistake was not realising that I needed to basically simulate two clicks.
HTML

        Video #2

        Video #3

        Video #4

Java script
$('.button--video').click(function(){ //When user clicks the button
    $(".first-video").click();//simulate click on first video link
});

$('.video-gallery').magnificPopup({ //magnific makes a gallery from any links in this container.
        delegate: 'a',
        type: 'iframe',
        tLoading: 'Loading video #%curr%...',
        mainClass: 'mfp-iframe',
        gallery: {
            enabled: true
        },
        iframe: {
            tError: 'This video #%curr% could not be loaded.',
            titleSrc: function (item) {
                return '';
            }
        }
    }
);

By simulating a click to a class called "first-video", Magnific popup can then open my hidden video gallery, allowing the user to navigate through the video list through Magnific popup. By having a class only on the first video link, I know the user is always going to the open that video link first.


text:
Q: Scrapy pipeline mysql connection module error I am unable to run scrapy through my pipeline to my local database. I have already installed mysql-connector-python 8.0.19 and am able to write data to the database within the same project but outside of a Scrapy pipeline . Can someone please help i can't figure out why it isn't working.
When i try to send data via scrapy pipeline i get the following error:
[twisted] CRITICAL: Unhandled error in Deferred:
File "C:\Users\Viking\PycharmProjects\Indigo_Scrp\IndgoScrp\IndgoScrp\pipelines.py", line 7, in <module>
        from mysql.connector import (connection)
        ModuleNotFoundError: No module named 'mysql

Here is my code for the pipeline :
from mysql.connector import (connection)
from mysql.connector import errorcode

class IndgoscrpPipeline(object):

    def __init__(self):
        self.create_connection()
        self.create_table()

    def create_connection(self):
        self.conn = connection.MySQLConnection(
            host='127.0.0.1',
            user='root',
            passwd='',
            database='Python'
        )
        self.curr = self.conn.cursor()

    def open_spider(self, spider):
        print("spider open")

    def process_item(self, item, spider):
        print("Saving item into db ...")
        self.save(dict(item))
        return item

    def close_spider(self, spider):
        self.mysql_close()
##########################################################################

    def mysql_connect(self):
        try:
            return self.curr.connect(**self.conf)
        except self.curr.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(err)
#########################################

    def create_table(self):
        self.curr.execute(""" DROP TABLE IF EXISTS indigo""")
        self.curr.execute(""" Create table indigo(
        Product_Name text,
        Product_Author text,
        Product_Price text,
        Product_Image text
        )""")

    def process_item(self, item, spider):
        self.store_db(item)

    def store_db(self, item):
        self.curr.execute("""Insert Into indigo values (%s,%s,%s,%s)""",
                          (item['Product_Name'][0],
                           item['Product_Author'][0],
                           item['Product_Price'][0],
                           item['Product_Image'][0],
                           )
                          )
        self.conn.commit()

        return item

        self.conn.close()

*
Here is my code from my spider
import scrapy

from ..items import IndScrItem
class IndgoSpider(scrapy.Spider):
name = 'Indgo'
start_urls = ['https://www.chapters.indigo.ca/en-ca/books/?link-usage=Header%3A%20books&mc=Book&lu=Main']

def parse(self, response):
    items = IndScrItem()
    Product_Name= response.css('.product-list__product-title-link--grid::text').getall(),
    Product_Author= response.css('.product-list__contributor::text').getall(),
    Product_Price= response.css('.product-list__price--orange::text').getall(),
    Product_Image=  response.css('.product-image--lazy::attr(src)').getall()

    items['Product_Name'] = Product_Name
    items['Product_Author'] = Product_Author
    items['Product_Price'] = Product_Price
    items['Product_Image'] = Product_Image

    yield items

This is the line in the settings file that i have to enable pipelines
    ITEM_PIPELINES = {
   'IndgoScrp.pipelines.IndgoscrpPipeline': 100,
}

A: I actually found the issue was tied to having previously pip installed the wrong version of mysql-connector even though through my ide pycharm i had installed the correct one python was confused. After uninstalling both and reinstalling mysql-connector-python it was able to run.


text:
Q: perl XML::LibXML parsing issue of invalid char I am getting the following error while parsing XML with perl XML::LibXML library
file:///C://Users/yhussain/Desktop/DESKTOP/LTE%20TRX/output.xcm:3686518: parser
error : PCDATA invalid Char value 30
     ]▲W☺
                     ^
file:///C://Users/yhussain/Desktop/DESKTOP/LTE%20TRX/output.xcm:3686518: parser
error : PCDATA invalid Char value 1
     ]▲W☺
I used the following command to create a new file removing invalid char
perl -CSDA -pe's/[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]+//g' input.xml > output.xml

If you have better perl command to remove invalid char please let me know.


text:
Q: How to read content from application specific binary files in c# I am trying to read a binary file's contents using C#. Consider an application that can have files that are specific to the application, meaning users can open these files using only this application. The application may not give full access to a user, e.g., a certain user may be granted read-only access. Say I want to allow a certain user to open a file associated with my application and allow the user to edit the file. I have tried the following:
// Read the file into <bits>
var fs = new FileStream(@"c:\temp\test.appx", FileMode.Open);
var len = (int)fs.Length;
var bits = new byte[len];
fs.Read(bits, 0, len);
// Dump 16 bytes per line
for (int ix = 0; ix < len; ix += 16)
{
    var cnt = Math.Min(16, len - ix);
    var line = new byte[cnt];
    Array.Copy(bits, ix, line, 0, cnt);
    // Write address + hex + ascii
    Console.Write("{0:X6}  ", ix);
    Console.Write(BitConverter.ToString(line));
    Console.Write("  ");
    // Convert non-ascii characters to .
    for (int jx = 0; jx < cnt; ++jx)
        if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
}

However, I am not able to read the data from the application-specific binary file. Is there any other way that I can read the complete file contents?
I Updated my Question :
d        ÿþÿ5C
: \ U S E R S \
V S   T E C H N
O S \ D E S K T
O P \ T R A I N
I N G \ R A W \
1 \ S E C - 3 5
. X P R  ÿÿ
CProfileÿþÿ
   ²    çÂu°
º£ì?         €AÀ
          :
: §èH.
ÿ¡!ÀåÐ"ÛùÞ.À
 €AÀZd;ßOí ÀT㥛
Ä -À     €AÀ¨WÊ2
Ä1 ÀÚ¬ú\me+À
 €AÀHPüs×ÀÊTÁ¨
¤®)À     €AÀÄBi
Þ1À®¶bÙý'À
 €AÀ°çŒ(mÀ0»'
U&À     €AÀ¿}8
g"ÀƒÀÊ¡E¶$À
 €AÀÁÊ¡E¶sÀNÑ'\
þ##À     €AÀd]ÜF
i am able to read some text in human readable format and i can't remaining text which is like corrupted data.

A: Quick and VERY dirty version. I did this with a small binary file I have, and it worked perfectly.
var file = File.ReadAllBytes(fileName);
//Your byte array stuff, turn it from Binary to Byte array into memory aka byteArray

... //MORE STATEMENTS ETC....

//Reads your byteArray as a readable txt File that will allow them to read it accordingly in ENGLISH.

string result = System.Text.Encoding.UTF8.GetString(byteArray)


text:
Q: How to solve the Gem::LoadError in Ruby on Rails? I am new to Ruby, previously I installed an older Ruby and gem versions and I create one sample project.
Now I...

*

*uninstall the Ruby and all using uninstall program via control panel.

*install new versions of ruby and all.

*run the server - it throws a lot of errors.

I solved some problems but I am not able to solve the Gem::LoadError and rake db:migrate errors.

Please help me. Thanks in advance.

A: Try to add gem sqlite3 into your Gemfile and then run bundle in console.
It should look something like this
Gemfile
source 'https://rubygems.org'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'


text:
Q: ng if else template expression for different containers with same content How can I use Angular's if else template condition for rendering different containers with the same content?
something like this
<ng-container *ngIf="whichContainer; then container else other_container">

   content here...
</ng-container>

<ng-template #container><button>content...</button></ng-template>
<ng-template #other_container>
content..
</ng-template>


text:
Q: faking a httpcontext returning null I have been following different tutorials but all of them are returning null, code I have been  using is,
  public HttpContext SetNewHttpContext(string uRL)
    {
        var httpRequest = new HttpRequest("", uRL, "");
        var httpResponse = new HttpResponse(new StringWriter());
        return new HttpContext(httpRequest, httpResponse);
    }

I also tried
        public static HttpContext FakeHttpContext(string uRL)
    {
        var httpRequest = new HttpRequest("", uRL, "");
        var stringWriter = new StringWriter();
        var httpResponce = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponce);

        var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                new HttpStaticObjectsCollection(), 10, true,
                                                HttpCookieMode.AutoDetect,
                                                SessionStateMode.InProc, false);

        httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null, CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                            .Invoke(new object[] { sessionContainer });

        return httpContext;
    }

but non of them actually works, i am calling this context using
 SiteMapProvider contentMapProvider = SiteMap.Providers["SPContentMapProvider"];
 SiteMapNode currentNode = contentMapProvider.FindSiteMapNode(FakeHttpContext(Request.UrlReferrer.ToString()));

it gives me error

Operation is not valid due to the current state of the object.

Scenario
I need HTTPContext of a different ASP.NET page(sharepoint) A in Another ASP.NET page B, when we are being navigated from Page A to Page B.


text:
Q: How to iterate a list ? I am trying to iterate a list of (Users) and I am receiving this error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to br.com.meupacote.model.Usuario
at

Users is a class with @Entity annotattion. It's a table of my database.
I trying to interate this 2 forms:

List<Deg> lista = new ArrayList<Deg>();

degV.forEach(d -> {
  Deg dgust = Degustacao.builder().codProduto(d.getId().getCodProduto())
      .dataInicio(d.getDtaInicio())
      .dataFim(d.getDtaFim()).build();
  lista.add(dgust);
});

for (Usuario d : degV) {
  Deg dgust = Degustacao.builder().codProduto(d.getId().getCodProduto())
      .dataInicio(d.getDtaInicio())
      .dataFim(d.getDtaFim()).build();
  lista.add(dgust);
}

Sorry for my english.
Thanks in advance.

A: The problem is that I was not returning a Usuario List in the method that accessed my table. Since u was only selecting a few columns, I was returning an object list, so the cast error. I solved the problem by returning all the fields of the tables and selecting only the ones I wanted during the iteration to build the Deg obj.


text:
Q: d3.js - area chart vertical overflow if y.domain doesn't start at 0 How do I limit the contents of an area chart to stay inside the area determined by the two axes?
Here's the situation. If I set the vertical domain to be between 0 and the maximum of my data set, I don't have a problem:
y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);

However, sometimes I can't start from 0. When I need to start from the smallest number in the data set, the problem emerges:
y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);

As you see, the blue area of the chart flows over the bottom horizontal axis, and that's just ugly and messy. I could switch to a line chart to avoid this problem, but I'd much rather keep an area chart and resolve the issue. Any solutions?
EDIT This is the full code I'm using. If the full parameter is true, then the chart starts at 0. If not, then it starts at the data minimum.
function create_area_chart(data, full){
    var svg = d3.select(".chart-holder").append("svg").attr("width","800").attr("height", "400")
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y-%m-%d")
        bisectDate = d3.bisector(function(d) { return d.date; }).left;

    var x = d3.scaleTime()
        .rangeRound([0, width]);

    var y = d3.scaleLinear()
        .rangeRound([height, 0]);

    var area = d3.area()
        .x(function(d) { return x(d.date); })
        .y1(function(d) { return y(d.value); });

    data.forEach(function(d) {
        d.date = parseTime(d.date);
        d.value = +d.value;
    });

    x.domain(d3.extent(data, function(d) { return d.date; }));
    if(full)
        y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    else
        y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));

    g.append("path")
        .datum(data)
        .attr("fill", "steelblue")
        .attr("d", area);

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("Price ($)");

    svg.append("rect")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .attr("class", "overlay")
        .attr("width", width)
        .attr("height", height);
}

A: You need to set the floor for the area chart by changing y0
if(full){
    y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));
} else {
    y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0.91*d3.min(data, function(d) { return d.value; })));
}

see the docs: https://github.com/d3/d3/blob/master/API.md#areas
EDIT
Reproducing the Problem
Consider this area chart which OP's code is adapted from.
I run the code in the example and get the following plot:

Everything is as expected. The y domain and y0 are set as follows:
y.domain([0, d3.max(data, function(d) { return d.close; })]);
area.y0(y(0));

Now, if I change the y domain to:
y.domain([
    0.91*d3.min(data, function(d) { return d.close; }),
    d3.max(data, function(d) { return d.close; })
]);

I get the following plot:

We get the overflow, but if I now change the y0() to match the new y domain to:
area.y0(y(0.91*d3.min(data, function(d) { return d.close; })));

which plots:

The overflow has now been corrected.

A: I think the problem might come from the range of your scales.
Maybe try with
var y = d3.scaleLinear()
        .rangeRound([height-margin.bottom, margin.top]);

edit : it's probably not what's wrong with your code though, since you define height minus the two margins already. Sorry, best of luck !


text:
Q: Sorting in O(n) time? I'm stuck on this problem(2 weeks). Any idea of how to approach it?.

Let L be a list of n different integer numbers, assume that the elements of x of L are in the range [1,750]. Design a linear ordering algorithm to order the elements of L

I already tried with insertion sort. But i'm not sure if my approach is right:
Construct an array of bits. Initialize them to zero.
Read the input, for each value you see set the respective bit in the array to 1.
Scan the array, for each bit set, output the respective value.

Complexity => O(2n) = O(n)

A: Try Radix sort - http://en.wikipedia.org/wiki/Radix_sort
If you consider given 750 as constant, it sorts at O(n).
Comparison based sorting can't sort in less than O(nlogn), but if number of values is bounded by D, you can sort in O(D*n), or O(n) if you consider D as constant.

A: I won't give a full approach, but here's one observation that ought to help.
You already know that the numbers are strictly within the range [1, 750]. It's not particularly difficult to figure out how many of each number there are in linear time.
Once you have that information, how could you get back the sorted list (again, in linear time)?

As for the approach that you've given, that's not an insertion sort, it's more like a bucket sort or counting sort (which is what I was trying to hint at). The one thing I see is that your approach does not work if the array can contain duplicates. If you're given that there are none, then you're good to go. Otherwise, you'll need to modify what you have to deal with this.

A: You can use Counting sort. Make a Hash of inputs and at each insertion just increment the value at corresponding indexes. This sorts in O(n) time with extra memory O(n).

A: Here's some code:
IntegerSort (Array A):
   Dimension Work as Array[1..750]

   Fill Work with (0)

   For i:=0 to A.Length - 1
     Work[A[i]]++

   n = 0;
   For i:=1 to 750
      For j :=1 to Work[i]
         A[n++] = i

As all loops are O(n) the algorithm is O(n) as well.
In an array Work which spans over the complete range of numbers and which is initialized with 0, increase each element Work[k] by one,  with  k=A[i] for all elements of A.
Now reconstruct the array by scanning through the Work array. Any element >0 represents one or more elements in the original array. As we are scanning from 1 to 750, we will reconstruct the sorted array.


text:
Q: Cannot display images in ReactJS? I have multiple images instead of importing each image in my content.js like this eg:
import myimg1 from './myimg1.png'
import myimg2 from './myimg2.png'
import myimg3 from './myimg3.png'
import myimg4 from './myimg4.png'
I have made images.js and then imported each image inside images.js and exported it so that I can access those images in content.js:
images.js:
import java from './images/java.png';
import neural from './images/neural.png';
import logo from './images/logo.png';
import dsa from './images/dsa.png';
import dl from './images/dl.jpeg';
import ds from './images/ds.jpeg';
import boy from './images/boy.jpeg';
import ml from './images/ml.jpeg';
import phone from './images/phone.png';

export default {
    java,
    logo,
    dsa,
    dl,
    ds,
    boy,
    ml,
    neural,
    phone
}

In content.js:
import React, { Component } from 'react';
import images from './images';

I have made images folder which contains all images but I am not able to access the images and display it in content.js component.

A: See there is no class named images  in your images.js, so
import images from './images'

will do nothing in content.js...So try this way
images.js
import java from './images/java.png';
import logo from './images/logo.png';

export {
    java,
    logo
}

content.js
import React, { Component } from 'react';
import { java, logo } from './images';

A: the export default is just used for when there is only one import function, in your case you should do export without default
export {
    java,
    logo,
    dsa,
    dl,
    ds,
    boy,
    ml,
    neural,
    phone
}

Then, in your file, you'd import all inside brackets
import { java, logo, dsa.. } from './yourFilePath'


text:
Q: Yii (with Rights) is logging out users only in some computers I'm making a tutoring for students system in Yii 1.1.12 but I'm stuck in user session management.
I'm with other three guys in this. I'm using Rights for role management.
The problem is that two of the other guys are being logged out if a specific sequence of links is followed, but not me (neither the last guy).
The process is this:
We have a login form (the default login form Yii gives you, but with db login)

Then the user is presented in a dashboard where he has a menu and in the main info, theres a link (is equal to one in the left menu) to an action.

If the user clicks on the link (the blue one in the image) in the main part, they go to that action.

Here we have a table with registered tutors (in a db table) with a link (it looks like a button but is CSS, the gray ones under the red ones) to an action for assign students to that tutor.
Suddenly, the system logs out the user asking for username and password again

As you can see in the variables values we have Yii::app->user->isGuest() as true when this happens (before this it is false).
The button links are built like this:
<td>
  <?php echo CHtml::link('Dar de baja', array('desactivar', 'id'=>$academic->id), array('class'=>'btn btn-mini btn-danger')); ?>
  <?php echo CHtml::link('Expediente', array('view', 'id'=>$academic->id), array('class'=>'btn btn-mini')); ?>
</td>

And also the link in the second image is built that way:
<?php echo CHtml::link('Asignación e información de tutores', array('tutor/registered')); ?>

The left menu is a zii.widgets.CMenu and the $menu is built with:
array('label'=>'Asignación e información de tutores', 'url'=>array('/tutor/registered')),

The reason I'm explaining this is because this log out error only happens that way. If the user instead of choosing the blue link clicks the left menu item (both links looks the same) they dont get logged out.
EDIT: The user is logged out also if he clicks the left menu item.
Also, I don't get this error even if I click on the blue link, I tried in OSX with chrome, safari and firefox and Windows 8 with IE, even in Safari for iOS.
The two guys with that error used Windows with Chrome, Firefox and IE.
I thought it was an error with the action I was linking in the button but I changed it and still got the error.
I was thinking in a session issue or a cookie issue but I don't know what exactly to test, because I tested it in the same Browsers and didn't get the error.
Just to note, I'm using Rights module and we are testing the app in different locations (I can't go where the other two guys are to see if it has something to do with the ISP, but I don't think it is). Any suggestions?


text:
Q: iOS 7 - UISegmentedControl not staying highlighted? I have a UISegmentedControl that is being displayed within my UINavigationBar on an iPhone app running iOS 7.  I've noticed that when I select one of the values in the UISegmentedControl the highlighting does not stay active.  That is, if I select the first item, it triggers the action that I have added to it, but immediately un-highlights the value I selected.
Is this expected behavior?  A bug?  I don't recall ever seeing this in other apps using this control, and it works just fine on iOS 6.  Thoughts?

A: Make sure the momentary property of the UISegmentedControl is NO (Apple docs).


text:
Q: Eigen - diagonal update of sparse matrix What's the fastest way to edit the diagonal of a sparse matrix in Eigen? I've already filled it using triplets but I occasionally need to change all the diagonal values (they were already set to nonzero).

A: If acceptable, you could simply use their indices like
sp_mat(i, i)

As each access involves a binary search, the performance may not be satisfied. In this case, you could still achieve better performance with some restrictions.

*

*You  don't change the underlying layout of the matrix, e.g. adding/deleting nnzs, compressing;

*You will access the diagonal repeatedly.

With these restrictions, you could store the pointers of the diagonal components so that you can access the data later in O(1) time. You could get the pointer with
&sp_mat(i, i)

A: To complete kangshiyin answer, you can also edit the diagonal through dense vector expressions, for instance to add 1 to each diagonal element:
sp_mat.diagonal().array() += 1;

Warning: this will work only if the diagonal elements already exist, which is the case in the original question.


text:
Q: What is the best way to store information that can be accessed from within the code readily? I have been developing SharePoint solutions for quite a while I came across this situation where I have to implement customized revisions for the users because of the complex revision process.
The issue I am facing is for the concurrency, the requirement is that if there are two users trying to make a revision (revision is a new item in the document library with a few attributes same as the actual item) for an item only one of them should be given access and the other one should not see the custom form.
I somehow have to store a hashtable or if there's any other better suggestion to keep track of the current revisions being made, in memory, accessible to the farm and available on all app servers in the farm. I know about the distributed cache but using it is not recommended by Microsoft. Please suggest how do I implement this lock system on top of SharePoint.
Any help would be appreciated. Thank you.

A: Why not use check-out/check-in? When a document is checked out nobody else can make edits until it is checked back in. There is an option that says "Require Check Out" in library settings under "Versioning Settings" that will help you.


text: Q: What is the meaning of infinite covariance? When I fit a line to a given set of data points then all the elements of the covariance matrix comes out to be infinite . What is the meaning of this infinite covariance and what measures I should take?


text:
Q: Porting query from JPQL to mongo using spring data mongo Criteria I've ported some of my Entity from JPA to document and now porting some of my queries.
here is the JPA query:
em.createQuery("select distinct c from CustomerImpl c left join fetch c.addresses ca where (:name is null or c.firstName LIKE :name or c.lastName LIKE :name) and (:ref is null or c.externalReference LIKE :ref) and (:city is null or ca.city LIKE :city) order by c.firstName").setParameter("name", name).setParameter("ref", customerRef).setParameter("city", city).getResultList();

below is my attempt :
    Criteria orNameCriteria = new Criteria().orOperator(Criteria.where("firstName").is(null), Criteria.where("firstName").is(name), Criteria.where("lastName").is(name));
    Criteria orCustomerRefCriteria = new Criteria().orOperator(Criteria.where("externalReference").is(null), Criteria.where("externalReference").regex(customerRef,"i"));
    Criteria orAddress = new Criteria().orOperator(Criteria.where("addresses.city").is(null), Criteria.where("addresses.city").regex(city, "i"));
    Query nameq = new Query(new Criteria().andOperator(orNameCriteria,orCustomerRefCriteria,orAddress));

this query return zero size arraylist. I've then changed the orNameCriteria to use is clause and making sure the data contained in name variable has / as suffix and prefix. That didn't work as well.
but queries from mongoVue and RockMongo clients :
{ firstName: /SAM/}

returns data.
Question 1: How do you write LIKE CLAUSE with spring-data-mongo Criteria?
Question 2 : is that the right way to use or and and clause with criteria
Thanks for reading

A: Criteria.where("field").regex(pattern) should work

A: Since I don't have the ability add comments...
If you do a static import on Criteria, it will make your where clauses look a lot better.
Criteria orAddress = new Criteria().orOperator(where("addresses.city").is(null), where("addresses.city").regex(city, "i"));


text:
Q: Javascript continuous typing of string keep item faded in I dont want to have to write ifs within ifs for every letter of Bill gates typed in a textbox, do i split the letters into an array or what?
function callManagers(val){
    var val = $("#limitedtextarea").val();
    if (val.indexOf('@BillGates')<=-1) {
        if(val.indexOf('@') > -1) {
            if (val.indexOf('b') > -1 || val.indexOf('B') > -1) {
                $("#test").fadeIn();
            }
        }
    }
}

I want the user to be typing Bill gates and for test to stay faded in so long as they are doing that, but fade out if they type bill gates wrong.

A: Why not this?
var str = "@BillGates",
    val = $("whatever").val();
if(str.indexOf(val) === 0) { //means val is a substring of "@BillGates"
   //do fade in
}


text:
Q: Outlook 2007 client-only rule I am trying to create a rule in outlook but the rule is automatically becoming client-only. How do I prevent it?
The rule actions are: Move messages to a folder & display an alert.
The rule works fine if I just configure moving messages to folder. But, when I set display alert, it becomes client-only. I have read this. But, at least moving messages to folder part should work with server as well.
I read somewhere that there is fixed size for outlook rules. Does this have anything to do with it? I have just 5 rules btw and one of them is becoming client-only.

A: The answer to this is the same as the answer to the linked question.  If the rule is server-side, it is processed whether or not there is a client present and connected.  If you want to display an alert, then the client must be present, therefore it cannot be a server-side rule.
If you want it server-side, you cannot have an alert.  If you want an alert, you cannot have it server side.


text:
Q: Can/will a long running thread be terminated, when the app pool is still running I know that any threads that I've started will forcibly be terminated when the application pool is recycled or stopped, or when the process exits. I also know that IIS is not designed or intended for long running tasks.
Consider the following in Global.asax
protected void Application_Start(object sender, EventArgs e)
{
    _worker = new Thread(Run);
    _worker.IsBackground = true;
    _worker.Start();
}

private void Run()
{
    while(true)
    {
        Thread.Sleep(50000);

        WorkWork.BeHappyTo();
    }
}

Given that the process and application pool is not in any way shutting down, is there any other mechanism in IIS that could terminate my _worker thread, yet still continue to serve new request, as though nothing has happened?
I'm looking for any mechanism that monitors for threads not related to requests, CPU time, clock time, etc, and terminates them based on some set of heuristics.

A: No, your thread is safe for as long as the app domain lives. Terminating random parts of your app would not be a good design for a web framework. In fact there is no .NET API to enumerate all threads (thank god).
You need to handle errors, though, because an error will terminate the thread. Usually, logging them and continuing is the right approach. The logs should be looked at.
I find it to be a safer and easier pattern to have time-based scheduling outside of the application. Make a cron call a secret URL every 5 seconds.


text:
Q: how read binary data in go?(smartcard) convert code to java I need convert the following code to Java programming language. What does mean []byte{}? What is type uint8?
func int8ToByte(int_val int) byte {
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, uint8(int_val))
    if err != nil {
        log.Fatal("binary.Write failed:", err)
    }
    return buf.Bytes()[0]
}

A: []byte{} is a composite literal which creates an empty byte slice (of type []byte). The uint8 type is an unsigned integer type whose size is 1 byte. In Go the type byte is an alias for uint8, so byte and uint8 are equivalent and completely interchangeable.
I don't know who wrote your int8ToByte() function, but that seems like an obfuscation. All it does is it returns the least significant byte of its argument, which is nothing more than a simple conversion from int to byte:
byte(int_val)

See this Go example:
func main() {
    fmt.Println(int8ToByte(0x01))
    fmt.Println(int8ToByte(0x0102))
    fmt.Println(int8ToByte(-1))

    var i int
    i = 0x01
    fmt.Println(byte(i))
    i = 0x0102
    fmt.Println(byte(i))
    i = -1
    fmt.Println(byte(i))
}

func int8ToByte(int_val int) byte {
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, uint8(int_val))
    if err != nil {
        log.Fatal("binary.Write failed:", err)
    }
    return buf.Bytes()[0]
}

It outputs (try it on the Go Playground):
1
2
255
1
2
255

To achieve the same in Java, you again just have to convert the int number to byte:
 public static void main(String []args){
    int i = 0x01;
    System.out.println((byte)i);
    i = 0x0102;
    System.out.println((byte)i);
    i = -1;
    System.out.println((byte)i + " " + String.format("%x", (byte)i));
 }

This outputs:
1
2
-1 ff

Note the difference: Java's byte is signed, it has a valid range of -128..127, while Go's byte is unsigned, its valid range is 0..255. But the binary representation of both outputs are the same. For details, see Java vs. Golang for HOTP (rfc-4226).


text:
Q: Link of react-router-dom updates the URL without rendering the component I'm using the react-router-dom Link component to manage my navigation but it doesn't work.
The Link changes the URL but doesn't render the component.
Here is a simple app describing my problem. I'm trying to use My App header as go home link:
    import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import React from 'react';

const Navigation = () => {
  return (

      <Link to="/events">

My Application

      </Link>

  );
};
const ConnectedNavigation = connect((state) => state)(Navigation);

export default ConnectedNavigation;

App.jsx code :
import React from 'react';
import { Provider } from 'react-redux';
import { store } from '../store/index';
import ConnectedDashboard from './Dashboard';
import ConnectedEventDetails from './EventDetails';
import { Router, Route } from 'react-router-dom';
import { history } from '../store/history';
import ConnectedNavigation from './Navigation';

export const Main = () => (
  <Router history={history}>
    <Provider store={store}>

        <ConnectedNavigation />
        <Route exact path="/events" render={() => <ConnectedDashboard />} />
        <Route
          exact
          path="/event/:id"
          //match prop is necessary in order to determine which event
          //we are looking for
          render={({ match }) => <ConnectedEventDetails match={match} />}
        />

    </Provider>
  </Router>
);

As you can see i added exact on my Routes to avoid any confusions

A: This problem comes from this line:
import { Router, Route } from 'react-router-dom';

The correct import is :
import { BrowserRouter as Router, Route } from 'react-router-dom';


text:
Q: Graph for tire contact patch, related to negative camber in a car tire I don't know if this should be on stack overflow or here, but I'm gonna ask it anyway:
I need an equation for the graph of relation between the camber angle (the angle between the ground and the axis of rotation) and contact patch in a tire.
For angle $\theta=0$, the area is a.
For some angle $\theta_{max}>\theta$, the area is $a_{max}>a$.
For another angle $\theta_{min}>\theta_{max}$, the area theoretically is 0. (This is practically impossible.)
X axis is camber angle, while y axis is contact patch.
The graph is a curve with $\theta_{max}$ in the first quadrant.
The curve also doesn't start from 0, but from $a$ (area) on y axis, moving up until $a_{max}$, corresponding to $\theta_{max}$ on x axis and then falling until it intersects the x axis at $\theta_{min}$.
Any quick and dirty solution would do, as long as it bears some semblance to the curve I described above. Thanks in advance. Also, I couldn't post the picture of the graph because either the internet is crap, or there's something wrong with my mobile phone, so I'm sorry.


text:
Q: Speed Time and distance question A person walks from his house to school at 2.5 km/h and arrives 12 minutes late. When he comes back from school to home at a speed of 4km/h, he reaches 15 minutes early. What is the distance?
The answer is 3km
I have no idea how to solve this question. Can somebody please explain to me how to get the answer?

A: Hint :
distance = rate $\times$ time.
Assume distance = $D$, morning trip takes time $(T + 0.2)$ and afternoon trip takes
time $(T - 0.25).$
Morning rate was $R_1 = 2.5$ km/h and afternoon rate was $R_2 = 4$ km/h.
Then $D = R_1 \times (T + 0.2)$ and $D = R_2 \times (T - 0.25)$.
You have two (non-linear) equations in two unknowns, $D$ and $T$.
You can solve for these two variables.


text:
Q: Deploy legacy .net framework console application to on prem server using Azure DevOps CICD pipeline I am new to DevOps and CICD pipelines.
I successfully deployed ASP .NET MVC website using Azure DevOps CICD pipeline to my onprem agent/machine using Azure DevOps.

Similarly I want to deploy a console application which can be
  ultimately used as scheduled job in windows 'Task Scheduler' or either
  as a 'Windows Service'. Right now I am managing these deployments
  manually but after seeing the power of DevOps I hope, there could be
  really some automated solution for console apps as well.

The applications are built in legacy framework like 3.5 to 4.5, so not .net core apps.
I found lot of online articles which demonstrates deploying webjobs on azure or may be possible for onprem but is it possible for old console apps?
I tried to build a very simple console app in Framework 4.7 and tried to deploy/copy/publish to my onprem machine's shared path. Gave permission to VSTS agent services which are running but copy files and publish artifact tasks are failing. I tried to do it in both CI and CD pipelines but all are failing.
Please review the pipelines and logs and suggest where I am doing wrong or there are any alternatives?
https://dev.azure.com/MSTCsandippatel/DemoConsoleApp

2019-11-05T05:03:52.8436105Z ##[error]Publishing build artifacts
  failed with an error: Unable to create directory '\MAHANTAM\Azure
  Artifacts\DemoConsoleApp'. Unable to verify the directory exists:
  '\MAHANTAM\Azure Artifacts\DemoConsoleApp'. If directory is a file
  share, please verify the share name is correct, the share is online,
  and the current process has permission to access the share.

CI pipeline 1
trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:
- task: NuGetToolInstaller@1

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=True /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'DemoConsoleApp'
    publishLocation: 'Container'
trigger:
- master

pool:
  vmImage: 'windows-latest'

variables:
  solution: '**/*.sln'
  buildPlatform: 'Any CPU'
  buildConfiguration: 'Release'

steps:
- task: NuGetToolInstaller@1

- task: NuGetCommand@2
  inputs:
    restoreSolution: '$(solution)'

- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=True /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'DemoConsoleApp'
    publishLocation: 'Container'

CI pipeline 2
pool:
  name: Azure Pipelines
  demands:
  - msbuild
  - visualstudio

steps:
- task: NuGetToolInstaller@0
  displayName: 'Use NuGet 4.4.1'
  inputs:
    versionSpec: 4.4.1

- task: NuGetCommand@2
  displayName: 'NuGet restore'
  inputs:
    restoreSolution: '$(Parameters.solution)'
    vstsFeed: '622d44e2-69d4-4d42-bb91-9d6ddd97f9ba/8eaf9077-829d-4567-93c0-8e0d7973634b'

- task: VSBuild@1
  displayName: 'Build solution **\*.sln'
  inputs:
    solution: '$(Parameters.solution)'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'

- task: PublishSymbols@2
  displayName: 'Publish symbols path'
  inputs:
    SearchPattern: '**\bin\**\*.pdb'
    PublishSymbols: false
  continueOnError: true

- task: CopyFiles@2
  displayName: 'Copy Files to: $(build.artifactstagingdirectory)'
  inputs:
    SourceFolder: '$(system.defaultworkingdirectory)'
    Contents: '**\bin\$(BuildConfiguration)\**'
    TargetFolder: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

- task: CopyFiles@2
  displayName: 'Copy Files Task'
  inputs:
    SourceFolder: '$(system.defaultworkingdirectory)'
    Contents: '**/**'
    TargetFolder: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

- task: ArchiveFiles@2
  displayName: 'Archive $(Build.BinariesDirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact: DemoConsoleApp'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
    ArtifactName: DemoConsoleApp

A: If you use Agent Pool "Azure Pipelines" for your agent, the deployment will occur on an azure cloud machine which doesn't know anything about your on-premise machines.

You should install a self-hosted agent on-premise and link that to your DevOps and use that for the agent.
https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/v2-windows?view=azure-devops


text:
Q: django-dynamic-formset shows "add" and "remove" buttons in the wrong place My app was working fine yesterday.  After I started playing with the .css properties in the browser , suddenly the django-dynamic-formset script is not working properly anymore.  It shows "Add" and "Remove" buttons for each input in the form, instead of for each row.  Please see the photo attached.
{% load crispy_forms_tags %}
{% load staticfiles %}
{% load static %}

{{ formset.management_form|crispy }}

    {% for form in formset.forms %}

                {% for field in form.visible_fields %}

                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field|as_crispy_field }}

                {% endfor %}

    {% endfor %}

{{formset.media}}

`

Also, its not respecting the renaming I gave (see script at the end of the code).  Instead of the "Agregar Posicion" text, shows the default one which is "Add another".

A: You have got a few different issues going on:
First, you are calling the .formset function directly on a jQuery object.  Per the docs, it needs to be wrapped in an "on-ready" function, like this, for example:

This should solve the issue with the custom parameters not being used, as they weren't passed to the .formset function.
As for the adding the tag to each input, you didn't supply your views.py or forms.py files to know what you are actually passing to the template, but from my experience working with the django-dynamic-formset plugin, it's persnickety.  I have found that using the class name selector works best if you're working with divs in forms, but the example from the docs using tables works best with tables. If you assign your table an "id" and then added a tbody tag, you would change the code to this:

Also, without seeing your views.py file, but I'm not sure why you're using
{% for form in formset.forms %}

You should just be passing the formset from your view to your template and referencing it as
{% for form in formset %}


text:
Q: An error occurred because there is no graphics environment available I am getting below error when I try to use hudson and maven, Any idea how to resolve?
Xlib: connection to ":1.0" refused by server
Xlib: No protocol specified

[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] An error occurred because there is no graphics environment available.  Please set the headless-server setting in the Flex configuration file to true.
[INFO] ------------------------------------------------------------------------
[INFO] Trace
java.lang.InternalError: An error occurred because there is no graphics environment available.

Thanks
sharp

A: Under <compiler> tag in flex-config.xml add
<headless-server>true</headless-server>


text:
Q: Как на C# проверить, запущена ли служба "Х" или нет, и узнать тип запуска(авто) и изменить параметры-выкл,включить, поставить в автозапуск? Как на C#  проверить, запущена ли служба Windows "Х" или нет, и узнать тип запуска(авто) и изменить параметры-выкл,включить, поставить в автозапуск?

A: Есть класс ServiceController. Я думаю, что его функционала будет достаточно и не нужно лезть в WinApi.
UPD:
Единственное, чего не хватает в ServiceController, как я понял - это смены типа запуска.
В этом случае можно вспользоваться методами отсюда.
Предлагается:

*

*Обратится к WinApi

*Обратится к WMI

*Обратится к CMD

Еще нашел вариант через реестр:
   using System;
using Microsoft.Win32;

public enum ServiceStart
{
Boot = 0,
System = 1,
Automatic = 2,
Manual = 3,
Disabled = 4
}

public class ServiceController2 : System.ServiceProcess.ServiceController
{

public ServiceStart ServiceStart
{
 get
 {
    RegistryKey key = Registry.LocalMachine.OpenSubKey(
     "SYSTEM\\CurrentControlSet\\Services\\" + this.ServiceName );
      ServiceStart start = (ServiceStart)key.GetValue("Start");
     key.Close();
     return (start);
 }

 set
 {
       RegistryKey key = Registry.LocalMachine.OpenSubKey(
         "SYSTEM\\CurrentControlSet\\Services\\" + this.ServiceName, true );
       key.SetValue( "Start", (int)value );
       key.Close();
}
}
}
}

A: Список WinAPI:
OpenSCManager() + OpenService() - открытие конкретного сервиса по имени. Заодно проверка на наличие такого сервиса в принципе. Потом:
QueryServiceStatusEx() - текущее состояние сервиса
QueryServiceConfig() - тип запуска
ChangeServiceConfig() - изменение параметров, включая тип запуска
ControlService() - приостановка или остановка сервиса.


text:
Q: Демон оповещений (фоновая программа) на Java Недавно начал изучать тему ботов ВК, Телеграм и других соц сетей. У них есть одна проблема: чтобы увидеть оповещение об появлении новой информации на каком-либо сайте (том же YouTube) нужно быть активным в соответствующей соц-сети или запустить браузер.
Можно ли совместить такого бота с оповещениями и демона (сервис), который бы отслеживал появление новых видео на интересных мне каналах и поверх всех запущенных окон запускал оповещение?
Можно ли как-то отследить обновление информации на сайте программно? Какую библиотеку (пакет) следует изучить для подобной работы с сайтом?
P.S. Лучше знаю Java, чем С++, поэтому хотелось бы найти реализацию на Java, но если на С++ по каким-то причинам легче реализовать данную задачу, объясните, спасибо.

A: Примерно то что ты описываешь вполне возможно.
за ютуб не скажу но вк, телеграм советую смотреть в сторону api данных сетей.
Либо регулярные http запросы (принцип как у парсеров - парсишь страницу раз в 10 секунд если появился новый элемент вызываешь в новом потоке открытие окна-уведмления)
Kибо использовать api
https://vk.com/dev/first_guide
https://core.telegram.org/
На java есть готовые библиотеки для работы с api telegram и vk


text:
Q: Prevent JS code to run, before function has ended I can't wrap my head around this one?
WHY IS IT THAT MY:
.each loop runs right through even though I'm stalling things inside by 1000ms per loop?

The problem is that the window.location.href command runs TO EARLY before the setTimeout has finished? Same for the stopload() function which is also ended to early? I have seen something about recursive setTimeout functions is that what is needed here and how do I implement that?
function shop(clickedButton)
{
  var buttonvalue = $(clickedButton).val();
  startLoad();
  pdel = 1000;

  $("input:submit[value='buy']").each(function(index)
  {
    if(index != 1)
    {

       $("#backgroundPopup").text(index);
       var submithing = this;
       setTimeout(function(){ clicksubmitbutton(submithing); },pdel);
       pdel += 1000;
    }
  });

  stopLoad();

  if(buttonvalue == "1")
  {
     window.scrollTo(0,0);
  }
  else
  {
     window.location.href = 'http://my.url';
  }

}

A: Javascript has no notion of a sleep, or stall.  Execution continues right past a setTimeout call.  This function simply schedules a function to be run after the given number of milliseconds.
In order to get your desired behavior, you need to call the next iteration in the setTimeout callback function.
Something like:
function submitTheThing(index) {
    if (done) { //some logic
        return;
    }

    // do something

    setTimeout(function() { submitTheThing(index+1); }, 1000);
}


text:
Q: Meteor - What is the best process for securing forms and storing sensitive data I'm building my first app with Meteor and I'd like to know the best security measures to take in a couple of situations...

*

*How do I ensure users are not submitting commands like drop table to my forms? Do I have to manually sanitize somehow or is this automatically handled?

*Normally I would use a GET on forms if it asks the user for sensitive information, however I'm confused how Meteor handles inserting items to the db. Is the info submitted through forms secure or is it being passed over somewhere people can it?

*If I have removed the autopublish and the insecure packages it means users cannot just query for other user information, is that correct?
Sorry, if these are noob questions. I haven't quite wrapped my head around how the security of an app all fits in but any help would be much appreciated :)

A: Here is a quick rundown of the basics of securing your meteor app:

*

*Transmit everything over HTTPS.

*Separate your client and server code into their own directories. A great way to keep your server-side secrets safe is to never send them to the client in the first place.

*Remove the insecure package.

*Remove the autopublish package.

*Add the audit-argument-checks package and add checks to all methods and publish functions.

*Add the browser-policy package (after completing all of the above).

Here are some answers to your questions:

*

*If insecure is removed and you don't have any allow rules, then users can't remove anything. Regardless, documents on the client can only be removed or updated by id, so you can't drop a collection with a single command.

*With the proper allow rules specified, then the client can execute an insert/update. Otherwise, you can use a meteor method to have the server perform an insert/update for you. e.g. you can specify a method like postsInsert on the server. Messages will be passed between the client and the server in the clear unless you use SSL.

*Correct. With autopublish off, you need to specify which documents are published to the client - otherwise the client will not have read access to any documents.

A: If you don't want your users to perform certain operations, you don't allow them to do so. The only commands your users are able to perform on the database are those you specify : when you remove the insecure package, typing Collection.remove({}); in the browser console won't drop the entire collection, users will have to Meteor.call certain allowed operations (through Meteor.methods) to perform authenticated-only stuff.
Generally, you want the OWNER of a resource to be able to edit/delete it, but other people shouldn't be able to modify it.
If you have an edit form for one of your collection, you will likely have corresponding Meteor.methods to edit/delete it.
Inside a Meteor.method, you can check the passed arguments received from the client to validate data correctness, you can also verify if the call was issued from an allowed user (typically the owner of the document).
Hopefully, Meteor comes with a Match framework to test parameters sent to Meteor.methods.
// define a test to check if a document is editable by a certain user
EditableDocument=function(userId){
    return Match.Where(function(documentId){
        var document=Collection.findOne(documentId);
        if(!document){
            throw new Meteor.Error(500,"Document doesn't exist !");
        }
        if(userId!=document.creator._id){
            throw new Meteor.Error(500,"Can't update a document you don't own.");
        }
        return true;
    });
};

Meteor.methods({
    updateCollection:function(documentId,fields){
        check(documentId,EditableDocument(this.userId));
        check(fields,{
            field1:Match.Optional(String),
            field2:Match.OneOf(Number,Boolean),
            field3:Match.Any
        });
        // if the tests pass, do your thing
        ...
    }
});

To communicate form data between the client and the server, Meteor uses DDP (Data Distributed Protocol) with a technique known as Remote Method Invocation.
A client can Meteor.call a Meteor.method declared in the server and get a response asynchronously.
This is different from classic form submition manipulation techniques which is done using HTTP, and can use its secure counterpart HTTPS, to encrypt data between a client and the server, avoiding data sniffing issues.
DDP supports data encryption and every *.meteor.com hosted sites are using meteor.com certificate to ensure that all traffic is properly encrypted using SSL.
On your own hosting solution, you will have to handle this yourself though.
https://groups.google.com/forum/#!topic/meteor-core/a9dPA1-mgXA
After removing autopublish, every server resources won't be published to all clients no more, meaning that one can't just query your collections to get other users documents access.
Be sure to read the docs at least once to fully understand Meteor related aspects of web development.


text:
Q: Do delegated elements for an event need to be present when binding In JQuery? I am encountering condition where part of the page isn't present when I try to bind elements on that part of the page. I would like to know if I can avoid the issue by delegating off of a container that is present. To give an example, suppose that I have the following:
$('.contianer').on('click', '.button1', function () {
  console.log('success');
});

Suppose that the code above get's triggered before '.button1' exists but '.container' does exist. Will the console log success in this scenario?


text:
Q: "Can't find any matching row in the user table" when attempting "SET PASSWORD" When I do SELECT User, Host FROM mysql.user I see that I have a user named myuser on %. I tried setting that users password thusly:
SET PASSWORD FOR 'myuser'@'%' = 'mypassword';

Doing so, however, resulted in this error:
Error Code: 1133. Can't find any matching row in the user table

Any ideas?

A: If I recall correctly wildcards in hostnames in this context.  You're explicitly trying to set a password for 'myuser'@'%', not any user named myuser.
You will need to get a list of users and their hostnames and set the password for each of them if they all should indeed have the same password.


text:
Q: Invalid Directory path while executing a procedure that produces a csv file in Oracle (in windows) I have a procedure
create or replace procedure dump_table_to_csv( p_tname in varchar2,
  2                                                 p_dir   in varchar2,
  3                                                 p_filename in varchar2 )
  4  is
  5      l_output        utl_file.file_type;
  6      l_theCursor     integer default dbms_sql.open_cursor;
  7      l_columnValue   varchar2(4000);
  8      l_status        integer;
  9      l_query         varchar2(1000)
 10                      default 'select * from ' || p_tname;
 11      l_colCnt        number := 0;
 12      l_separator     varchar2(1);
 13      l_descTbl       dbms_sql.desc_tab;
 14  begin
 15      l_output := utl_file.fopen( p_dir, p_filename, 'w' );
 16      execute immediate 'alter session set nls_date_format=''dd-mon-yyyy hh24:mi:ss''
';
 17
 18      dbms_sql.parse(  l_theCursor,  l_query, dbms_sql.native );
 19      dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );
 20
 21      for i in 1 .. l_colCnt loop
 22          utl_file.put( l_output, l_separator || '"' || l_descTbl(i).col_name || '"'
);
 23          dbms_sql.define_column( l_theCursor, i, l_columnValue, 4000 );
 24          l_separator := ',';
 25      end loop;
 26      utl_file.new_line( l_output );
 27
 28      l_status := dbms_sql.execute(l_theCursor);
 29
 30      while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
 31          l_separator := '';
 32          for i in 1 .. l_colCnt loop
 33              dbms_sql.column_value( l_theCursor, i, l_columnValue );
 34              utl_file.put( l_output, l_separator || l_columnValue );
 35              l_separator := ',';
 36          end loop;
 37          utl_file.new_line( l_output );
 38      end loop;
 39      dbms_sql.close_cursor(l_theCursor);
 40      utl_file.fclose( l_output );
 41
 42      execute immediate 'alter session set nls_date_format=''dd-MON-yy'' ';
 43  exception
 44      when others then
 45          execute immediate 'alter session set nls_date_format=''dd-MON-yy'' ';
 46          raise;
 47  end;
 48  /

When I try to execute
exec dump_table_to_csv('emp', 'C:\Temp','a.txt')

I am getting the error
(Error): Error executing statement: ORA-29280: invalid directory path ORA-06512: at "LCM_EVAL.DUMP_TABLE_TO_CSV", line 59 ORA-06512: at line 2
What is the possible problem?

A: The error message is pretty clear: the path is invalid. Most probably it is just a typo: C:/Temp doesn't exist, but maybe C:\Temp does.
It could also be a problem with grants. In PL/SQL you only have access to the disk if you have been given a specific right. The UTL_FILE documentation explains how to grant access to PL/SQL:

*

*(recommended) Create a directory with a dba account, grant access to user.

*(obsolete) Use the UTL_FILE_DIR system parameter. Be careful, this is a system-wide parameter, all users will be able to write and read this directory.

A: You should create an Oracle DIRECTORY object first, then refer to that object in the call to fopen instead of passing the filesystem path.
More info: http://www.orafaq.com/wiki/Oracle_directory

A: Anything to do with UTL_FILE happens on the database server, not the client. Make sure the directory exists on the server, and that the Oracle user has permission to write to it.


text:
Q: How to reconstruct raw data from scaled data? I have some data on which I applied scaling with scikit-learn.
Once scaled I would like to recover the original data.  Is this possible? If not, how can I get correspondance from the original data.
Here a toy example
from sklearn.datasets import load_iris
from sklearn.preprocessing import scale
iris = load_iris()
X = iris.data
X_scale = scale(X)
print X[:4]
print X_scale[:4]

producing
[[ 5.1  3.5  1.4  0.2]
 [ 4.9  3.   1.4  0.2]
 [ 4.7  3.2  1.3  0.2]
 [ 4.6  3.1  1.5  0.2]]
[[-0.90068117  1.03205722 -1.3412724  -1.31297673]
 [-1.14301691 -0.1249576  -1.3412724  -1.31297673]
 [-1.38535265  0.33784833 -1.39813811 -1.31297673]
 [-1.50652052  0.10644536 -1.2844067  -1.31297673]]

How from the second data can I recover the original data?

A: One of the most common types of feature scaling methods scales the data by setting the mean value of a data set to zero, and the standard deviation to one. This is extremely useful for many learning algorithms. This is achieved simply using the following:
scaled_array = (original_array - mean_of_array)/std_of_array

In Sklearn, each array column appears to be scaled in this way. To find the original data, simply rearrange the above, or alternatively just calculate the standard deviation and mean of each column in the unscaled data. You can then use this to transform the scaled data back to the original data at any time.
For more information on how Sklearn's scaling works, the docs are here. To understand more about feature scaling generally, the wiki page is a good place to start.

A: MarkyD43 has provided a great answer to this question.  Here is the code version of transforming the data back to the original version
from sklearn.datasets import load_iris
from sklearn.preprocessing import scale
iris = load_iris()
X = iris.data

mean_of_array = X.mean(axis=0)
std_of_array = X.std(axis=0)

X_scale = scale(X)

X_original = (X_scale * std_of_array) + mean_of_array

print X[:4]
print X_original[:4]

producing
[[ 5.1  3.5  1.4  0.2]
 [ 4.9  3.   1.4  0.2]
 [ 4.7  3.2  1.3  0.2]
 [ 4.6  3.1  1.5  0.2]]
[[ 5.1  3.5  1.4  0.2]
 [ 4.9  3.   1.4  0.2]
 [ 4.7  3.2  1.3  0.2]
 [ 4.6  3.1  1.5  0.2]]


text:
Q: Find out which div was clicked and pass it to the click function handler? I'm adding a list of child divs (cards) by looping through an array. I want to create an onclick event listener for each child div (card) of parent div (board).

$.each(cardArray, function(i,value){

if(i<9){
  var tCard = $('
'+cardArray[i]['damage']+'
')
  $("#area_myCards").append(tCard)
}

});
$("#area_myCards > .cardContainer").on('click',cardClick())

but I'm unsure how to find out which child div was clicked and pass it to cardClick()?
I'm also going to be using the child's data-id within cardClick() and I'd like to know how to get this- should I pass it to the function in the on click listener somehow, or do it within the function?

A: Something like this?

const cardArray = [
  {name: 'A', damage: 'A-D'},
  {name: 'B', damage: 'B-D'},
  {name: 'C', damage: 'C-D'},
  {name: 'D', damage: 'D-D'},
  {name: 'E', damage: 'E-D'},
  {name: 'F', damage: 'F-D'},
  {name: 'G', damage: 'G-D'},
  {name: 'H', damage: 'H-D'},
  {name: 'I', damage: 'I-D'}
];
$.each(cardArray, function(i,value){

if(i<9){
  var tCard = $('
'+cardArray[i]['damage']+'
')
  $("#area_myCards").append(tCard)
}

});
$("#area_myCards > .cardContainer").on('click',e => cardClick(e.target))

const cardClick = (div) => {
  $(div).toggleClass('clicked');
};
.cardContainer { margin: 2px; padding: 10px; border: 1px solid #eee; }
.cardContainer.clicked { background-color: red; }

A: Assuming that cardClick() is defined somewhere else, first of all, you would call it with $("#area_myCards > .cardContainer").on('click',cardClick) (without the parenthesis at the end).
That function would get passed an event as its first argument (usually called e), and the event has a property called currentTarget that can be used to see which instance has been clicked.
From MDN:

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

So the cardClick function would be something like:
const cardClick = (e) => {
    const targetInstance = e.currentTarget;
    // Do stuff with your specific card...
    // To access data-id: targetInstance.getAttribute('data-id')
    // or targetInstance.dataset.id
}


text:
Q: Find function and regex in lua  local ct = s:find('[ \t]', 80)

find function in Lua is generally used to find a particular pattern in a given string.  In above line of code, we are passing '[ \t]' as the pattern to find along with 80.
What does it mean to pass [ \t] as the pattern to find and where is this 80 coming from?
As far as I know, find function takes only two parameters i.e the string and the pattern to find.
Thanks

A: The pattern [ \t] matches one space or one tab.
The match is attempted starting at position 80 in the given string.
string.find accepts two optional arguments besides the string and the pattern.


text:
Q: fatal: ssh variant 'simple' does not support setting port When I clone a remote GitLab project, I get the following error:
error fatal: ssh variant 'simple' does not support setting port

I tried to re-install TortoiseGit, but this did not solve the issue.

A: The internal behavior of Git (>=2.16.0) for SSH tool detection changed and TortoiseGitPlink is not detected any more as ssh or plink compatible.
This only affects if the SSH URL contains a port or you have configured Git to use the Protocol version 2. For now, you need to set the environment variable GIT_SSH_VARIANT to ssh or configure it in Git settings using git config --global ssh.variant ssh.
In the next version of TortoiseGit 2.5.7 this will be done automatically when TortoiseGitPLink is invoked by TortoiseGit (cf. https://tortoisegit.org/issue/3139). If you use TortoiseGitPLink from CLI the setting is still needed).
Update (TLDR):

*

*Update TortoiseGit to the latest stable version: https://tortoisegit.org/download/

*I f you use TortoiseGitPLink from Git CLI also issue git config --global ssh.variant ssh on CLI or set the environment variable GIT_SSH_VARIANT to ssh.

A: if you are using Windows version of git, try this:
git config --global ssh.variant ssh
This is a better option for those who don't want to clutter the environment variables a lot.

A: Set environment variable GIT_SSH_VARIANT to ssh. This will solve the problem.
export GIT_SSH_VARIANT=ssh


text:
Q: Obtain XML element's value from REST server response using Ruby n00b REST question. I'm making a GET request to an API's endpoint and getting the proper XML response. The question I have is, how do I get the value of a particular XML element in the servers REST response using Ruby?
So let's say one of the elements is 'Body' and I want to assign its value 'Blah blah blah' to a variable
Part of the XML response:
<Body>Blah blah blah</Body>

How would I do that with the response? Basically I want to do something like this
variable = params["Body"]

Thanks in advance!

A: The best solution is to use RestClient or HTTParty and have it parse the response for you.
Otherwise, you'll have to parse the response itself using a library such as Nokogiri:
doc = Nokogiri.XML(response)
variable = doc.at("body").text

A: You'll want to use an XML parser of some kind.
It sounds like you want something like XmlSimple, which will turn an XML document into ruby arrays and hashes. There's tons of examples of how to use it on the page that has been linked.
One thing to be aware of is that XML to native container mappings are imperfect. If you're dealing with a complex document, you'll likely want to use a more robust parser, like Nokogiri.

A: If you want full XML Object Mapping, HappyMapper is a decent library, although it isn't very active anymore. It can work with XML from any source, so you'll still want something like the libraries mentioned by @Fitzsimmons or @MarkThomas to do the HTTP request.


text:
Q: Why orientation of plane region boundary implies surface boundary? For parametrized surfaces $\Phi:D\to \mathbb R^3,$ we assume that $\Phi$ is one to one on the whole of $D$. Then the image of $D$ is $S$ and we define the image of $\partial D$ (the boundary of $D$) is  $\partial S$ (But I'm sure I'm missing something, eg., we know boundary of sphere (as surface $\mathbb R^3$) is empty).

Question: (1)If we assume that $\partial D$ is oriented as in Green's theorem, Can we get an orientation for $\partial S$ and $S$ itself is oriented so $\Phi_u \times \Phi_v$ is in the direction of the normal.  (2) Is the above definition of boundary  of surface  is correct in $\mathbb R^3$? If so, then I think  then $\partial S \neq \emptyset$

If $D$ is a  plane  region, with boundary curve $C,$ the positive orientation of $C$ is given by  the vector $k\times v_{out},$ where $v_{out}$ is the normal vector field pointing outward along curve.
As you walk along $C$ in the direction of positive orientation, the region $D$ is on your left.
Edit: Assume that $D$ is  plane region of elementary type (as in Greens theorem)

A: I think what's going on is that you are thinking about a somewhat restricted version of Stokes Theorem, which I'll refer to as the "singly parameterized Stokes Theorem", in which one assumes that the surface $S$ is restricted to be a parameterized surface, with parameterization $\Phi : D \to S$ as stated in your question. In that case all I can say is that the answers to your two questions are "Yes" and that $\partial S$ is indeed nonempty, for the reasons that you suggest.
However, there is a more general version of Stokes Theorem where $S$ is not assumed to be "singly parameterized", and where $\partial S$ is allowed to be empty. In this more general situation there is no guarantee that $S$ is orientable (the Möbius band is a nonorientable, for example), and therefore the more general version has an extra hypothesis requiring that $S$ be orientable, and another hypothesis that $S$ be compact. The proof of this general version of Stokes Theorem does make use of the multiple coordinate systems needed to cover an arbitrary oriented surface $S$.
For example this more general version of Stokes Theorem does indeed apply to the case that $S \subset \mathbb R^3$ is the unit 2-sphere (which means the boundary of the unit 3-ball in $\mathbb R^3$). Of course we know intuitively that the unit 2-sphere is not a "singly parameterized" surface. For example spherical coordinates do not apply to the north or south pole, so we have to add a "north polar" coordinate system and a "south polar" coordinate system, which gives a covering of the unit 2-sphere by three coordinate systems. You can actually do better and cover the unit 2-sphere with only two coordinate systems. But there does not exist any single coordinate system that covers the whole 2-sphere in a one-to-one fashion.
It is difficult to explain the details of coordinate systems, orientations, and boundaries without some more advanced knowledge of manifolds, which one eventually learns about in a course on differential geometry or differential topology.


text:
Q: Tipo de campo adequado para guardar moeda no Oracle Tem algum problema em salvar dados com vírgulas ou ponto (.) no meu banco de dados (SQL Developer)? Qual é a variável mais adequada para se declarar para campos do tipo moeda (preço)?

A: Você pode gravar qualquer dado no banco de dados, depende do que deseja.
O tipo de coluna mais correto para guardar dinheiro é um NUMBER com casas fixas (há alternativas). Exemplo:
NUMBER(19, 4)

Coloquei no GitHub para referência futura.
Isso permite 19 dígitos com 4 na parte decimal.
Cuidado para não usar tipo errado e ter prejuízos.

A: Para declarar campos do tipo moeda é melhor você usar um Decimal/Numeric assim você pode definir as casas decimais.
Já para o campo com virgulas ou ponto você tem que ver o tamanho do campo, se for um texto maior você deve usar um campo do tipo Blob, se não pode utilizar um varchar. Só que você devera ter muito cuidado na hora de realizar as queries.


text:
Q: Calling Rust cargo from R results in "cargo not found" error on macOS Running R from RStudio on macOS 11.2.1
When calling cargo from R, as when using the rextendr package or trying to install helloextendr, I receive the errors sh: cargo: command not found and make: cargo: command not found, respectively. However, from the terminal, calling cargo works as expected.
One can see the difference from below.
In R cargo is not found:
> Sys.which("cargo")
# cargo
# ""

From a terminal cargo is found
% which cargo
$HOME/.cargo/bin/cargo

A: The cause is related to this question: Why do which and Sys.which return different paths? Simply put, macOS has a different $PATH variable, depending on whether you use a terminal directly or use an application launched from the dock (as R and RStudio are).
One solution is to use a .Rprofile file. Add the following lines to the .Rprofile in your home directory or project's home directory. (For more on .Rprofile files, see here.)
# R can't find Rust's cargo binary
# issue is because $PATH is different for shell vs. dock launched applications in MacOS
# See: https://stackoverflow.com/questions/48084679/why-do-which-and-sys-which-return-different-paths
Sys.setenv(PATH = paste0("/Users/username/.cargo/bin:", Sys.getenv("PATH")))

Make sure "username" is your username. For example, my path is "/Users/tommy/.cargo/bin:"
This appends the default location of Rust installation to the $PATH variable that R receives on startup.