text:
Q: Adding app insights logging inside AD B2C Display Controls (emailVerificationControl) We implemented a custom email verification workflow through send grid and it works great.  We want to add app insights logging to know how many are putting their email but not verifying it. Calling AppInsights-EmailVerificationSent Technical Profile in the display control below is giving me a "Unable to validate the information provided." error.  How can I call this technical profile to log the action in app insights?  Thanks very much!
<TechnicalProfile Id="AppInsights-Common">
          <DisplayName>Application Insights</DisplayName>
          <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.Insights.AzureApplicationInsightsProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
          <Metadata>
            <Item Key="InstrumentationKey">xxxxx</Item>
            <Item Key="DeveloperMode">true</Item>
            <Item Key="DisableTelemetry ">false</Item>
          </Metadata>
          <InputClaims>
            <!-- Properties of an event are added through the syntax {property:NAME}, where NAME is property being added to the event. DefaultValue can be either a static value or a value that's resolved by one of the supported DefaultClaimResolvers. -->
            <InputClaim ClaimTypeReferenceId="EventTimestamp" PartnerClaimType="{property:EventTimestamp}" DefaultValue="{Context:DateTimeInUtc}" />
            <InputClaim ClaimTypeReferenceId="PolicyId" PartnerClaimType="{property:Policy}" DefaultValue="{Policy:PolicyId}" />
            <InputClaim ClaimTypeReferenceId="CorrelationId" PartnerClaimType="{property:CorrelationId}" DefaultValue="{Context:CorrelationId}" />
            <InputClaim ClaimTypeReferenceId="Culture" PartnerClaimType="{property:Culture}" DefaultValue="{Culture:RFC5646}" />
          </InputClaims>
        </TechnicalProfile>
        <TechnicalProfile Id="AppInsights-EmailVerificationSent">
          <InputClaims>
            <InputClaim ClaimTypeReferenceId="EventType" PartnerClaimType="eventName" DefaultValue="EmailVerificationSent" />
            <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="{property:UserId}" DefaultValue="NoValue" />
          </InputClaims>
          <IncludeTechnicalProfile ReferenceId="AppInsights-Common" />
        </TechnicalProfile>

<DisplayControls>
      <DisplayControl Id="emailVerificationControl" UserInterfaceControlType="VerificationControl">
        <DisplayClaims>
        <DisplayClaim ClaimTypeReferenceId="email" Required="true" />
        <DisplayClaim ClaimTypeReferenceId="verificationCode" ControlClaimType="VerificationCode" Required="true" />
        </DisplayClaims>
        <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="email" />
        </OutputClaims>
        <Actions>
          <Action Id="SendCode">
            <ValidationClaimsExchange>
              <ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="GenerateOtp" />
              <ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="SendOtp" />
              **<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="AppInsights-EmailVerificationSent" />**
            </ValidationClaimsExchange>
          </Action>
          <Action Id="VerifyCode">
            <ValidationClaimsExchange>
            <ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="VerifyOtp" />
            **<ValidationClaimsExchangeTechnicalProfile TechnicalProfileReferenceId="AppInsights-EmailVerified" />**
            </ValidationClaimsExchange>
          </Action>
        </Actions>
      </DisplayControl>
    </DisplayControls>

A: Having had this exact problem recently the only way I found was to set up an API endpoint that would write custom events to App Insights, then use a REST technical profile to call that API from the DisplayControl.


text:
Q: OData table data display based on tile click in sapui5 I have three tiles for different status in my XML view. When I click on a particular tile it should navigate me to a another XML where table data is displayed based on this status. I am able to navigate to the other view on tile click. But, my table displays all the data instead of displaying data for that particular status. I want to display open status data only when the corresponding tile is clicked:

I display only the count of the status to the tile using oModel.read().
The count to the Tile is displayed using the code
oModel.read("/ServiceRequestCollection?$filter= CustomerID eq '1001192'", {
      success: function(oData, response) {
      var fld = [];
      fld = oData.results;
      var x = [];
      var count1 = 0;
      var count2 = 0;
      var count3 = 0;
      for (var i = 0; i < oData.results.length; i++) {
      var p1 = "1001190";
      var obj = fld[i];
      if(x[obj.ProductID] === p1) {
      x[obj.ServiceRequestLifeCycleStatusCodeText] = [obj.ServiceRequestLifeCycleStatusCodeText];
      x[obj.ServiceRequestLifeCycleStatusCodeText].push(obj);
      // console.log(x);
      }
      if (fld[i].ServiceRequestLifeCycleStatusCodeText === "Open") {
      var OpenArray = [];
      count1 = count1 + 1;
      OpenArray.push(count1);
      OpenArray = {tilearray:OpenArray};
      var oVizFrame3Model = new sap.ui.model.json.JSONModel(OpenArray);
      var oTile = oView.byId("opentile");
      oTile.setModel(oVizFrame3Model);
      oTile.setNumber(count1);
      // return OpenArray;
      } else {
      if (fld[i].ServiceRequestLifeCycleStatusCodeText === "In Process") {
      var InProcessArray = [];
      count2 = count2 + 1;
      InProcessArray.push(count2);
      InProcessArray = {tilearray:InProcessArray};
      oVizFrame3Model = new sap.ui.model.json.JSONModel(InProcessArray);
      oTile = oView.byId("inprocesstile");
      oTile.setModel(oVizFrame3Model);
      oTile.setNumber(count2);
      // return TileData;
      }
      }
      if (fld[i].ServiceRequestLifeCycleStatusCodeText === "Completed") {
      var CompletedArray = [];
      count3 = count3 + 1;
      CompletedArray.push(count3);
      CompletedArray = {tilearray:CompletedArray};
      oVizFrame3Model = new sap.ui.model.json.JSONModel(CompletedArray);
      oTile = oView.byId("completedtile");
      oTile.setModel(oVizFrame3Model);
      oTile.setNumber(count3);
      // return TileData;
      }
      }
      }
      });

The table data is loaded from a different array to that view. Please provide suggestions on how to accomplish this.

A: you need to use a filter to filter the data. I am showing you the code to do it for status as Open. Here 'iHome1' is the id of your table.
 var filters = [];

 var f1 = new  sap.ui.model.odata.Filter('CustomerID', [{operator:"EQ",value1:"1001192"}]);
 var f2 = new  sap.ui.model.odata.Filter('Status', [{operator:"EQ",value1:"SALESREP"}]);
            filters.push(f1);
            filters.push(f2);
            var oModel = new sap.ui.model.odata.ODataModel("/ServiceRequestCollection",
                    false);
            var oHtable1 = sap.ui.getCore().byId("iHome1")
            oHtable1.setModel(oModel);
            oHtable1.bindRows({path:"/ServiceRequestCollection", filters: filters}  );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extending Sobolev functions by zero I believe that if you have a sufficiently regular (say Lipschitz) bounded domain $\Omega\subset\Bbb R^n$, then you can extend a function $u\in H^1_0(\Omega)$ by zero, and the extension lies in $H^1(\Bbb R^n)$.
Consider the unbounded wedge $\Omega=\{(x,y)\in\Bbb R^2:- \infty<x<y,y>0\}$, and the subset $\Omega_R=B_r(0)\cap\Omega$ for some $R>0$ bounded.
Let $\Gamma = \{(x,y)\in\overline{\Omega}_R:x^2+y^2=R^2\}$ (i.e., the full curved boundary) consider the space $H^1_E(\Omega_R)=\{v\in H^1(\Omega_R):v|_{\Gamma}=0\}$.
My question is can I extend a function $u\in H^1_E(\Omega_R)$ by zero to the whole of $\Omega$, and have the extension lie in $H^1(\Omega)$?
If this does or doesn't hold it would be great to hear an argument as to why/ why not.

A: Since your region has a simple geometry this should be a consequence of the "absolutely continuous on lines" characterization of $H^1$, e.g. section 4.9.2 in Evans and Gariepy.
By the way, the zero extension of a function in $H^1_0(\Omega)$ will belong to $H^1(\mathbb R^n)$ with no restriction whatsoever on the boundary of $\Omega$.


text:
Q: ReplicaSet spring-data-mongodb com.mongodb.MongoSocketException: mongo1: nodename nor servname provided, or not known I'm trying to connect to a replicaSet using remote domain, but it seems like spring-data-mongodb is picking up the internal domain configured for the replicaSet when trying to connect, which of course won't be accessible from my application.
I'm on spring-boot-starter:2.6.2 with spring-data-mongodb:3.3.0 and I'm using spring.data.mongodb.uri to connect to the replicaSet as per the documentation.
This gist should provide enough info to reproduce: https://gist.github.com/Tyngstast/45997c498a25a0ca36026b4669a060c9
Changing the replica set config in the gist to use my machine IP 192.168.x.x as host, instead of docker internal net, works.
Am I missing something, or is this a bug in spring-data-mongodb?


text:
Q: How do I get my AutoHotKey script to activate upon click an area of the screen, then deactivate until a different area of the screen is clicked? I am writing my first script in AutoHotKey.  What I am trying to achieve is as follows:
When a certain area of the screen is clicked I want the script to run where it will click the specific co-ords on the screen.  I then want the script to be disabled until I click a different area of the screen (as specified within the else if).
The current script is sporadically activating AFTER it has already run once (after c has been set to 1)
c = 0

#IfWinActive, ahk_exe C:\Program Files (x86)\Hearthstone\Hearthstone.exe
~LButton::
MouseGetPos, x, y
if (c = 0 and x > 1700 and x < 2150  and y > 1600 and y < 1800) {
  c = 1
  Tooltip, c is %c%
  Sleep, 1000
  MouseGetPos, currentX, currentY
  CoordMode, Mouse, Screen
  Click, Right, 1940, 410
  Sleep, 200
  Click, 1610, 200
  MouseMove, currentX, currentY
  return
}

else if (x > 2620 and x < 3000  and y > 1590 and y < 1950) {
  c = 0
  Tooltip, c is %c%
}

A: It actually works.  This numpty was running an older version of the script concurrently and that was what was causing the issues.
So anyone who needs to do something similar - here's the script for you!  =)


text:
Q: Richardson-Lucy for bitmap image I am new to Python and am trying to modify an existing Richardson-Lucy program for an image that I have.
Specifically, I have a bitmap image 'flower2.bmp' that I am using to test the following program:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
from scipy.signal import convolve2d as conv2
from skimage import color, data, restoration

Image.open('flower2.bmp').convert('L').save('flower2_gray.bmp')

astro = Image.open('flower2_gray.bmp')

psf = np.ones((5, 5)) / 25

astro = conv2(astro, psf, 'same')
# Add Noise to Image
astro_noisy = astro.copy()
astro_noisy += (np.random.poisson(lam=25, size=astro.shape) - 10) / 255.

# Restore Image using Richardson-Lucy algorithm
deconvolved_RL = restoration.richardson_lucy(astro_noisy, psf, iterations=100)

fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(8, 5))
plt.gray()

for a in (ax[0], ax[1], ax[2]):
       a.axis('off')

ax[0].imshow(astro)
ax[0].set_title('Original Data')

ax[1].imshow(astro_noisy)
ax[1].set_title('Noisy data')

ax[2].imshow(deconvolved_RL, vmin=astro_noisy.min(), vmax=astro_noisy.max())
ax[2].set_title('Restoration using\nRichardson-Lucy')

fig.subplots_adjust(wspace=0.02, hspace=0.2,
                    top=0.9, bottom=0.05, left=0, right=1)

plt.show()

Below is the image output. I would appreciate help understanding why the Restoration image is black.

Thank you.

A: The restoration.richardson_lucy documentation notes that the function has an optional "clip" argument, which is true by default:

clip : boolean, optional
True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility.

However, the astro image read from Image.open has nominal range [0, 255]. I'm guessing that all pixels in astro are >= 1, so that the result after clipping to [-1, 1] is simply a constant image of ones. This could explain the plot.
The fix is to divide astro_noisy by 255 before passing it to restoration.richardson_lucy.


text:
Q: We found a pre-release version of Office error I just wiped my machine and did a fresh install of Windows 8 and updated it to Windows 8.1.
I am trying to install Office Professional 2013 and I am getting this error:

We found a pre-release or Beta version of an Office product on your
  computer and can't install because of it.  Please uninstall any
  pre-release Office software using the Programs and features item in
  the Control Panel and try installing again.

The thing is, this is the first time I've tried to install office since wiping the hard-drive and re-installing Windows.  So there is no Pre-release or Beta version installed.  The only software I have installed since the machine was wiped, is Windows, Visual Studio 2012 and Kaspersky Internet security.
I downloaded the Microsoft Fix It tool and it is also throwing an error when I attempt to run it saying

The program encountered an error trying to contact the server

Has anyone encountered this or know how to fix it?

A: So I got this sorted in the end.

*

*I downloaded the Office FixIt tool which Uninstalled office.  I think what happened was the first attempt to install Office failed for some reason, so when I went to re-run it, it thought I had a version already installed.

*I deleted the temporary internet files through the Settings, Options, menu in Internet Explorer.

*I downloaded the Office click to run.exe again but saved it as a different filename.  I just called it office.exe.

*Ran the office.exe file I downloaded in Step 3 and it worked, although the installation was very slow.
For some reason my download speeds from Microsoft today seem very slow, not sure if that had something to do with it.
Anyway Office is installed now.


text:
Q: I want to use fields in an object to filter product Here is my model:
class PromotedProduct(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    start_date = models.DateField(
        verbose_name="When do you want your advert to start", null=True, blank=True)
    stop_date = models.DateField(
        verbose_name="When do you want your advert to end", null=True, blank=True)
    is_promotion_paid = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(
        auto_now_add=True, editable=False, null=True)
    updated_at = models.DateTimeField(auto_now=True, editable=False, null=True)

class Product(models.Model):
    merchant = models.ForeignKey(
        MerchantProfile, on_delete=models.SET_NULL, null=True)
    name = models.CharField(verbose_name="Product Title",
                            max_length=255, null=True, blank=True)
    is_digital = models.BooleanField(default=False, null=True, blank=False)
    category = models.ForeignKey(
        ProductCategory, on_delete=models.RESTRICT, null=True, blank=True)
    image = models.ImageField(null=True, blank=True, upload_to='products')
    product_video_provider = models.CharField(
        max_length=60, null=True, blank=True)
    product_video = models.CharField(max_length=60, null=True, blank=True)

    brand = models.CharField(max_length=200, null=True, blank=True)
    description = models.TextField(null=True, blank=True)

class ProductCategory(models.Model):
    name = models.CharField(max_length=200, null=True)
    image = models.ImageField(null=True, blank=True,
                              default="category/blank.jpg", upload_to='category')
    icon = models.ImageField(null=True, blank=True,
                             default="category/icon.jpg", upload_to='category')
    added_by = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    slug = models.SlugField(null=True, unique=True, default=None)

I want to filter our promoted products under a category, say we have the category "computers"
and a promoted product "Laptop" under the category "computers".
i want to filter my PromotedProduct table with products under the category 'computers', i tried this but got an error, any help will be appreciated:
def promoted_products(request)
    cat = ProductCategory.objects.get(slug='computers')
    promoted = PromotedProduct.objects.filter(product.category=cat
    is_active=True, stop_date__gte=datetime.now().date(), start_date__lte=datetime.now().date())
    print(promoted)

A: I was able to figure it out:
def promoted_products(request)
    cat = ProductCategory.objects.get(slug='computers')
    promoted = PromotedProduct.objects.filter(product__category=cat,is_active=True, stop_date__gte=datetime.now().date(), start_date__lte=datetime.now().date())
    print(promoted)

A: sfirst, when you get an error it is always helpful to add the error text as part of the question.
second the query you are trying to make should be written like that:
def promoted_products(request)
    #if you need multiple categories, you can pull the ids
    #l_slugsList = []
    #cat_ids = ProductCategory.objects.filter(slug__in=l_slugsList)

    #single category
    cat = ProductCategory.objects.get(slug='computers')

    #get the subset of products for the specific category
    #OR if multiple categories use 'category_id__in=cat_id' instead
    #of the id filter
    product_ids = Product.objects.filter(category_id=cat.id)\
                                 .values_list('id',flat=True)

    #pull the promoted products for the subset of products
    #the product_ids query allows you to drop the reference
    #to a related object which is generally preferred for
    #performance reasons
    promoted = PromotedProduct.objects.filter(\
                                 product_id__in=product_ids,\
                                 is_active=True,\
                                 stop_date__gte=datetime.now().date(),\
                                 start_date__lte=datetime.now().date())
                              #.select_related('product')
    #if you want to work on the product of the promoted product is efficient
    #to request it beforehand. This will result in less sql queries.
    #in order to do that, uncomment the [select_related][1] part

    print(promoted)


text:
Q: Golang byte array communication through channel loses data I'm using a work-worker Queue implementation in my golang project.
The WorkRequest Struct is as below
type WorkRequest struct {
fields map[string] []byte }

and the dipatcher is
go func() {
    for {
        select {
        case work := <-WorkQueue:
            go func() {
                worker := <-WorkerQueue
                worker.Work <- work
            }()
        }
    }
}()

The worker.Work is channel for WorkRequest struct and WorkerQueue is channel of Worker struct.
Whenever there are many concurrent requests coming in WorkQueue it gets assigned to worker byt the dispatcher routine.
I'm observing issue when I send concurrent requests to WorkQueue, few of them miss out and few of them get executed multiple times.
e.g. If I've queued works with ID  1, 2, 3, 4, 5... then I see workers getting work with ID 1, 2, 4, 4, 5... here 4 is executed twice and 3 is missed. The same code works fine when I implement WorkRequest fields as map[string]string instead of []byte.
Am I missing something or is slice not thread safe and gets assigned same variable.

A: In Go string is immutable, so it works fine but all slices are mutable. Moreover they can share the backing array. You are not showing the relevant code but I guess you are expecting the map to hold copy of a slice. A slice is just address in memory and length. You need to manually make a new slice and copy its contents.
To fix your code make a copy of slice when putting it into map.


text:
Q: What's the origin of the saying "know your onions"? In French, there's the expression occupez-vous de vos oignons which means  "mind your own business" in English but can be literally translated as "take care of your onions".
Know your onions however means to be knowledgeable about a subject - a meaning which is clearly distinct from the French saying.
But what's its origin? I'd really love to know.

A: In the days of wooden walled sailing ships - with no fridges or freezers - onions were a key part of the crew's staple diet. They provided vital protein and vitamins.  Moreover, they would keep for a long time provided they were kept dry and in a dark space.
The ship's 'Purser' or 'Pusser' was responsible for storing the ship before sailing and very often he would purchase the necessary victuals from local markets.  It was thus vital that the Purser could assess the quality of the food supplies that he was buying - a good Purser would 'know his onions'

A: The phrase 'to know one's onion(s)' first appeared in print at least as early as 1891. Given its historical linguistic context, the 'source' of the phrase may be construed as the independent adoption of a generalized idiomatic response to the equally idiomatic and earlier-evidenced declaration that someone 'does not know the difference between an onion and [another object, commonly another vegetable]'. Both phrases, but particularly the latter, vary freely in individual use, but are loosely formulaic.1
OED (paywalled) defines 'to know one's onions' as "to be experienced in or knowledgeable about something". The OED entry only mentions the plural variant "onions", attested from 1908 (note the slightly earlier appearance of the attestation shown in the compilation below, from January 1908 as compared to February):

1908 Postal Rec. Feb. 27/3   Never mind: Billy knows his onions. He is not troubled with corns or bunions.

The singular variant "onion" was, however, as far as I have discovered, the only variant in print up to 1908. The singular continued in frequent use into the 1920s, when the plural variant gradually came to dominate use. By the mid-1920s, the plural variant was used almost if not entirely exclusively.2

Early attestation of 'know one's onion(s)'
Early appearances of the phrase 'know one's onion(s)' were a regionalism centered on and predominantly from Pennsylvania. Occasional instances were found in the surrounding states of New York, Delaware, and New Jersey, with only one outlier (from Washington State).
All links are paywalled unless otherwise noted.
The Morning Post (Camden, New Jersey) 22 May 1891, Page 1:

Say, Garrett, don't part with Ely, if you know your onion, and we believe you do.

The Evening Journal (Wilmington, Delaware) 06 May 1892, Page 2:

I know my onion, chappies, and doncher forget it — see?

The Morning Post (Camden, New Jersey) 29 Feb 1892, Page 1:

You don't know your onion, Stackey; you oughtn't to pull me in.

The Morning Post (Camden, New Jersey) 05 Apr 1894, Page 1:

This trolley knows her onion and don't you forget it.

The Philadelphia Inquirer (Philadelphia, Pennsylvania) 15 Jun 1898, Page 4:

You must "know your onion" to get your money on right.

The Evening Democrat (Warren, Pennsylvania) 27 Jun 1899, Page 4:

He is a big and busy bug and he knows his own onion and lights on it.

The Seattle Post-Intelligencer (Seattle, Washington)
04 Feb 1900, Page 28:

In cooking onions it is well to first know your onion.

Buffalo Courier (Buffalo, New York) 14 Apr 1900, Page 4:

According to the Binghamton Herald, there is one man in this State who knows 'his onion' as the tough boy says; you can't fool him.

The Selinsgrove Times-Tribune (Selinsgrove, Pennsylvania) 20 May 1903, Page 1:

The people may criticise and damn the old man, but he always knows his onion and rarely makes a mistake.

The New York Times (New York, New York)
07 Jun 1903, Page 6:

"He Knows His Onion."
To the Editor of The New York Times:
  Apropos of the discussion of the meaning and origin of "makes no bones," will some slang etymologist let us know the origin and connection of "he knows his onion," meaning he minds his own affairs, or is posted about certain pertinent situstions?

Republican News Item (Laport, Pennsylvania) 25 Jun 1903, Page 1:

The Experimental farmer comes down strong on the butter business, and when he talks about leeks, we have nothing more to say in advice, for it is plain to see that "he knows his onion."

The Index (Pittsburgh, Pennsylvania) 26 Nov 1904, Page 7 (not paywalled):

Not if he knows his onion, and he thinks he does.

Lewisburg Journal (Lewisburg, Pennsylvania) 06 Oct 1905, Page 7:

I know my onion.

Wilkes-Barre Times (Wilkes-Barre, Pennsylvania)
18 May 1907, Page 4 [blurb headline]:

Knows His Onion

The Morning Post (Camden, New Jersey) 26 Oct 1907, Page 11:

It isn't wise for a policeman to say "I never saw the beat." He knows his "onion!" If he made such a remark, in all probability he would not "turn-up" again. He'd get it in the Adam's "apple." That's all!

The Wilkes-Barre Record (Wilkes-Barre, Pennsylvania)
02 Jan 1908, Page 4:

But never mind, Billy knows his onions,
  He is not troubled with corns or bunions,
  He travels along at a good fair gait;
  Unless the roads are bad, he is never late.
    O.S. White, (Letter Carrier No. 9),
    48 Carey Avenue, Wilkes-Barre, Pa.

Early attestation of 'does not know an onion from a ——'
The Scottsboro Citizen (Scottsboro, Alabama) 01 Feb 1883, Page 2:

The Chattanooga Democrat intimates that a man who doesn't know an onion from a grindstone ought not to have been appointed commissioner of agriculture of Tennessee.

Ellsworth Messenger (Ellsworth, Kansas) 15 Apr 1885, Page 1:

If he should take his garden down to his Great Steam Printing Shop, he had better take Jimmy Jarvis along to weed it, for he himself would not know an onion from a bull nettle.

The Gazette (Montreal, Canada) 22 Jun 1888, Page 8:

He did not know an onion from a cabbage.

Woodland Daily Democrat (Woodland, California)
22 Jul 1890, Page 3:

Thad Spaulding and family are there also, and Thad wouldn't know an onion from a potato to-day.

Northumberland County Democrat (Sunbury, Pennsylvania) 19 Sep 1890, Page 2:

Now that fairs are opening we raise to remark that the horse jockey, who does not know an onion from a turnip, generally gets away with more than his share of the boodle.

The Brooklyn Daily Eagle (Brooklyn, New York) 29 Oct 1899, Page 25:

She didn't know onions from lamp wicks and bunions;
  A clam from a lobster, or crab from an eel!

Endnotes

*

*For purposes of definition, the
formula underlying the former phrase is "know(s) one's X", and the
formula of the latter phrase is "do(es) not know the difference
between X and Y".

*I do not know why the plural
variant came to be preferred to the exclusion of the singular. As a
matter of speculation, I observe that I am slightly more
uncomfortable with the ill-defined referent of the metaphorical
"onion" than I am with the equally ill-defined referents of the
metaphorical "onions". My mild discomfort may be due to what I
consider the stronger likelihood of inappropriate interpretations of
"onion" than of "onions".

A: I find The Phrase Finder's explanation most persuasive:

The English grammarian and lexicographer C. T. (Charles Talbut) Onions
  was an editor of the Oxford English Dictionary from 1895 and continued
  to write reference works throughout a long and distinguished career.
  His last work was The Oxford Dictionary of English Etymology, 1966,
  which was published a year after his death. If I knew as much
  etymology as he did I could certainly claim to 'know my onions', and
  it is tempting to assume that this is where the phrase originated.
If the 'onions' referred to in the phrase is indeed human rather than
  vegetable, there is another Mr. Onions that could be our man. S. G.
  Onions (they were strong on initials in those days) created sets of
  coins which were issued to English schools from 1843 onwards. These
  were teaching aids intended to help children learn £.s.d. (pounds,
  shillings and pence). They looked similar to real coins and had
  inscriptions like '4 Farthings make 1 Penny' or, as in the example
  pictured, '12 Pence make 1 shilling'. We can imagine that 'knowing
  your Onions' might be coined, so to speak, in those circumstances.
The first known use of 'know your onions' in print, in the 1920s,
  tends to argue against either of the above men being involved. While it is true that the phrase originated at a time when C. T.
  Onions had established a reputation, the match between the phrase and
  his name is just a coincidence. Know your onions is in fact an
  American phrase. There are many references to it in print there from
  the 1920s onward, but none in the UK or elsewhere until the middle of
  the century.

The Phrase Finder goes on to conclude:

1920s America was a breeding ground for wacky phrases (see the bee's
  knees) and know your onions is just another of those.

It's worth visiting The Phrase Finder to read the full explanation, which includes a link to other phrases that were coined in the USA.

A: This is an American phrase, first recorded in the May 1922 edition of Harpers Magazine:

"Mr. Roberts knows his onions, all right."

According to World Wide Words, this had nothing to do with any Mr. Onions, but:

The crucial fact is that the expression isn't British
  but American, first recorded in the magazine
  Harper's Bazaar in March 1922. It was one of a set
  of such phrases, all with the sense of knowing
  one's stuff, or being highly knowledgeable in a
  particular field, that circulated in the 1920s. Others were to know one's oats, to know one's
  oil, to know one's apples, to know one's eggs,
  and even to know one's sweet potatoes (which
  appeared in a cartoon by T A Dorgan in 1928).
  You may notice certain similarities between the
  substances mentioned, most being foods and most having names that start with a vowel.
They contain much of the verbal inventiveness
  and mildly juvenile wordplay that characterises
  another American linguistic fad of the flapper
  period, that of describing something excellent of
  its kind in terms of an area of an animal's
  anatomy (elephant's instep, gnat's elbows and about a hundred others — see my piece on bee's knees for more).
As with bee's knees, one of these multifarious
  forms eventually triumphed and became a
  catchphrase that has survived to the present day.

The Phrase Finder agrees:

Other phrases that refer to
  knowing - 'know the ropes', 'doesn't know shit from Shinola' etc. allude to specific items as
  the focus of the knowledge.
  Other 1920s variants of 'know
  your onions' are 'know your oil/
  oats/apples' etc. The only one that caught on and
  is still in common use is 'know your onions'. So, why onions? Well, as the citation above asks -
  why not? Explanations that relate the phrase to
  knowledgeable vegetable gardeners, or even to C.
  T. or S. G. Onions, are just trying too hard. 1920s
  America was a breeding ground for wacky
  phrases (see the bee's knees for some examples) and this is just another of those.

Edit: A tantalising snippet in Google Books shows this may have been used in 1908 in a humorous poem in The Postal Record (Volumes 21-22 - Page 27). It' shown in the summary, and is interesting as the year 1908 is also shown. Care must be taken with snippets, as they're sometimes incorrectly dated, but here it is anyway:

But, never mind; Billy knows his onions, He Is not troubled with corns or bunions. He travels along at a good, fair gait; Unless the roads are bad, he Is never late. O. 8. WHITE. WHkesbarre, January 1, 1908. West Hoboken, N. J. At the regular meeting of Branch 1065, held on January 10, 1908, it was honored by the presence of Brother Kelly, President of our National Association.

A: I don't know but have always been told that it is was a phrase that started among actors. C.T Onions wrote the first comprehensive glossary of Shakespeare's words. If an actor could speak his part without asking what a word meant he knew his onions. David Crystal has since compiled a more extensive glossary and if I'm working on a Shakespeare play I take it with me. I know my Onions but I don't know all my Crystal.

A: An old small time grocery store owner named Tommy Campbell in McGraw, NY used to tell all of us kids that bought candy from the store that we knew our onions. This was approximately 1965. I remember asking my father what the expression meant. He told me that he was probably short changing us. For example giving him a nickel for 4 cents worth of candy and being told you know your onions instead of getting the penny change back. While in college in the early 1980's I bought a copy of " The Dictionary of American Slang ". I no longer have possession of the book yet my memory recalls what my father had told me.Making you feel good about the transaction yet actually having "the wool pulled over your eyes".

A: Vince Kosuga captured the onion futures market in 1955-56 and enjoyed a monopoly of that culinary necessity. He knew his onions.

A: 'Know your onions' is Cockney rhyming slang. 'Onion rings' = 'things'. I heard this explained on a BBC radio show decades ago.


text:
Q: ajax request is not stopping Here is my ajax call:
 $.ajax({
                        url: "AutoRFQ_Vendors_ST.aspx/BindVesselGrid",
                        type: "POST",
                        timeout: 3000,
                        data: JSON.stringify(sendingdata),
                        contentType: "application/json",
                        success: function (data) {
    //do something
    }

Here is my CSS loader:
  ajaxStart: function () { $body.addClass("loading"); },
            ajaxStop: function () { $body.removeClass("loading"); }

When I make an ajax call which responds d:'' an empty string but my ajaxstop: event is not firing.

A: You have to hide your loader on ajax() complete like:
ajax({
    complete: function(){
        $body.removeClass("loading");
    }
});

complete executes after either the success or error callback were executed.

A: You need to understand that the ajaxStart and the ajaxStop events falls under global event handlers in jQuery. Hence you need to hook them to document instead of having in your $ajax call.
You need to rewrite your code as,
$(document)
 .ajaxStart(function () {
   $body.addClass("loading");
 })
.ajaxStop(function () {
   $body.removeClass("loading");
});

Hope this helps!


text:
Q: AnyObject to [String: [String: String]] crashes without error Description:
I'm trying to convert AnyObject from my [String: AnyObject] as [String: [String: String]] but just crashes without any error.
    //where my dict is the [String: AnyObject]
    if let data = dict["data"]{
        //We enter here
        print(data)
        //Crashes here.. because of conversion
        for (_, item) in data as! [String: [String: String]]{
            //Do stuff here
        }
    }

Here is the print of data:
{
    1 =     {
        col = "#006666";
        date = "2016-09-01";
        desc = "<null>";
        img = "1.png";
        tit = "title here";
        url = "id=1";
    };
    2 =     {
        col = "#006666";
        date = "2016-07-01";
        desc = "<null>";
        img = "2.png";
        tit = "title here";
        url = "id=2";
    };
    3 =     {
        col = "#006666";
        date = "2016-10-01";
        desc = "<null>";
        img = "3.png";
        tit = "title here";
        url = "id=3";
    };
    4 =     {
        col = "#006666";
        date = "2016-06-01";
        desc = "<null>";
        img = "4.png";
        tit = "title here";
        url = "id=4";
    };
}

Question:
Why am I not able to convert it AnyObject as [String: [String: String]] or even [Int: [String: String]] ?
Edit:
Converting it to [String: [String: AnyObject]] lets me get into the loop. Then when I try to handle desc it crashes:
    //In the loop
    if let description = item["desc"]{
       //Should enter here.. but it doesn't...
       if (description.isEqual(NSNull.self)){
          fotmItem.description = ""
       } else {
          //enters here and attempts to convert "<null>" to string and crashes
          fotmItem.description = description as! String
       }
   }

A: Try to convert your [String: [String: String]] like below.

*

*AnyObject as [Any: [String: Any]], if you are not sure about the type of dic keys (1, 2, 3, etc).

*AnyObject as [String: [String: Any]] if you are sure that keys (1, 2, 3, etc) are strings.

So, [String: Any] will be useful whenever you don't know about the dictionary values data type(Int or String or Null, etc).
For Example:
if let data = dict["data"] as? [String: [String: Any]]{

     for (_, item) in data{
             //Do stuff here
     }
}

Updates to handle desc:
if let description = item["desc"] as? String, description != "<null>"{

     fotmItem.description = description

}else{

   fotmItem.description = ""
}

Note: Syntaxes are in Swift 3.0

A: You should compare item["desc"] to NSNull() instead of NSNull.self.
Replace this
if (description.isEqual(NSNull.self)){

with
if (description.isEqual(NSNull())){

Another approach would be trying to cast it as String
if let description = item["desc"] as? String {
    fotmItem.description = description
} else {
    fotmItem.description = ""
}


text:
Q: IBM Worklight - How to access JSON sent using an adapter in server-side PHP? I am developing a hybrid application in IBM Worklight.
In my app, there is a registration form. I have a requirement: After the user registers with the app, the form data will be sent to an external server in JSON format using an HTTP adapter.
In the external server,

*

*How to access the JSON data sent using the HTTP adapter in a PHP file? and

*How to send back a response in the same JSON format?

Please give demo codes of both HTTP adapter and server side PHP code.

A: Client code:
function callAdapter(){

    var invocationData = {
            adapter : 'MyAdapter',
            procedure : 'MyAdapterProcedure',
            parameters : [username, password]
    };

    WL.Client.invokeProcedure(invocationData, {
        onSuccess : adapterSuccessCallback,
        onFailure : adapterFailureCallback
    });
}

Adapter implementation:
function myAdapterProcedure(username, password) {

    var credentials = JSON.stringify({username: username, password: password});

    var input = {
        method : 'post',
        returnedContentType : 'json',
        path : "/myPHPscript.php",
        parameters: {credentials: credentials}
    };

    return WL.Server.invokeHttp(input);
}

PHP script:
<?php
        $jsonObj = $_POST['credentials'];
        $credentials = json_decode($jsonObj)

        // sanitation, database calls, etc

        $returnDict = array();
        $returnDict["success"] = true;
        echo json_encode($returnDict);
?>


text:
Q: Amazon Alexa hierarchical dialog I'm playing with the Amazon Alexa SDK and I'm programming my first skill.
My goal is to programm a dialog like this:

*

*Where do you live?

*How long have you been living there?

The problem is that I can answer the question number one with keywords from the second question and then Alexa assumes that I answered to the second question and will provide me the answer for question number two.
Is there a way to prevent this?
I know I could use session attributes but this looks rather hacky to me...
Thanks for your help =)
PS: I'm using flask-ask for my Alexa Skill.

A: There are a few ways you could structure this dialog. The first way, similar to what you're doing currently, is to use a series of single turn dialogs. My guess is that you're not using the right slot types in your existing interaction model, which is why the wrong intents are matched.
If I were using a single turn approach, I'd have two intents.
The first intent would match responses to the question "Where do you live?"
Intent: GetAddressCity
Utterance 1: {AMAZON.US_CITY}
Utterance 2: I live in {AMAZON.US_CITY}

The second would match responses to the question "How long have you been living there?"
Intent: GetAddressDuration
Utterance 1: {AMAZON.NUMBER}
Utterance 2: {AMAZON.NUMBER} years
Utterance 3: For {AMAZON.NUMBER} years

A different approach altogether (and one that I'd likely use in this situation) would be to structure the conversation using a Multi-turn Dialog. This approach would define a single intent, with multiple required slot values.
Intent: GetLivingInfo
Utterance 1: I live in {AMAZON.US_CITY}
Utterance 2: I've lived in {AMAZON.US_CITY} for {AMAZON.NUMBER} years

One intent, with two required slots. If the user says I live in Boston, Utterance 1 will match, and Alexa will respond with a prompt asking for the number of years they've lived there. Look into Multi-turn Dialogs for more details.

A: I think Bill's answer is the best solution. Yes, you can use multiple questions, but the 2nd question needs to have the response information passed to it by the first response. You can do this using a DB such as DynamoDB keyed to the user's ID, but I think it is much easier to pass it in the session.

A: Bill is 100 percent correct fix your slot values as he recommended and the flow should work correctly . I did somewhat the same in skill MedTime if you wish to give it a try and provide me some feedback. I will be glad to work with you on building skills for Alexa.


text:
Q: React.Children.count or children.length? I'm doing on migration from class based components to functional components.
My problem is legacy codes counts react comopnents using children.length which is different my previous use React.Children.count(children).
Any differences between two of these? which one is better?
  ...
  const SomeParentFC = () => {
  const arrays = [1,2,3,4,5]
  function renderSomething() {
    return arrays.map((value,index) => {
      <SomeReactComponent key={index}>value</SomeReactComponent>
    })
  }
  return(
    <SomeChildFC>
       { renderSomething() }
    </SomeChildFC>
  )
}

  const SomeChildFC = ({children}) => {
  const getMyChildrenCount = () => {
    ? ???
  }

  return (
    <>
    </>
  )

A:
you can use React.Children.count , documentation here: reactjs.org/docs/react-api.html#reactchildrencount

const getMyChildrenCount = () => React.Children.count(children);


text:
Q: Identify who took new free space each day I have a Windows Server 2012 R2. I am hosting my development database server there. Last week I truncated many tables and did a shrink database to free up some space. And I had obtained around 60GB free space. Now free space is getting decreased around 5GB every day (15GB in 3 days).
I would like to know who is taking this much space every day. It is not the database transactions – because I don't have many transactions in my development database. Is there a way to get who claimed "new" free space each day?
Please be clear that I am NOT looking for memory used by each application. What I am looking for is who took "new" free space each day.

A: You can try a tool such as http://diskreport.net to get a periodic report of your disk space usage, and then find where space has grown between two reports.


text:
Q: Dockerfile instruction to write to host under non-root I am to create a Dockerfile with some specific properties:

*

*it should use a VOLUME statement

*while running the image it should write a textfile to mounted host directory that is protected from all users unless UID=1000

*it should write this textfile under a specified user with UID=3000

I have created such a Dockerfile:
FROM ubuntu:16.04
<...>
WORKDIR $HOME
ENV UID 3000
RUN groupadd -g $UID custom_group
RUN useradd -u $UID -g $UID custom_user
RUN chown -R custom_user:custom_group $HOME
VOLUME $HOME
USER custom_user:custom_group
ENTRYPOINT nano

However I get a permission error when run the image with "-v" option.
What should I improve?


text:
Q: mod_proxy_html and Apache 2.2.29: parse all  and turn them in real http headers I'm using Mamp 3 (pro) on Mac OS X Yosemite 10.10; I'v already compiled and installed mod_proxy_html (3.1.2) and mod_xml2enc, they are both correctly loaded by Apache 2.2.29 without issues.
This is my typical html file:
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="Authorization" content="Bearer dummyToken">
    <title>Header Test</title>
</head>
<body>

</body>

I need to convert all the <meta http-equiv="some" content="thing"> to real http headers. I've already known how to do this via ajax, it's not a problem. But I need to add an oauth token, inside the Authorization header field, to get access to various protected resources, like images or video streams, that are not served through ajax but referenced, through an url, directly inside the html.
So, directly inside my httpd.conf I have:
ProxyHTMLEnable On
ProxyHTMLMeta On

this config should globally apply to apache. At the moment my server replies with all the field contained inside the request: it seems that the ProxyHTMLMeta On is ignored and all the meta tags are not translated into http headers:
Accept: "*/*"
Accept-Encoding: "identity;q=1, *;q=0"
Accept-Language: "it,en;q=0.8"
Connection: "keep-alive"
Cookie: "laravel_session=dummy
DNT: "1"
Host: "192.168.2.2:8888"
Range: "bytes=0-"
User-Agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2535.0 Safari/537.36"

See, no Authorization header. If I call the api from SoapUI:
"Accept-Encoding": "gzip,deflate",
"Authorization": "Bearer dummy",
"Host": "fillusso:8888",
"Connection": "Keep-Alive",
"User-Agent": "Apache-HttpClient/4.1.1 (java 1.5)"

It's a kind of magic, the header is there (because it directly sent from SoapUI, no parsing or meta tag here).
How can I solve the problem? Am I doing everything all right?


text:
Q: Token in uri trimmed when trying to connect I'm trying to connect to socket.io hosted on our server and I'm getting the error message. When comparing two tokens (one provided in code, and other in the logs), token in the logs is shorter than one provided.
Code with token:
let url = URL(string: urlString)!
let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijc1M2Y5YmZkMjRiMzBmODA0N2JjMmQ1YzY4MzYxZjc2YzM5NjBhNTdmZjhmNWU5YmJmY2Q0NTdjZTIxNTY1ZjYwNTk5YTczZWM4NTJjNmMxIn0.eyJhdWQiOiIyIiwianRpIjoiNzUzZjliZmQyNGIzMGY4MDQ3YmMyZDVjNjgzNjFmNzZjMzk2MGE1N2ZmOGY1ZTliYmZjZDQ1N2NlMjE1NjVmNjA1OTlhNzNlYzg1MmM2YzEiLCJpYXQiOjE1ODQ2MjAzNDYsIm5iZiI6MTU4NDYyMDM0NiwiZXhwIjoxNTg1OTE2MzQ2LCJzdWIiOiIzMCIsInNjb3BlcyI6W119.Dhsn0vm1B7W_6sfHPgUox6qO3hYEnsvMQC_sGCNnviWNL_U45sUkT2W_dijjk2Px6ugyib6x9OcSqHB_bnKAWFdopZY7KU21uxxLy-p-f-YuwkZdYhfHYWKTufL09wjxUCQhRl04zSqj0QqpAei6C1zHtT6tmKR-N1U2iNh_AB1_UF2m0YIC-Zt3u92v0a8ssaLBMzfsu-lsv3N4pbwxfJ1CJQHX1z9WaLP7_Y5Bm5yDfpULS4as5639RGhfydRVfEAJfvwrTB9QmCJ0GV7ZDmZlNSKwWozgHo0btgw3UVUp1py3xKef-V-a8NJx-401k7jgDW0N0D5C9AV6uXhCiAcpc7NYRxm4hWRgRDipC-SaQ_Mvbsn9vOZHrEiHc-rqWsMeDA_GfbpTqfZOXZY8xWFSIem0aa5apOACvPsAS_6UoVk2WImoqfjsNfnVC43svGDiwJG24SvHtesit7Kr17RaaINstWz8zoDX3ZCS5L4enA2zia-w5mZYz1Ej2L-_wgzeAdglBtUIM5qStnG_uTPHNCgr80JWo0PvUykI8NIzRl_eoMkJfUXo2wrmZrp-93gDA8KsL7NkzogkFHpm890R7PIo-x4HTQWRVS08pGacddFJWEJ4D_T29E2Cl2KbbpREuqlF6qApi0B99tsgABWfKE7b28r-Uuc2echWQbE"
self.manager = SocketManager(socketURL: url, config: [.log(true), .compress, .path(""), .connectParams(["token": token])])
self.socket = manager.defaultSocket

Error log:
LOG SocketEngine: Handshaking
LOG SocketEnginePolling: Doing polling GET https://{DEV_URL}/?transport=polling&b64=1&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijc1M2Y5YmZkMjRiMzBmODA0N2JjMmQ1YzY4MzYxZjc2YzM5NjBhNTdmZjhmNWU5YmJmY2Q0NTdjZTIxNTY1ZjYwNTk5YTczZWM4NTJjNmMxIn0.eyJhdWQiOiIyIiwianRpIjoiNzUzZjliZmQyNGIzMGY4MDQ3YmMyZDVjNjgzNjFmNzZjMzk2MGE1N2ZmOGY1ZTliYmZjZDQ1N2NlMjE1NjVmNjA1OTlhNzNlYzg1MmM2YzEiLCJpYXQiOjE1ODQ2MjAzNDYsIm5iZiI6MTU4NDYyMDM0NiwiZXhwIjoxNTg1OTE2MzQ2LCJzdWIiOiIzMCIsInNjb3BlcyI6W119.Dhsn0vm1B7W_6sfHPgUox6qO3hYEnsvMQC_sGCNnviWNL_U45sUkT2W_dijjk2Px6ugyib6x9OcSqHB_bnKAWFdopZY7KU21uxxLy-p-f-YuwkZdYhfHYWKTufL09wjxUCQhRl04zSqj0QqpAei6C1zHtT6tmKR-N1U2iNh_AB1_UF2m0YIC-Zt3u92v0a8ssaLBMzfsu-lsv3N4pbwxfJ1CJQHX1z9WaLP7_Y5Bm5yDfpULS4as5639RGhfydRVfEAJfvwrTB9QmCJ0GV7ZDmZlNSKwWozgHo0btgw3UVUp1py3xKef-V-a8NJx-401k7jgDW0N0D5C9AV6uXhCiAcpc7NYRxm4hWRgRDipC-SaQ_Mvbsn9vOZHrEiHc-rqWsMeDA_GfbpTqfZOXZY8xWFSIem0aa5apOACvPsAS_6UoVk2WImoqfjsNfnVC43svGDiwJG24SvHtesit7Kr17RaaINstWz8zoDX3ZCS5L4enA2zia-w5mZYz1Ej2L-_wgzeAdglBtUIM5q
ERROR SocketEnginePolling: Error during long poll request
ERROR SocketEngine: Error
ERROR SocketManager: Error

Did someone had similar issue or has solution for this? Thanks

A: The issue is with logger. After debugging the code, request had proper url while the logger trimmed the string for some reason.


text:
Q: nodeschool javascripting ARRAY FILTERING var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filtered = numbers.filter(function evenNumbers (number) {
  return number % 2 === 0;
});

console.log(filtered);

I am total beginner to JavaScript, picking up the course offered by nodeschool. While in the exercise of "ARRAY FILTERING", I wonder what is the role of 'number' within the function evenNumbers as it was not declared beforehand.

A: It is declared, as a formal parameter to the callback evenNumbers (a function that takes an argument and tests whether it is even). filter will call the callback function once for each element of the array numbers, providing the element as the argument to the callback (which will assign it to number, via the usual function invocation process).

A: *

*numbers is an Array

*.filter is a method declared on Array.prototype

*.filter method accepts a callback function.

*Internally it looks Like,

,
Array.prototype.filter(callback[, thisArgs]) {
    '''''
    '''''
    callback(currentElement, index, arrayObjectBeingTraversed)
});

So,
In your case,
callback  --> function evenNumbers() {}

currentElement --> Number

More about Javascript Callback Functions


text:
Q: Aplicar uma regex no resultado de um select Estou fazendo uma consulta para pegar todos os projetos que estejam sendo executados:
SELECT p.id FROM projetos p WHERE p.status LIKE 'Execução'

Um exemplo do resultado:
COD00012347
COD00012348
COD01212349
COD00123410
COD00123411

Gostaria de aplicar uma regex afim de que o meu resultado fosse apenas os números (desconsiderando os 0 a esquerda):
12347
12348
1212349
123410
123411

Tentei aplicar a função SUBSTRING() mas não tive bons resultados. Estou aprendendo SQL ainda, o que posso fazer??

A: Caso seu id seja essa quantidade fixa, não vejo a necessidade de regex, basta dar um cast pra inteiro que os zeros a esquerda irão desaparecer após o substring, exemplo:
select cast (SUBSTRING('COD00012347',4,8) as int )  -- resulta em 12347

Atualização
caso as letras no inicio também possuam uma quantidade dinamica, aí fica mais fácil com regex mesmo usando patindex, exemplo:
select substring('COD00012347',PATINDEX('%[1-9]%','COD00012347'),len('COD00012347')) -- regex pega o index do primeiro numero de 1 a 9, depois a quantidade de caracteres da string conforme sua dica


text:
Q: git rm removing physical files even without -f I'm very new to Git so this might be obvious to someone.
Previously I was removing files (not physically, just from the repo) via git rm <file>.
Then for reasons I won't go into I had to do a force deletion, i.e. git rm -f <file>.
The problem: Since then, running git rm without the -f argument is deleting physical files as well, as though it's remembered that -f and is assuming it for each future request.
Why is this happening, and how can I stop it?

A: As you've noticed, git rm removes files from both the working tree and the index. You need to use -f if the file in the working tree has changed on disk, but isn't the same as the version in the index. If they're the same, then -f is not needed.
However, if you want to retain the version in the working tree but remove the version in the index (thereby staging its removal from the repository), then use git rm --cached. That will leave the working tree version alone.

A: the git rm command removes files from the working tree and from the index. The files being removed have to be identical to the tip of the branch, and no updates to their contents can be staged in the index.
With -f option we only override the up-to-date check of the file being removed against the file in the branch.
In your case I suppose earlier file(s) being deleted had different content then one in the branch, as a result, you had to use -f option with git rm command but now since they are in synch removal is working without the -f option.
Reference : Git RM Doc


text:
Q: Wrong timestamp format on kibana I'm new in kibana, currently i'm working with aws waf and i'm using kibana to visualize my waf log. but i got problem in timestamp format it's in number format instead of date format.

i have tried to add _timestamp format, but the log didn't showed up due to wrong timestamp.
thanks.
sample log

{"timestamp":1608166564696,"formatVersion":1,"webaclId":"arn:aws:wafv2:ap-southeast-1:regional/webacl/***/","terminatingRuleId":"Default_Action","terminatingRuleType":"REGULAR","action":"ALLOW","terminatingRuleMatchDetails":[],"httpSourceName":"ALB","httpSourceId":"-app/api-staging-waf/a4cc29fda18b3ac2","ruleGroupList":[{"ruleGroupId":"regional/rulegroup/SQLi_Prevention/a9616e2c-0c1f-4a7b-9278-8","terminatingRule":null,"nonTerminatingMatchingRules":[],"excludedRules":null}],"rateBasedRuleList":[],"nonTerminatingMatchingRules":[],"httpRequest":{"clientIp":"10.90.40.000","country":"-","headers":[{"name":"Host","value":"api.com"},{"name":"Content-Length","value":"81"},{"name":"content-type","value":"application/json"},{"name":"authorization","value":"REDACTED"},{"name":"accept-encoding","value":"gzip"},{"name":"user-agent","value":"http-client/2.0"}],"uri":"/notification/","args":"","httpVersion":"HTTP/2.0","httpMethod":"POST","requestId":"1-5fdaaca4-5d4a7a83048d7bb54ded7d0c"}}
Blockquote

A: Since you're indexing long values as "timestamp":1608166564696, ES will not transform that to a formatted date inside the source document.
However, if the mapping of the timestamp field is correctly defined as having type date
  "timestamp": {
    "type": "date"
  }

Then, in the Discover view in Kibana, you'll see properly formatted dates, such as below:


text:
Q: Access React context value from redux-saga function I have some variables which are controlled by React Context through React.createContext() with Provider and Consumer component. I'm also using redux-saga, so my question is are there anyway to access this context value in redux-saga function. I'm looking for something like "yield select" statement that works with redux-store.
Anyone who know it please explain to me. Thank you in advances.
P/S: Currently, I pass context value to action object payload when dispatch an action. So in redux-saga, we can use it in action parameter. I don't know whether it's the best practice.

A: EDIT: There is now a package that allows you to grab context easily, react-outside-call
You can keep an outside reference of your provider component, and grab the state from that.
Something like this...
Provider component
class AppProvider extends Component {
  state = {
    number: 10,
  }

  render() {
    return (
      <AppContext.Provider value={this.state}>
        {this.props.children}
      </AppContext.Provider>
    )
  }
}

Apps main entry file, or where ever you reference that provider instance.
let appProviderRef
export const getProviderState = () => appProviderRef.state

ReactDOM.render(
  <AppProvider ref={ref => appProviderRef = ref}>
    <App />
  </AppProvider>
, document.getElementById('root'))

You can now grab the state from within your redux sagas (or anywhere you want) synchronously calling getProviderState


text:
Q: Redirecionar usuário sem token Fala galera, bom dia, então estou com um problema e não estou sabendo como resolver, (talvez seja na forma que implementei isso), pois bem:
eu estou salvando um usuario e seu token toda vez que faço login dentro da minha plataforma, caso alguem sem token tente acessar uma rota que necessite de token ele não consegue e é redirecionado para a rota " / ", porém ela aparece sem nada carregado, e não estou sabendo como resolver isso.

import { Component, OnInit } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';

@Component({
    selector: 'app-admin',
    templateUrl: './admin.component.html',
    styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
    user = JSON.parse(localStorage.getItem('user'));
    token = this.user.token;

    constructor(private http: HttpClient) { }

    ngOnInit() {

    }

    downloadStudents() {
        let url = environment.apiUrl + 'admin/csv';
        this.http.get(url, { responseType: "text" })
            .subscribe(res => {
                let csv = 'data:text/csv;charset=utf-8,' + res;
                let data = encodeURI(csv);

                let link = document.createElement('a');
                link.setAttribute('href', data);
                link.setAttribute('download', 'alunos.csv');
                link.click();
            })
    }
}

esse é meu código.
E como podem ver é assim que eu pego o meu usuário e meu token,
user = JSON.parse(localStorage.getItem('user'));
    token = this.user.token;
será que alguém consegue me ajudar ?

A: Utiliza o método navigate do router angular para redirecionar.
 constructor(private router: Router, private http: HttpClient) { }
 user;
 token;
 ngOnInit(){
   this.user = JSON.parse(localStorage.getItem('user'));

   if (!this.user || !this.user.token)
    this.router.navigate(['/']);
   else
    this.token = this.user.token;
}


text: Q: Deploy jsp project via IIS I had finish my jsp project by using Netbeans IDE with glassfish server. But the problem I faced now is how can I deploay it to site and access via another computer? I am trying to use IIS but I have no ideas to do it. Can someone please me. Thank you.


text:
Q: Limit of $f(x)=x^2\left(\sin{\frac 1 x}\right)^2$ for $x\rightarrow\pm\infty$ I have the following function:
$$f(x)=x^2\left(\sin{\frac 1 x}\right)^2$$
For $x\rightarrow\pm\infty$, we have
$$f(x)\sim x^2\cdot\frac{1}{x^2}=1$$
so the limit is $1$. In cases like this I assume that the limit is $1^+$ because every operation I've done to get to that limit involves positive numbers. Therefore I assume that the function approaches $1$ from "above" (not below). However this is not the case, we approach $1$ from below:

The limit is actually $1^-$. Sometimes it is required to draw the graph of a function. How could I have known I had to draw from below $1$? Do I have to look at what the function does in the other points (e.g. for $x\rightarrow$0) Any hints?

A: Since $\sin(x) \leqslant x$ when is $x$ is enough close to $0$, you have (we take $x > 0$ because of the function parity) :
$$ x^2 \sin(1/x)^2 \leqslant 1$$
And the limit is $1^-$

A: Since $sin(\frac {1}{x}) \leq \frac {1}{x}$, the graph will always stay below $y=1$.

A: If you check the first and second derivative of your function for large positive values of x, you figure out that your function is
 increasing and concave down which gives you a hint about your limit.
Same with large negative values of x.


text:
Q: SignalR not receiving an abstract type Background
I have three classes:

*

*"A" an abstract base class

*"B" a class then extends "A"

*"C" another class that extends "A"

The client receives no events while we are listening for the type A, however when we listen for types B or C I receive half of the events.  What I want is to listen for abstract type A for any event that extends it while maintaining strong typing.
I am unable to find out if this is a limitation of Signalr or if I'm missing something from my implementation.
Server
using Microsoft.AspNetCore.SignalR;
using SignlR.Shared;
using System.Threading.Tasks;

namespace SignlR.Experiments.Hubs
{
    public class PolyHub : Hub
    {
        // Empty
    }

    public class PolyService
    {
        private readonly IHubContext<PolyHub> _hubContext;

        public PolyService(IHubContext<PolyHub> hubContext)
        {
            _hubContext = hubContext;
            Task.Run(Job);
        }

        private async Task Job()
        {
            A example = null;
            while (true)
            {
                example = new B();
                await _hubContext.Clients.All.SendAsync("Example", example);
                await Task.Delay(250);
                example = new C();
                await _hubContext.Clients.All.SendAsync("Example", example);
            }
        }
    }
}

Client
using Microsoft.AspNetCore.SignalR.Client;
using SignlR.Shared;
using System;
using System.Threading.Tasks;

namespace SignlR.Consoles
{
    class Program
    {
        static void Main(string[] args)
        {
            var connection = new HubConnectionBuilder()
                .WithUrl("https://localhost:44384/poly")
                .Build();

            connection.StartAsync().Wait();

            connection.On<A>("Example", (obj) =>
            {
                Console.WriteLine("Event" + obj.GetType().FullName);
            });

            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(2000);
                    Console.WriteLine(connection.State.ToString());
                }
            });

            Console.ReadKey();
        }
    }
}


text:
Q: How to set_names after using pull on a list column in the tidyverse Given the following:
library(tidyverse)
my_tibble <- tibble(
  var_1 = c("label_a", "label_b", "label_c"),
  var_2 = c("another_x", "another_y", "another_z"),
  result = list(
    data.frame(x = 1, y = 2, z = 3),
    data.frame(x = 4, y = 5, z = 6),
    data.frame(x = 5, y = 10, z = 11)
  )
)

my_tibble
# # A tibble: 3 x 3
#   var_1   var_2     result
#   <chr>   <chr>     <list>
# 1 label_a another_x <df[,3] [1 x 3]>
# 2 label_b another_y <df[,3] [1 x 3]>
# 3 label_c another_z <df[,3] [1 x 3]>

If we pull the result list-column, we get:
my_tibble %>% pull(result)

# [[1]]
#   x y z
# 1 1 2 3
#
# [[2]]
#   x y z
# 1 4 5 6
#
# [[3]]
#   x  y  z
# 1 5 10 11

How can I set the names (e.g. set_names()) of this pulled result by referring to more than one column from the original tibble? That is, instead of an unnamed list, I would like that list to have names referring to the tibble such as:
# $`label_a | another_x`
#   x y z
# 1 1 2 3
#
# $`label_b | another_y`
#   x y z
# 1 4 5 6
#
# $`label_c | another z`
#   x  y  z
# 1 5 10 11

A: Do it in the other order instead?
> my_tibble %>%
    mutate(result = set_names(result,paste(var_1,var_2,sep = " | "))) %>%
    pull(result)

$`label_a | another_x`
  x y z
1 1 2 3

$`label_b | another_y`
  x y z
1 4 5 6

$`label_c | another_z`
  x  y  z
1 5 10 11

A: Recent versions of tibble have the functions enframe and deframe, although as of v2.1.3 they both say they're maturing. deframe creates a named list out of a data frame. It assumes that the first column is the names and the second is the values, so just make a column (I used tidyr::unite) for the names.
library(dplyr)

my_tibble %>%
  tidyr::unite(key, var_1, var_2, sep = " | ") %>%
  tibble::deframe()
#> $`label_a | another_x`
#>   x y z
#> 1 1 2 3
#>
#> $`label_b | another_y`
#>   x y z
#> 1 4 5 6
#>
#> $`label_c | another_z`
#>   x  y  z
#> 1 5 10 11


text:
Q: How to make sure only 1 thread has access to DataTable at a time I have this Windows Console Application:
using System;
using System.Text;

namespace ThreadLockSample
{
    class Program
    {
        static void P1(System.Data.DataTable dt)
        {

            for (int i = 0; i < 100000; i++)
            {
                dt.Rows.Add(i);
            }
        }
        static void P2(System.Data.DataTable dt)
        {

            for (int i = 100000; i < 200000; i++)
            {
                dt.Rows.Add(i);
            }
        }

        static void Main(string[] args)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            for (int i = 0; i < 200; i++)
                dt.Columns.Add("Id " + i);

            System.Threading.Thread t1 = new System.Threading.Thread(() => P1(dt));
            System.Threading.Thread t2 = new System.Threading.Thread(() => P2(dt));
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
        }
    }
}

Now i am passing a DataTable accessible to both threads but the app freezes - how can i change my code to remove this issue.

A: When running this application, you won't get a deadlock. Instead you get an error stating that some data is corrupted within the DataTable because the DataTable itself has some internal checks for concurrency.
I suppose this application is a simpler version of your real app. There are a couple of steps you can take to improve your program:

*

*Avoid multithreading with shared data

Multithreading with shared data is hard. Can you simplify your program so that you don't need any shared data? Maybe you can run two operations in parallel, return a result and then merge those results. This would safe you from a lot of potential problems.
If that's not possible you can do the following:

*

*Add locks

You create a lock object like this:
private static object _lock = new object();

And now you surround calls to your datatable with:
lock (_lock)
{
    dt.Rows.Add(i);
}

*

*Don't use Threads directly. Instead use the Task Parallel Library:

A Task object is an intelligent wrapper around a Thread. Using Tasks is recommended.
Task t1 = Task.Run(() => P1(dt));
Task t2 = Task.Run(() => P2(dt));

Task.WaitAll(t1, t2);

UPDATE
Since the original question now changed from deadlock to freezes, there are a couple of other things you need to consider.
In a console application, you will always have to wait at some point until your two tasks finish. This waiting will freeze your UI. Off course you can use clever things like a Timer to check if the tasks are finished or something but a console application really isn't meant for a situation like this.
If however, your app is actually a WinForms or WPF app you should look at using asynchronous code with the new async/await keywords added in C# 5. They work perfectly with Tasks and they let you run code on another thread while the UI keeps responsive. When the Task finishes, the result is merged back on your UI thread and the user keeps a responsive app.
For more information on async/await, you can start here: Asynchronous Programming with Async and Await (C# and Visual Basic)

A: In addition to Wouter de Kort's answer:
If you want to use a lock on the DataTable, use the DataTable.Rows.SyncRoot Object like
lock(dt.Rows.SyncRoot)
    //Your code here

because it is the supposed lock object.


text:
Q: why this exception is coming : One or more errors occurred. at System.Threading.Tasks.Task.ThrowIfExceptional I am developing a task scheduler where I am fetching data from more than 200 queries and running these queries in Parallel.foreach loop.
But I am getting the below error:

One or more errors occurred. at
  System.Threading.Tasks.Task.ThrowIfExceptional(Boolean
  includeTaskCanceledExceptions) at
  System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout,
  CancellationToken cancellationToken) at
  System.Threading.Tasks.Task.Wait() at
  System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive,
  Int32 toExclusive, ParallelOptions parallelOptions, Action1 body,
  Action2 bodyWithState, Func4 bodyWithLocal, Func1 localInit,
  Action1 localFinally) at
  System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IList1
  list, ParallelOptions parallelOptions, Action1 body, Action2
  bodyWithState, Action3 bodyWithStateAndIndex, Func4
  bodyWithStateAndLocal, Func5 bodyWithEverything, Func1 localInit,
  Action1 localFinally) at
  System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable1
  source, ParallelOptions parallelOptions, Action1 body, Action2
  bodyWithState, Action3 bodyWithStateAndIndex, Func4
  bodyWithStateAndLocal, Func5 bodyWithEverything, Func1 localInit,
  Action1 localFinally) at
  System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable1 source,
  Action`1 body) at PFMSAccountJob.JobMethods.AppService.runService() in
  C:\SVN\PFMSToPFG_RAWDbJob\PFMSToPFG_RAWDbJob\JobMethods\AppService.cs:line
  95 Void ThrowIfExceptional(Boolean)

I have tried with Cancellation token and Cancellation token source but still getting the same issue.
 Parallel.ForEach(queries, query =>
                         {

                           qry = query.Replace(Convert.ToString("TmpOblId"), val);
                             dt = DBUtil.ExecSelectMultipleSQL(accIdqryConnNode.ToString(), qry);

                             DataTable dtCopy = dt.Copy();
                             ds.Tables.Add(dtCopy);

                         });

Kindly help with this issue. As whenever I am getting this issue the task scheduler gets terminated automatically


text:
Q: C - why cant i read a linked list in a module and return the header in main? Today I was pretty confident I would get 100% on my exam, but I wasted all my time trying to fix this error, needless to say I never finished and I'm pretty fed up with it. The idea is:
typedef struct Poly{
    int x;
    int y
    struct Poly *next;
}Poly;

Poly *add_poly();

int main(){

Poly *a = (Poly*)malloc(sizeof(Poly));

a = add_poly(); //so this should be ret, the first 2 ints i typed should be here

printf("%dx^%d",a->x,a->y); //this works
a=a->next;
printf("%dx^%d",a->x,a->y); //this crashes.

}

Poly *add_poly(){
    Poly *temp = (Poly*)malloc(sizeof(Poly));
    Poly *ret = (Poly*)malloc(sizeof(Poly));

    temp = ret; //make sure i get to keep the header of the list?

    while(1){

        scanf("%d %d",&x,&y);

        temp->x=x;
        temp->y=y

        printf("%dx^%d",temp->x,temp->y);//authentication

        temp=temp->next;
        temp=(Poly*)malloc(sizeof(Poly));

        if(y==0){
            temp->x=0;
            temp->y=0;
            break;
        }
    }

    return ret;
}

I don't get it! I've worked with linked lists before in much more complex coding but I never had this problem, I must be missing something but I wasted 1:30 hour trying to find the mistake in the exam, and another 2 hours after I went home, same error, even if I actualy deleted and retyped every command from scratch...

A: You need to initialize your objects that you allocate on the heap. The next pointer in your objects is never set to NULL.
You also have several memory leaks, here what a originally points to is leaked:
Poly *a = (Poly*)malloc(sizeof(Poly));
a = add_poly();

and here what temp originally points to is leaked:
  Poly *temp = (Poly*)malloc(sizeof(Poly));
  Poly *ret = (Poly*)malloc(sizeof(Poly));
  temp = ret;

here you put in x and y in the temp node
    temp->x=x;
    temp->y=y

but here you take the uninitialized next pointer and assign it to temp so it ends with a memory leak and temp pointing somewhere in the blue
    temp=temp->next;

When you declare a pointer you do not need to allocate it in some way which it seems you do.
Only when you want to add a node should you allocate and make sure the contents of the node are initialized properly:
e.g. memset(ptr, 0, sizeof(Poly));
So something like this (you should check return values of sscanf etc in real code), let's assume you have two pointers one first and one last:
Poly* first = NULL;
Poly* last = NULL;

char values[100];
while (fgets(values, sizeof(values), stdin) != NULL)
{
  sscanf(values,"%d %d", &x, &y);

  node = malloc(sizeof(Poly));
  node->x = x;
  node->y = y;
  node->next = NULL;

  if (last == NULL)
  {
    first = last = node;
  }
  else
  {
    last->next = node;
    last = node;
  }
}

A: Only allocate a node if you need one. Allocate the node where next points to, before you step one forward.
Poly *add_poly(){

    Poly *ret = (Poly*)malloc(sizeof(Poly)); // allocate first node
    ret->next = NULL;                        // successor of first node is NULL

    Poly *temp = ret;
    while(1)
    {
        scanf("%d %d", &temp->x, &temp->y);  // read data
        printf("%dx^%d", temp->x, temp->y);  // print data

        if ( temp->y==0 )                    // terminate if y == 0
            break;

        temp->next = (Poly*)malloc(sizeof(Poly)); // allocate next node right to target
        temp = temp->next;                        // step one forward
        temp->next = NULL;                        // successor of last node is NULL
    }

    return ret;
}

Don't allocate memory if you don't need it. a is set by the return value of function add_poly. If you allocte memory to a in main, this becomes a memory leak. Apart from this don't forget to free your memory at end of program.
int testmain(){

    Poly *a = add_poly();   // read data and create list

    Poly *temp = a
    while ( temp != NULL )  // print data from list
    {
        printf("%dx^%d",temp->x,temp->y);
        temp = temp->next;
    }

    while ( a != NULL )     // free list
    {
        temp = a->next;
        free( a );
        a = temp;
    }

    return 0;
}

A: The program has numerous memory leaks.
It can look the following way
#include <stdlib.h>
#include <stdio.h>

typedef struct Poly
{
    int x;
    int y;
    struct Poly *next;
} Poly;

Poly * add_poly( Poly *head );

int main( void )
{
    Poly *head = NULL;
    Poly *next = NULL;

    head = add_poly( head ); //so this should be ret, the first 2 ints i typed should be here

    printf( "%d %d\n", head->x, head->y ); //this works

    next = head->next;

    printf( "%d %d\n", next->x, next->y ); //this crashes.
}

Poly * add_poly( Poly *head )
{
    Poly **current = &head;
    int x, y;

    while( *current ) current = &( *current )->next;

    do
    {
        if ( scanf( "%d %d", &x, &y ) != 2 || x == 0 )
        {
            x = 0; y =0;
        }

        *current = malloc( sizeof( Poly ) );

        ( *current )->x = x;
        ( *current )->y = y;

        current = &( *current )->next;
    } while ( x != 0 );

    return head;
}


text:
Q: How to Open a URL in Python Jupyter Notebook/Cell? I have to show results/webpage in the jupyter noteboook. I want to open a  URL in Python Jupyter Notebook/Cell?. Not in the Browser... Also the code should be inside a function.

A: You can display a webpage inside Jupyter notebooks using IFrame
from IPython.display import IFrame

url = 'https://www.wikipedia.org'
IFrame(url, width=800, height=400)


text:
Q: Angular i18n Dynamic text I am trying to figure out if it is possible to change language for a dynamic content using i18n and related libraries like (ngx-translate) for which I am doing a POC.
I am able to translate the static content but I am not able to figure out how to do the same for dynamic content, like,  content in ngfor loop or data coming from the server.
Is there any way to do the conversion for content coming from the backend/db?
or any other advice/suggestions would be really appreciated.

A: Any content that matches a key in your translation files would do. So if your backend gives you such keys, you can just use translate:

<div *ngFor="let key of keys">
  <p translate>{{key}}</p>
</div>

Or something like that. If this is what you meant?

A: This is fairly simple, provided you know the values your backend may deliver:
// backend data returns known possible values:
const values = ['red', 'blue', 'green']

// de.json
color: {
  "red": "Rot",
  "blue": "Blau",
  "green": "Grün"
}

// app.component.html

<div *ngFor="let value of values">
{{ ('color.' + value) | translate }}
</div>


text:
Q: Alternative way of using Antd Table Columns and ColumnGroups According to Ant Design's Column grouping demo, Ant Design tables are usually just called like the following - assuming you have pre-filled columns and data appropriately:

However, I stumbled upon code which uses deconstruction (const { Column, ColumnGroup } = Table;) and inheritance (e.g. class MyTable extends Table<Interfaces.myTable>) to allow a code like the following within the return() function of the render() part of a custom component

    <MyTable dataSource={myData}
             locale={{ emptyText: 'No data found'}}>
      <ColumnGroup title="Headline 1">
         <MyColumn title="Col 1.1"
                   dataIndex="iName"
                   key="kName"
         />
      </ColumnGroup>
</MyTable>

The problem is now that this does now (after update from Antd 2.10.0 to 3.23.3) no longer work:

Error TS2459 (TS) Type 'ComponentClass, "loading" | "footer" | "style" | "title" | "scroll" | "size" | "children" | "className" | "prefixCls" | "locale" | "getPopupContainer" | "onChange" | "dataSource" | ... 27 more ... | "sortDirections">, any>' has no property 'ColumnGroup' and no string index signature

I understand that this mainly because node_modules\antd\lib\table\Table.d.ts looks now different, and does not longer contain the ColumnGroup property. What alternatives do I have now, if I do not want to rewrite literally thousand lines of code?

A: Moving a major version considered as breaking changes, therefore in your case you might want to stay in your current version 2.x.x or re-implement components logics with the new version.

About inheritance with React,
React has a powerful composition model, its recommended to use composition instead of inheritance to reuse code between components.
If you still think about Inheritance:

At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.
Props and composition give you all the flexibility you need to customize a component's look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.
If you want to reuse non-UI functionality between components, we suggest extracting it into a separate JavaScript module. The components may import it and use that function, object, or a class, without extending it.

When you getting to a situation that inheritance is un-avoidable, try asking a senior React developer, you might just missing something, in any case you can always use references and use composition on them.


text:
Q: B2C Authority String doesn't work with MSAL4J We're implementing Microsoft B2C and I am charged with using MSAL4J 1.13.4 for our java-based web-app clients. I've been provided with an Authority string but it doesn't work against MSAL4J due to the format:
https://sadoenswb2c.b2clogin.com/sadoenswb2c.onmicrosoft.com/b2c_1a_dta_single_abn_authentication/
The MSAL4J source code accepts three types of format, AAD, ADFS, and B2C. None of those Authority types work with the above. The B2CAuthority type error is:
275345 [nio-8080-exec-4] INFO  sw.mw.msal.BusinessHubAuthUtil  - Authority: https://sadoenswb2c.b2clogin.com/sadoenswb2c.onmicrosoft.com/b2c_1a_dta_single_abn_authentication
275413 [nio-8080-exec-4] ERROR .nsw.mw.msal.BusinessHubFilter  - Exception that is not a MsalException
java.lang.IllegalArgumentException: Unsupported authority type. Please use B2C authority
        at com.microsoft.aad.msal4j.AbstractClientApplicationBase$Builder.b2cAuthority(AbstractClientApplicationBase.java:243)

This is expected due to the code, the URL is lacking the "tfp" segment. But my server-side team claims their URLs are standard and should be usable.
On examination of the source I can see the Builder pattern in use (which is great) but both the PublicClientApplication and ConfidentialClientApplication classes are fully encapsulated. It doesn't seem to be possible to pass in an Authority subclass that I could customize to our own situation.
Any help on this would be appreciated. I guess confirmation that the server team is actually giving us a valid B2C Authority would help, or if anyone has used MSAL4J and had it work with B2C.

A: I solved this with the help of a friend. Even though it is counter-intuitive, if you input a URL constructed from the segments of host, tenant, and policy, and add in the tfp segment, the MSAL4J library will accept it and do the right thing. So the Authority string is more of a spec than an actual URL. This not explained anywhere in the Microsoft Azure doco.


text:
Q: Run SML file but not be left in interactive mode I am using New Jersey SML on Windows. If test.sml is an SML file I can execute it by running this at a Windows command prompt:
C:\> sml test.sml

I then get the usual SML output and a new SML command prompt.
Standard ML of New Jersey v110.75 [built: Sat Sep 29 12:51:13 2012]
[opening hw1.sml]
val d2 = (1,1) : int * int
val d3 = (1,1) : int * int
val d4 = (2,1) : int * int
val d5 = (1,2) : int * int
val x7 = true : bool
-

What I would like instead is to be exited back to the Windows command prompt and not be left in the SML interactive mode.
How can I do this?

A: Running SML/NJ that way, it will open the REPL (read-eval-print-loop). Thus it will wait for new declarations to interpret, until you tell it to exit.
Acording to the SML/NJ faq on usage, then

The OS.Process.exit function is the proper means of quiting sml from within a program.

It takes either OS.Process.success or OS.Process.failure as argument.

A: Did you try:
sml <test.sml

Beyond that, using its compilation manager (CM) SML/NJ actually allows you to compile a program into binaries and run them separately. The manual should be able to tell you more (see especially section 15 describing the ml-build command).

A: Also from the command line you can:
Ctrl - C interrupts  (incase of loops that will not exit etc...)
Ctrl - Z exits the REPL


text:
Q: Facing token generation issue in case of data source using direct query When I'm issuing a POST request to generate a token for a datasource using a direct query connection:
POST https://api.powerbi.com/v1.0/myorg/GenerateToken
I'm receiving the following error:
{ "error": { "code": "InvalidRequest", "message": "Generate token request for the proxy model should include the core model ID" } }

This happens only in cases when sending requests for reports using a direct query connection.
If it is expecting a "Core model Id" in such a scenario, cannot understand what is core model Id and how to pass it in the request body as the request body doesn't mention anything like model or modelId.
For the Request body structure, please refer: https://learn.microsoft.com/en-us/rest/api/power-bi/embed-token/generate-token


text:
Q: What could be causing windows service to start slow the first time after changing the logon information? I've been changing various internal windows services to use a new domain account logon to get away from using the administrator account. On every server (Server 2003 network), after changing the logon info, the service takes forever to start. The new user is in the Administrator, Domain Administrators, and Users groups. I eventually want to lock it down even more, but I'm having another issue which I'll post separately. After the initial start, the service stops/starts without issues.
I see this warning in the Application event logs.
Windows cannot copy file C:\Documents and Settings\Default User\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch.2368.30046 to location C:\Documents and Settings\production\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch.2368.30046. Possible causes of this error include network problems or insufficient security rights. If this problem persists, contact your network administrator.
DETAIL - Access is denied.

A: I would imagine that when the service starts the first time the delay is caused by creation of the local profile for the new account that it runs under.  The error relates to the creation of a new profile for 'production', based on the default user template, and the fact that it's erroring isn't going to help the profile creation speed.
Edit: there's a hotfix for that error with .net 1.0, but not 2: http://support.microsoft.com/kb/842765


text:
Q: passing data to jquery modal aside from adding parameters to url? On click of a #dtDelete button I am opening an ajax modal in bootstrap 3.  I am also passing a parameter, selected, along with it and using $_GET on the php page to retrieve it.
As the value of selected may or may not be extremely large I think I should avoid passing the value this way / using $_GET.
How the heck can I pass values other than this method?  Due to the nature of opening the modal (loading it then showing it) I am stuck on any other ways.
$('#dtDelete').on('click', function () {
    //open the modal with selected parameter attached
    $('#modal-ajax').load('/modals/m_keystroke_delete.php?selected='+selected);
    $('#modal-ajax').modal('show');
});

A: Pass a data object as a second param to load for it to make a POST request.
$('#dtDelete').on('click', function () {

    var data = { 'propertyA': 'extremely large data' };

    //open the modal with selected parameter attached
    $('#modal-ajax').load(
      '/modals/m_keystroke_delete.php?selected=' + selected, // url
      data,                                                  // data
      function(responseText, textStatus, XMLHttpRequest) { } // complete callback
    );

    $('#modal-ajax').modal('show');
});

You can even pass your "selected" param through the POST request and use $_POST or even $_REQUEST to retrieve the data. Also notice that the modal now shows once the request has completed.
$('#dtDelete').on('click', function () {

    var data = {
      'selected': selected
      'largeData': '...'
    };

    $('#modal-ajax').load(
      '/modals/m_keystroke_delete.php',
      data,
      function() {

        // Invoke the delete-function
        deleteComp();

        // Show the modal
        $(this).modal('show');
      }
    );
});


text:
Q: Motor does not move I have had success in controlling position of my motor using PD controller. However I have some programming related problem.
Here is my code:
#define encoder0PinA_M1  2
#define encoder0PinB_M1  22
int EnablePin = 8;
int PWMPin1 = 3;
int PWMPin2 = 11;

volatile signed int encoder0Pos = 0;
unsigned long LastTime;
signed int Input;
signed int Scaled_PID;
float PID_Output, Scaled_PID1;
signed int ErrorSum,ErrorDiff,Error,LastError;
float kp=6;
float ki=0;
float kd=1;
int SampleTime = 10;
int TimeChange;
unsigned long Now;

void setup()
{
  pinMode(encoder0PinA_M1, INPUT);
  //digitalWrite(encoder0PinA_M1, HIGH);
  pinMode(encoder0PinB_M1, INPUT);
  pinMode(EnablePin, OUTPUT);
  pinMode(PWMPin1, OUTPUT);
  pinMode(PWMPin2, OUTPUT);
  //digitalWrite(encoder0PinB_M1, HIGH);
  attachInterrupt(0, doEncoder, CHANGE);
  Serial.begin (9600);
  Serial.println("start");
}

void PID()
{
  Now = millis();
  TimeChange = Now - LastTime;
  if(TimeChange >= SampleTime)
  {
    Error =  Input - encoder0Pos;
    ErrorSum = ErrorSum + Error;
    ErrorDiff = Error - LastError;

    PID_Output = kp * Error + ki * ErrorSum + kd * ErrorDiff;

    LastError = Error;
    LastTime = Now;

  }
}

void speedlimitforward()
{
  if (PID_Output >= 15)
  {
    PID_Output= 15;
  }
  if(PID_Output <= -15)
  {
    PID_Output=-15;
  }
  Scaled_PID = PID_Output+15;
  digitalWrite(EnablePin, HIGH);
  analogWrite(PWMPin1,Scaled_PID);

}

void speedlimitbackward()
{
  if (PID_Output >= 20)
  {
    PID_Output= -20;
  }
  if(PID_Output <= -20)
  {
    PID_Output= 20;
  }
  Scaled_PID = PID_Output+20;
  digitalWrite(EnablePin, HIGH);
  analogWrite(PWMPin2,Scaled_PID);
}

void loop()
{
  Input=50;
  PID();
  speedlimitforward();
}

void doEncoder()
{
  if (digitalRead(encoder0PinA_M1) == digitalRead(encoder0PinB_M1))
  {
    encoder0Pos++;
  } else {
    encoder0Pos--;
  }

}
If you look at my code, I have declared Input as global variable and in loop() I give a value to Input (50 counts in this code). This code works fine and motor stops at close to 50 encoder counts.
But when I change the loop in above code to the code given below my motor does not move. I want it to move to 50 count wait for sometime and come back to 0 count :
void loop()
{
  Input=50;
  PID();
  speedlimitforward();

  delay(2000);
  Input=0;
  PID();
  speedlimitbackward();

  delay(2000);
  Input=-100;
  PID();
  speedlimitbackward();

 }

A: *

*If you ask the same question in other places and get an answer, I think you should come back here and answer your own question and mark it as answered, otherwise people are going to spend time on it.

*The problem is clearly the delay(2000), and if you look at the code you'll see why. When you only have one instruction what happens is that the loop starts, checks the time and see if the motor has to move, based on how long has passed. So if you put a delay, the next time the loop runs, the time will already be entirely spent waiting and the motor will not move.

*What you can do is keep track of what the motor is doing, and move it based on that. For example, keep a variable called something like movement_completed and assign to it a value that is returned by the movement functions when they have, well, completed the movement. Only after that variable is set, go on with the next set of movements.
I think that the main problem here is that you have to remember that loop() is being constantly called, it's not something that runs just once.
You need to have a clear understanding of why your motor stops with the first code (then you'll understand why it doesn't move with the second).


text:
Q: Relative velocity of light beam and rocket (special relativity) I'm having a hard time understanding the following problem regarding special relativity:
Let's say we have a light beam moving in the +x direction with a speed of c, and a rocket is moving in the -x direction with a speed of 0.8c. Let's say they are separated by a distance d = 10 light minutes at t = 0 s. Now we want to calculate at what time $t_m$ the light beam will meet the rocket. In order to do this, we can calculate the relative speed $v_{relative}$ of the light beam with respect to the rocket (or vice versa), and then use $t = \frac{d}{v_{relative}}$, where d is 10 light minutes, and $v_{relative}$ is the relative speed. We know that we can't add velocities directly in relativity ($v_{relative} \neq c + 0.8c = 1.8c$), otherwise you break the light barrier, so you have to use Einstein's velocity addition formula. But this formula will return a maximum of 'c' as relative speed? But that would imply that it doesn't matter whether the rocket is stationary, or moving at v = 0.8c towards the light beam? What am I missing exactly? How would you go about solving this problem, using the relative speed?

A:
But that would imply that it doesn't matter whether the rocket is stationary, or moving at v = 0.8c towards the light beam? What am I missing exactly?

You are not missing anything. That is correct. Regardless of the velocity of the rocket in a separate frame, in the rocket's frame the light is traveling at c.
This is not a problem to be fixed, it is a necessary feature. This is the second postulate in action: the speed of light is c in all inertial reference frames. In order to fulfill this criterion it is necessary that the relativistic velocity addition formula be structured so that the relative velocity between c and anything else is c.

A: It is useful to draw a diagram $t \times x$. Then calculate the equations for the straight lines of the beam and of the rocket trajectory. The interception is the event $t,x$ where the light reach the rocket. The expression relative velocity can be confusing, because it is used normally for different frames, and there is no frame for a light beam.


text:
Q: Yii2 add attributes to script tag using registerJs Is there a way to add attributes to script tag using registerJs?
For example:
$this->registerJs("var options ={'a' : 2};", View::POS_END, 'my-options');

The above will  output something like that:
<script type="text/javascript">var options ={'a' : 2};</script>

But I need to add some attributes to script tag(or even change the type for richsnippets)


text:
Q: Completely new to Python. Unable to understand a lines of code written below I am having difficulty understanding the following lines of Python code. The code is written to find the vowels contained in the word "milliways".
vowels = ['a' , 'e' , 'i' , 'o' , 'u']
word = "milliways"
found = []
for letter in word:
    if letter in vowels:
        if letter not in found:
            found.append(letter)
for vowel in found:
    print(vowel)

Can someone please help me understand the code above.

A: So in the first 3 lines of code we first create a list of letters (vowels) to search for, define a word to search for vowels in, and create an empty array where we will store vowels found.
Next we iterate through each letter of the word we chose and check it the letter is a vowel and not already in the list with found vowels, if those criteria are met, we add the vowel to the "found" list.
In the last 2 lines of code we just loop through the list of found vowels and print them out to actually see which vowels we found in the word.

A: I've added comments to your code so that you can see what's going on
vowels = ['a' , 'e' , 'i' , 'o' , 'u'] # this declares a list of vowels
word = "milliways" # declares an input word
found = [] # used to store list of vowels in word

for letter in word: # iterates through every character in word
    if letter in vowels: # checks if character is in the vowels list
        if letter not in found:
            found.append(letter) # if the character is a vowel, and not in found list it adds it

for vowel in found: # prints list of vowels in word
    print(vowel)


text:
Q: A criterion for isotriviality of families of varieties of general type Let $f:X\rightarrow Y$ be a surjective map between smooth varieties with connected fibers. Assume that the generic fiber of $f$ is of general type, and everything is over $\mathbb{C}$. $f$ is said to be isotrivial if all its smooth fibers are isomorphic.
When $\mathrm{dim}X=2$ and $\mathrm{dim}Y=1$, if $\mathrm{deg}(f_*\omega_{X/Y})=0$, then $f$ is isotrivial, in BPV,Chapter III. Theorem 17.3.
My question is that does this true for $\mathrm{dim}X\geq 3$ and $\mathrm{dim}Y=1$?
The tools to prove this are using the period map and Torelli's theorem for curves.
In case $\mathrm{dim}X=2$ and $\mathrm{dim}Y=1$:
If $\mathrm{deg}(f_*\omega_{X/Y})=0$, then the period map $$\mathcal{P}:Y\rightarrow \overline{\Gamma/D}$$ is constant, where $D$ is the period domain and $\Gamma$ is the monodromy group. Thus $\mathcal{P}(Y^0)$ is a point in $\Gamma/D$, where $Y^0\subseteq Y$ such that $f^0:X^0=f^{-1}(Y^0)\rightarrow Y^0$ is smooth. By Torelli's theorem, all nonsingular fibers will be isomorphic.
In higher dimensional cases, it seems that Torelli's theorem is not true in general. Does this true that $\mathrm{deg}(f_*\omega_{X/Y})=0$ implies the associated period map is constant?


text:
Q: Having Multiple icons on the taskbar for most IDE For most IDE, such as eclipse, Intellij, Processing, and other, it seems that even after pinning the program to the task bar, when I actually open it, it creates another program that is not pinned to the task bar. As a result, I have multiple icons on the taskbar. I'm guessing that the ones I pinned on the taskbars are kind of like launching applications and they open a separate application, not that I'm sure of this theory, but I'd prefer to have only one application showing up on the taskbar. So, is there a way to set it up so even after I start the program, another doesn't show up on the taskbar?
Also, It seems like I can't pin the program that gets opened.
Here's a picture of the taskbar.
Or, since it seems like I can't post a picture yet,
This is what's going on with my taskbar.
http://i1320.photobucket.com/albums/u538/jerichoi224/Untitled_zps216034f9.png

A: This is because IDEs launch instances, which Windows doesn't support taskbar pinning for.
The solution for Eclipse IDE is to add:
-vm
C:/path_to_jre/bin

, to the beginning of the eclipse.ini file, in the eclipse directory, and relaunching the IDE.


text:
Q: Initialize PeerConnectionFactory with latest webrtc dependency I am using the below dependency of webrtc in my Android App
implementation 'org.webrtc:google-webrtc:1.0.+'

How to Initialize PeerConnectionFactory, I am doing it in below manner but it is giving compilation error.
private void initializePeerConnectionFactory() {
    PeerConnectionFactory.initializeAndroidGlobals(this, true, true, true);
    factory = new PeerConnectionFactory(null);
    factory.setVideoHwAccelerationOptions(rootEglBase.getEglBaseContext(), rootEglBase.getEglBaseContext());
}

I tried it with below fashion:
private void initializePeerConnectionFactory() {
    PeerConnectionFactory.initializeAndroidGlobals(this, true, true, true);
    factory = new PeerConnectionFactory(null);
    factory.setVideoHwAccelerationOptions(rootEglBase.getEglBaseContext(), rootEglBase.getEglBaseContext());
}

But it's not working

A: As of today (25 Jan 2023), use the latest version of the dependency.
As the older ones had security vulnerabilities and google play does not accept them.
You can initialize PeerConnectionFactory like this:
https://webrtc.googlesource.com/src/+/refs/heads/main/examples/androidapp/src/org/appspot/apprtc/PeerConnectionClient.java?autodive=0%2F%2F

A: Using
org.webrtc:google-webrtc:1.0.32006

which I believe to be the latest version of webrtc available
you initialise the peer connection factory using the following code
   PeerConnectionFactory.InitializationOptions initializationOptions = PeerConnectionFactory.InitializationOptions.builder(getApplicationContext()).createInitializationOptions();
    PeerConnectionFactory.initialize(initializationOptions);
    //Create a new PeerConnectionFactory instance - using Hardware encoder and decoder.
    PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
    DefaultVideoEncoderFactory defaultVideoEncoderFactory = new DefaultVideoEncoderFactory(rootEglBase.getEglBaseContext(),  /* enableIntelVp8Encoder */true,  /* enableH264HighProfile */true);
    DefaultVideoDecoderFactory defaultVideoDecoderFactory = new DefaultVideoDecoderFactory(rootEglBase.getEglBaseContext());

    factory = PeerConnectionFactory.builder().setOptions(options)
            .setVideoEncoderFactory(defaultVideoEncoderFactory)
            .setVideoDecoderFactory(defaultVideoDecoderFactory)
            .createPeerConnectionFactory();

Hope this helps!