text:
Q: Parsing through log file and printing out regex backreferences I want to parse my /var/log/maillog to print out the email addresses in from=<> and to=<> (mainly to do a quick check for false positives in the DNS RBLs that I've configured)
A maillog entry looks like this (postfix):
Jun 20 17:27:52 foobarserver postfix/smtpd[15925]: NOQUEUE: reject: RCPT from sbr.nouveauquebec.com[184.22.154.110]: 554 5.7.1 Service unavailable; Sender address [corporate@nouveauquebec.com] blocked using urired.spameatingmonkey.net; Red listed, see http://spameatingmonkey.com/lookup/nouveauquebec.com; from=<something@spam.com> to=<foo@foo.bar> proto=ESMTP helo=<sbr.nouveauquebec.com>

and my regex is
from=<(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b)> to=<(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b)>

I'm storing the matches in back references \1 and \2 which I want to print out. What I want to do is pipe the output from cat /var/log/maillog and apply the regex on each line and output the backreferences.
Is there a quick way to accomplish this?

A: This one uses a simplified regex and non-greedy quantifiers:
perl -ne 's/^.*from=<(.+?@.+?)> to=<(.+?@.+?)>.*$/$1 $2/; print;' /var/log/maillog

A: Using sed:
sed -r -n 's/^.* from=<([^>]+)>\s*to=<([^>]+)>.*$/\1 \2/p' /var/log/maillog


text:
Q: Converted a nested JSON column to Pyspark DataFrame Columns I have read and stored parquet files in S3 using pyspark.pandas dataframes. Now in the second phase I am trying to read the parquet files in a pyspark dataframe in databricks, and I facing issues converting the nested json columns into proper columns. First I read the parquet data from S3 using the command:
adf = spark.read.parquet('s3://path')

An example nested column in my pyspark dataframe looks like this:
event_params:array
   element:struct
      key:string
      value:struct
          double_value:double
          float_value:integer
          int_value:long
          string_value:string

Example Data in a pyspark dataframe column:
0: {"key": "ignore_referrer", "value": {"double_value": null, "float_value": null, "int_value": null, "string_value": "true"}}
1: {"key": "session_engaged", "value": {"double_value": null, "float_value": null, "int_value": null, "string_value": "1"}}
2: {"key": "engagement_time_msec", "value": {"double_value": null, "float_value": null, "int_value": 123, "string_value": null}}
3: {"key": "value", "value": {"double_value": null, "float_value": null, "int_value": 23, "string_value": null}}
4: {"key": "page_location", "value": {"double_value": null, "float_value": null, "int_value": null, "string_value": "https://abc/0.0.23-manual/index.html"}}

I am trying to create new columns for all the fields present in the json, so for example the result I am looking for is something like this:
key  session_engaged value
1        12           true

One way I tried was using spark.sql, but I am getting errors like Dataframe has no object'_get_object_id':
bdf = adf.createOrReplaceTempView(adf)
df = spark.sql('''
SELECT
               event_timestamp,
               event_name,
               event_params :element:value
 FROM bdf;''')

ERROR:
AttributeError: 'DataFrame' object has no attribute '_get_object_id'

I have tried using spark.SQL to do this, and I have also explored the explode function, but these columns are different for each row, and I want to just convert all these json nested structures to columns. If anybody can point me in the right direction using any working approach that would be very helpful!

A: I'm not really sure about the expected output, where did 12 come from?
You can use posexplode to get every element in event_params in a row with the position as a column of its own.
Then you can access all json fields with .select("*", col("col.value.*")) and this command will add the json fields to the df.
full code:
from pyspark.sql.functions import posexplode, col

df \
.select(posexplode("event_params")) \
.select("*", col("col.key") , col("col.value.*")) \
.show(truncate=False)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Lat/Lng from a Geometric property? Alright, I am very new to GIS, my question might not even make sense, but help me get through this.
I have this JSON data of some fields which have this geometry property:
"geometry": {"type":"Polygon","coordinates":[[[-9808308.55,4693529],[-9808325.985,4693527.669],[-9808334.548,4693526.964],[-9808333.404,4693527.538],[-9808328.685,4693530.385],[-9808326.444,4693532.015],[-9808322.29,4693535.601],[-9808318.672,4693539.547],[-9808315.572,4693543.916],[-9808313.091,4693548.874],[-9808311.481,4693554.29],[-9808310.817,4693559.639],[-9808310.73,4693566.446],[-9808307.432,4693534.353],[-9808308.55,4693529]]]},

So these co-ordinates are, obviously, not Lat-Lng's of the field co-ordinates which is what I want when I have to project them on Google Maps. How should I go about this? Can we get Lat/Lng of these co-ordinates without knowing which the transformation formula which had been applied on it? (I even don't know these field co-ordinates belong to which region!)

A: It is a part of a GeoJSON formated geometry  and the ordering of x and y are important.

Point coordinates are in x, y order (easting, northing for projected coordinates, longitude, latitude for geographic coordinates):


text:
Q: Save text as a hyperlink style for Access and C# private void button1_Click(objectsender, EventArgs e)
    {
        OpenFileDialogdlg = newOpenFileDialog();

        dlg.Filter = "JPGFiles(*.jpg)|*.jpg|PNG Files(*.png)|*.png|All Files(*.*)|*.*";

        if(dlg.ShowDialog() == DialogResult.OK)
        {
            stringpicLoc = dlg.FileName.ToString();

            txt_image.Text = picLoc;

            pictureBox1.ImageLocation = picLoc;
        }
    }
}

The command above will create a image path on the textbox(txt_image).
And when clicking save, the command is shown as below:
command.CommandText = "insert into RecordsSheet ([Picture]) values('" + txt_image.Text + "')";

Then an error occur saying that "Data type mismatch in criteria expression, since the "Picture" column setting in MS Access is Hyperlink.
I am not sure what to do to insert the data as a hyperlink, instead of a text.


text:
Q: Searching for alphanumeric passwords in regex I have been trying to create a Regex that can detect alphanumeric passwords between 5-20 characters in lengths. These passwords can contain special characters (@$!%*#?&£). My attempts either don't detect all of my test cases or they generate a large number of false positives.
The Regex currently looks like this:
\b(?=.*[a-zA-Z])(?=.*\d*)(?=.*[@$!%*#?&£]*)[a-zA-Z\d@$!%*#?&£]{5,20}(?<![a-zA-Z ])\b

Here is my Regex running on Regexr with my test cases
The criteria for the Regex is as follows:

*

*Detect mixed alpha numeric words between 5 & 20 chars long

*Detect special symbols (@$!%*#?&£ etc)

When writing the original regex I encountered alot of problems getting the character boundary to apply, say if a word is 21 characters I wouldn't want it getting detected at all. I essentially only want to scan items between this length, but this boundary has stopped many matches getting detected.
Take the strings "Rese7" & "Rese7A".
The first string matches && the second doesnt, I suspect this is because of how I have implemented the character checking. I basically want the regex to do the following things:

*

*Define words as any characters (including special)

*Look for words between 5-20 characters in length

*Check if they are alpha numeric (aA-zZ0-9!£$ etc)

*Only match words that fulfill this criteria

I'm not sure if I', thinking about this right, I had a look at other alphanumeric password questions and the answers didn't look to satisfy my test cases:

*

*There were only 2 regex answers on this but they didnt work in RegExr...

*This isn't complex enough

*Nothing on here worked despite it being well explained
Thanks for your help!

A: (?:^|[^a-zA-Z\d@$!%*#?&£])[a-zA-Z\d@$!%*#?&£]{5,20}(?:$|[^a-zA-Z\d@$!%*#?&£])

What you need is the beginning of the string ^ or not one of your matchable characters [^a-zA-Z\d@$!%*#?&£] followed by 5 to 20 matchable characters [a-zA-Z\d@$!%*#?&£]{5,20} followed by the end of the string $ or one non matchable character [^a-zA-Z\d@$!%*#?&£] again.
Regexs are as much about what you don't want as what you do

A: In your pattern you use these positive lookaheads(?=.*\d*)(?=.*[@$!%*#?&£]*)  where what you want to assert should match 0+ times a digit or a special char using the asterix *.
So the assertion would be true if it is or is not there, which will always be true giving you much more matches than you would expect.
You could use anchors to assert the start ^ and the end $ of the string and leave out the * to match it at least 1 times to make sure it is there.
The negative lookbehind at the end (?<![a-zA-Z ]) makes sure that what is on the left is not a char a-zA-Z or a space. You can omit this by not allowing a space to match.
But enforcing this rule would not allow rese7FwDdvgfe to match but in your example data you do want to match it so you can leave the lookbehind out of the pattern.
^(?=[^a-zA-Z\s]*[a-zA-Z])(?=(?:[^\d\s]*\d|[^\s@$!%*#?&£]*[@$!%*#?&£]))[@$!%*#?&£a-zA-Z\d]{5,20}$

Explanation

*

*^ Start of the string

*(?=[^a-zA-Z\s]*[a-zA-Z]) Assert upper or lower case a-z

*(?= Positive lookahead

*

*(?: Non capturing group

*

*[^\d\s]*\d Assert a digit

*| Or

*[^\s@$!%*#?&£]*[@$!%*#?&£] Assert a special char

*) Close non capturing group

*) Close positive lookahead

*[@$!%*#?&£a-zA-Z\d]{5,20} Match all of the allowed 5 - 20 times

*$ End of string

Regex demo


text:
Q: Command Line Variable for .NET Framework I'm trying to write a batch file that installs a windows service using installutil.exe.  I would like to use the installutil.exe that is in the latest version of the .Net Framework (located in C:\Windows\Microsoft.NET\Framework\v4.0.30319 on my machine).
Is there an easy way to change the directory in the command line to the latest .NET Framework directory?
For example, I know using cd %WINDIR% will give me C:\Windows.  What would I type to get to the latest .Net Framework Directory?

A: Using Reed Copseys advice about inspecting the registry I found a sample on another post about how to read the registry from a batch file.
Here is my batch file that finds the install directory for the .Net 4 Framework and installs my service:
@SET INSTALLUTILDIR=
@for /F "tokens=1,2*" %%i in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v "InstallPath"') DO (
    if "%%i"=="InstallPath" (
        SET "INSTALLUTILDIR=%%k"
    )
)

%INSTALLUTILDIR%\installutil MyService.exe

And here is the link where you can find the registry key for the specific version of the framework you are looking for: http://msdn.microsoft.com/en-us/kb/kbarticle.aspx?id=318785

A: There is no environment variable you can use as a "standard" replacement like that.  The way most installers do it is by inspecting the registry for the Framework installation path.


text:
Q: Could we rescue, raise and rescue the same error again using exception hierarchy syntax in ruby? I would like the exceptions to be rescued, raised and rescued again using exception hierarchy syntax like the below snippet..
class InnerCustomError < StandardError
  def initialize(msg = "inner")
    super
  end
end

class OuterCustomError < StandardError
  def initialize(msg = "outer")
    super
  end
end

begin
  raise InnerCustomError
rescue InnerCustomError
  raise OuterCustomError
rescue OuterCustomError, StandardError => e
  e.message
end

but this raises ==> OuterCustomError (outer)
why is this behaviour? Instead I would like it to be rescued ..
I understand nested begin end blocks like below is used to achieve the same,
begin
  begin
    raise InnerCustomError
  rescue InnerCustomError
    raise OuterCustomError
  end
rescue OuterCustomError, StandardError => e
  e.message
end

also I understand there are performance impacts with this idea but I would like to understand how is the former interpreted?

A:
but this raises OuterCustomError. Why is this behaviour?

Because that's how this construct works. The first matching rescue is selected as a handler for the exception and the result of this handling will be the result of the begin/rescue. If the handler raises and you want to catch that new exception, you need to add another layer of begin/rescue, exactly like you show in the last snippet.
It is described in the documentation here.


text:
Q: What kind of Library that will handle URL Linked Documents What kind of library do I need to set-up in order to be able to put a URL like on the Document which will allow that Document to be access by a Web Playable Program?
I will post the Document to the Library and then assign a URL to that Document.
Then the URL will be copied into a Training System to allow users to tab the URL and the Document to be pulled up.

A: which version of SharePoint are you using? If it's SP 2016 or SP Online you can create a guest link once you upload the document that will allow the document to be accessed by other people/systems that don't have access to the list.

A: You can setup a custom List and add a 'Link/URL' type column.


text:
Q: why the "reorder" in ggplot did not show the mean value? I am learning ggplot2 with the mtcarsexample:
library(ggplot2)

mtcars$vs <- factor(mtcars$vs)

#it shows the mean value
qplot(reorder(mtcars$vs, mtcars$mpg))

#it do not show the mean value, Why?
ggplot(mtcars, aes(x=reorder(vs, mpg), y=mpg, fill=vs))+
    geom_bar(stat="identity")

How to show the mean value as qplot using ggplot2?

A: What makes you think the initial plot is showing you the mean value? It is showing the counts of different factor levels - 18 and 14 respectively. It is equivalent to this:
ggplot(mtcars, aes(x=reorder(vs, mpg))) + geom_histogram().

The second plot is summing up the mpg values per each value of vs value. Try:
tapply(mtcars$mpg, mtcars$vs, sum)

These are the two values that are getting plotted in the bar plot. If you area really trying to get averages by vs value, then you should use:
ggplot(mtcars, aes(x=vs, y=mpg, fill=vs)) + geom_boxplot()


text:
Q: Modifying inserted record in DynamoDB I have a lot (millions) of json records stored as ndjson in a file, which I need to get into DynamoDB. I'm doing this by splitting the original file in chunks automatically and then uploading it to S3, which then triggers lambdas that parse the data and insert it into my DynamoDB table.
The problem I have is that every record contains a URL to another json file which contains some additional data about that record, and I would like to fetch that data and save it together with the record, so that I can perform quick searching with OpenSearch later.
My dilemma is should I fetch this data in the same lambda that does the parsing, or should I make a separate lambda that triggers on every DynamoDB insert? In my understanding, insert-triggered lambdas are invoked after the record is inserted (couldn't find anything in the documentation about this), so I would do one insert and one update for each record.
Notes:

*

*The https server I'm fetching the additional data from limits number of requests to ~100 requests per minute, and in the end I would like these lambdas to have different IPs so that I can go beyond that limitation

*I'm an AWS newbie so feel free to correct anything you thing I'm doing wrong

A: EDIT - Editing in light of additional info provided.
Between the 2 options, you rightly pointed out some of the considerations. For example, the insert/update option is more costly, because you are performing 2 operations instead of 1.
Another concern is the limit of 5 minutes per ~100 API calls. Since you have millions of calls to make, the time it takes is 1,000,000 / 100 * 5 minutes = ~35 days. However, I don't think it is possible to control the Lambda IP address without some advanced setup (along the line of running Lambda in VPC and using a custom NAT instance that changes IP every time). Even then, the rate is not going to be very fantastic.
So if 35 days is an issue, I think it is better to run a fleet of EC2, each with different IP address, to parallelly process the records. EC2 gives greater control over the networking compared to Lambda, as Lambda is meant to be serverless.
If it is not an issue, I don't see anything wrong with the 2 options you proposed. Just choose the one you are more comfortable with, as these 2 entail different solutions.


text:
Q: awk - match positive whole numbers and floating point numbers only I have an input file in .csv format which contains entries of tax invoices separated by pipe.
for example:
Header--TIN | NAME | INV NO | DATE | NET | TAX | OTHERS | TOTAL
Record1-29001234768 | A S Spares | AB012 | 23/07/2016 | 5600.25 | 200.70 | 10.05 | 5811.00
Record2-29450956221 | HONDA Spare Parts | HOSS0987 |29/09/2016 | 70000 | 2200 | 0 | 72200

The record's NET value, TAX Value, OTHER Charges and TOTAL value column may contain positive whole numbers or positive floating point numbers with 2-4 places after the decimal point.
Now my requirement is to check whether the columns meets the specified constraints by checking with appropriate 'Regular Expression using awk'.
I need to match these 4 columns with regular expression such that if I encounter any numeric value other than positive whole number or positive floating point number , I need to print an error message to the user.
I've tried the following , but it doesn't seem to work.
if(!($5 ~ /[0-9]+/) || !($5 ~ /[0-9]+[.][0-9]+/) || ($5<=0))
    { printf("NET VALUE (Violates constraints)" }

Can anyone give the proper working regular expression or any implementation using built-in-function to meet my requirements?

A: Sounds like your validation should be:
$5 ~ /^[0-9]+(\.[0-9]{2,4})?$/

If it matches that, then it's valid (either a positive whole number, or a number followed by . and between 2 and 4 other numbers).
The anchors to the start and end of the field are important!
As rightly pointed out in the comments, if you want to accept numbers with no digits before the decimal point, then you will have to go for a more complex regular expression.


text:
Q: How to wrap the nth to nth element in a div I have this:

and I am trying to get:

using jQuery. I have tried using nth-child, but then it wraps every element with that div instead.
I am trying to get every 5 elements into a div called holder.
Although that, I am trying to use "nth to nth" element approach. In other words, it is NOT an assumption that every 5 element is wrapped, but rather 1st-to-5th element wrapped in one div, and perhaps 6th-to-14th element in another. And let's assume these 2 batches are both wrapped with the same class, holder.
Any dynamic way to batch these up?

A: You can do it by using each() and wrapAll(),
var tmp = $();
$(".myTest").each(function(i){
  tmp = tmp.add(this);
  if(((i+1) % 5) == 0){
    tmp.wrapAll("
");
    tmp = $();
  }
});

DEMO


text:
Q: Can't update OpenSusue 12 without Memory Stick I recently installed OpenSuse using a jump drive that had the openSuse DVD-1 "dd"'ed to it. Everything went fine. However, when I try to install software using zypper or update the system software, I have to have the usb inserted or zypper warns me it's missing a repository and the software updater just spins (don't lock, I can close it). How can I fix this?
Thanks,
JPD


text: Q: How to rotate labelme polygons to increase dataset size? I want to increase size of my dataset. I have already annotated the images I have using the labelme tool but now i want to rotate the images. Is there away to rotate all the polygons created while annotating the image so that i don't have to again annotate the new rotated images?


text:
Q: How to change this jQuery widget (written for jQueryUI 1.7) so that it works with jQueryUI 1.8 This jQuery plugin, which lets users draw rectangles in a div, works with jQueryUI 1.7.2.
I need to get it working with jQueryUI 1.8.4. From reading the widget upgrade guide, I can't work out what needs to change. I tried renaming _init() to _create(), but that didn't do anything. What else do I need to change to get it working? Thanks for reading.

A: The $.widget signature changed to do the extend internally, so change this:
$.widget("ui.boxer", $.extend({}, $.ui.mouse, {

To this:
$.widget("ui.boxer", $.ui.mouse, {

And at the bottom, remove the extra ) as well, changing })); to });

Also, to get the default options, it's best to move them right inside, like this:
$.widget("ui.boxer", $.ui.mouse, {
  options: {
    appendTo: 'body',
    distance: 0
  },
  ///rest of widget, unchanged...
});

Here's a sample of the updated version with only the changes above, working.


text:
Q: DistinctBy With Condition in LINQ I am having entity collection from Database which contains certain duplicates like One sequence with values and other sequence with empty values. I would like to remove sequence with empty one. I have tired moreLINQ for DistinctBy but still my case is not satisfying.
I have a following list from result set.
Result: Id=1, Name="Test1", Status="New", Values=NULL
Result: Id=1, Name="Test1", Status="Assigned", Values=123
Result: Id=2, Name="Test2", Status="New", Values=NULL
Result: Id=2, Name="Test2", Status="Assigned", Values=698
Result: Id=3, Name="Test3", Status="Assigned", Values=569
Result: Id=4, Name="Test4", Status="New", Values=NULL
Result: Id=5, Name="Test5", Status="Assigned", Values=156

I would like to retrieve follwoing outputs always by skipping duplicate with empty values or New status.
Result: Id=1, Name="Test1", Status="Assigned", Values=123
Result: Id=2, Name="Test2", Status="Assigned", Values=698
Result: Id=3, Name="Test3", Status="Assigned", Values=569
Result: Id=4, Name="Test4", Status="New", Values=NULL
Result: Id=5, Name="Test5", Status="Assigned", Values=156

A: You can so something like below
DOTNETFIDDLE working code
var modified = listOfValues
                .GroupBy(x => x.Id)
                .Select(x => x.OrderByDescending(x => x.Values ?? int.MinValue).FirstOrDefault());

Results:

A: Group by Id and take the first record of each group that is ordered by Status:
var records = new[]
{
    (Id:1, Name:"Test1", Status:"New", Values:default(int?)),
    (Id:1, Name:"Test1", Status:"Assigned", Values:123),
    (Id:2, Name:"Test2", Status:"New", Values:default(int?)),
    (Id:2, Name:"Test2", Status:"Assigned", Values:698),
    (Id:3, Name:"Test3", Status:"Assigned", Values:569),
    (Id:4, Name:"Test4", Status:"New", Values:default(int?)),
    (Id:5, Name:"Test5", Status:"Assigned", Values:156),
};

var result = records
    .GroupBy(r => r.Id)
    .Select(r => r.OrderBy(x => x.Status).First());

Result:
Id  Name    Status      Values
------------------------------
1   Test1   Assigned    123
2   Test2   Assigned    698
3   Test3   Assigned    569
4   Test4   New         null
5   Test5   Assigned    156


text:
Q: Telerik-grid paging and sorting when using an external data source I am experimenting with using an external data source with a Telerik Grid using their Twitter search sample as my guide
http://demos.telerik.com/aspnet-mvc/razor/grid/externalservicetwitter
I have got their sample running but cannot get paging and sorting to work.
In the sample they set-up the grid server side using the code
@(Html.Telerik().Grid<TwitterItem>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Template(o => { }).Title("Author").Width(100);
        columns.Template(o => { }).Title("Avatar").Width(80);
        columns.Bound(o => o.text).Title("Post");
    })
    .ClientEvents(events => events
        .OnDataBinding("onDataBinding")
        .OnRowDataBound("onRowDataBound")
    )
    .Scrollable(scrolling=>scrolling.Height(400)))

So I added .Pageable and .Sortable to the construct like in the other samples but this seems to make no difference
@(Html.Telerik().Grid<TwitterItem>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Template(o => { }).Title("Author").Width(100);
        columns.Template(o => { }).Title("Avatar").Width(80);
        columns.Bound(o => o.text).Title("Post");
    })
    .ClientEvents(events => events
        .OnDataBinding("onDataBinding")
        .OnRowDataBound("onRowDataBound")
    )
    .Scrollable(scrolling=>scrolling.Height(400))
    .Pageable()
    .Sortable()

)
Should this be working?  Is there something else I should be doing?

A: I am having the same problem.
My challenge is that the users want to retreive repeatedly for different criteria and they expect the results to accumulate in the grid until they clear the grid.  I am building this capability.  I got the accumulation to work, but along the way something is causing the "Displaying items 0 - 0 of 0".
This question has been sitting out here for a long time.  It makes me feel discouraged.
My theory is that the custom binding messes up the other settings.
Joe


text:
Q: Volume UI Should not appear when using on screen volume slider- iOS
Volume UI should not appear during use of volume slider of the application.

A: I am not saying this is the perfect solution but somehow with this tricks, my problem has fled away:
 MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame: CGRectMake(0, -100, 0, 0)];
[self.view addSubview: volumeView];

I have implemented above code in viewWillAppear and problem resolved.
With above code you can also customise your volume controller frame.


text:
Q: PowerShell New-GPLink is giving the errors on cross domains I am trying to write a PowerShell script to link my GPOs to several OUs on multiple domains. The issue I am having is with the New-GPLink cmdlet. When I run the command I get different errors. I can create and link GPOs in all domains in GPMC.
My domain is setup as a Forest with two domains under it (lets call them DomA and DomB). Then I have a third domain not under that forest (lets call it DomC).
My computer is in DomA and my account is in DomC.
The GPO is created in DomA and well call it GPO_Test_1.
The OU I want to link is at ou=Test,ou=GPO Testing,dc=DomA
If I run:
New-GPLink -Name "GPO_Test_1" -Target "ou=Test,ou=GPO Testing,dc=DomA" -LinkEnabled Yes

I get this error:
New-GPLink : The "GPO_Test_1" GPO was not found in the DomC domain.
Parameter name: gpoDisplayName
At line:1 char:1
+ New-GPLink -Name "GPO_Test_1" -Target "ou=Test,ou=GPO Testin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.GroupPolicy.GPDomain:GPDomain) [New-GPLink], ArgumentExceptio
   n
    + FullyQualifiedErrorId : GpoWithNameNotFound,Microsoft.GroupPolicy.Commands.NewGPLinkCommand

So I can see its looking at the domain that my account is on. Not the one that my computer is on.
I tried different parameters resulting in different errors.
-Domain DomA
New-GPLink : A referral was returned from the server. (Exception from HRESULT: 0x8007202B)

-Server DConDomA
New-GPLink : Value does not fall within the expected range.

-Domain DomA -Server DConDomA
New-GPLink : Value does not fall within the expected range.

I read that this may be because my credentials are not passing correctly to the other domain. So I tried the below:
Invoke-Command -ComputerName DConDomA -scriptblock {New-GPLink -Name "GPO_Test_1" -Target "ou=Test,ou=GPO Testing,dc=DomA" -LinkEnabled Yes} -credential $c

The "GPO_Test_1" GPO was not found in the DomC domain.

Again the error referencing domain my account is on ...
Adding the -Server DConDomA inside the script block still gives this error.
New-GPLink : Value does not fall within the expected range.

Tried a few different DCs (including RIDMatser on DomA and DomC) but those results in the same type of errors.
I am not sure what I am missing or doing wrong here.

A: I found my own answer in is Microsoft documentation. Seems I just missed it. My Domain parameter has to be the FQDN where as I using the short name.
https://learn.microsoft.com/en-us/powershell/module/grouppolicy/new-gplink?view=windowsserver2022-ps
-Domain
Specifies the domain for this cmdlet. You must specify the fully qualified domain name (FQDN) of the domain.
This note explained why it was checking the domain where my account was as well.
"If you do not specify the Domain parameter, the domain of the user that is running the current session is used. If the cmdlet is being run from a computer startup or shutdown script, the domain of the computer is used. For more information, see the Notes section in the full Help."


text:
Q: How to dynamically attach behaviors to dynamically loaded elements in HTML using jQuery I have an HTML form being attached to a div element dynamically. How can I attach existing behavior to the newly added elements.
For example. I have methods like
$.fn.jqueryAjaxFormLoad - defined in jquery.ajaxload.js
$.fn.displayMessage  - defined in jquery.messagebar.js

already defined, which were loaded during page load. Now I want to append or make these available to the newly added form element and its children. What would be a best way to achieve this using jQuery.
The end expectation is that I can call
$('.form_element').displayMessage() on one of the form elements.

A: You can use the following code to run an event on click of an element:
$("#something").click(function(){
    alert("Something was clicked!");
});

Simply replace click with the event you want to use. You can see a list of the events at this page.
If your event isn't in the list of events at the above link, simply use this code:
$("#something").bind("touchstart",function(){
    alert("You tapped something!");
});

The above code will make an alert appear when the user taps the screen on a mobile device.
Simply change touchstart with whatever event you need to use.
Ad@m

A: You can bind handlers to dynamically added elements using jquery's delegate.

A: Using jQuery's .live() you can bind event handlers onto objects and the events will be triggered even if new objects are added via AJAX.
http://api.jquery.com/live/
A simple example would be:
$('#foo').live('click', function() {
    // this will be called even if #foo is added minutes after the initial page load!
});


text:
Q: BootstrapVue's b-nav with lazy loading I can't wrap my head around the following problem:
I have a Vue.js component in which I need tabs with routes. I went for a variant of b-nav Tabs style (official docs) and it is working fine, regarding the tabs and routing.
The problem: I can't figure out how to lazy load the tab-content of each item in myItems instead of loading them all on requesting one of the tab routes.
The routes look like this: localhost/items/#tab0, localhost/elements/#tab1 etc.
(Btw: b-tabs have built in lazy loading, but are not routable! Can't use them :-/)
This is the code of my component's template:
<template>

                {{ item.name }}

</template>

And this my TypeScript code:

EDIT:
Of, let's say 7 tabs, I need to lazy load only 2, the other's immeditately.
Anybody got an idea? Thanks in advance :-)

A: I see two options here:
First, you can use b-tab and implement routing for them, using query params may help you. you need to use @change every time one tab changes.
Second, you can implement a component for showing your output:
<MyCustomComponent v-for="(item, index) in myItems" :key="item.id" :is="selected_component_name " />

check the vue documentation for more explanation.

A: I solved it like this:
I created a component for the tab content:
Template:

  <TabContent
    v-for="(item, index) in myItems"
    class="tab-pane"
    :class="{ active: $route.hash === '#tab' + item.Id || (index === 0 && $route.hash === '') }"
    :key="item.Id"
    :tab-content="item"
  />

In the new TabContent component, I check:
Template:
<template>

        <TabContent1
            :v-if="$route.hash === "#tab" + item.Id && item.name === 'tabName1'"
        />

        <TabContent2
            :v-if="$route.hash === "#tab" + item.Id && item.name === 'tabName2'"
        />

        <TabContentDefault v-else />

</template>

This is simplified code, of course. In reality I use functions for the checks and way more properties.


text:
Q: run a single program on raspberry pi 3 with no user interface The goal is to interface with and control two pieces of equipment (receiving and logging data). I don't need the gui...or likely much of anything that could cause the system to crash. There is no chance that a human can interact with the system once it goes to where it is going.
The system will be turned on and automatically run...is this possible...and do I even need a full OS for this to happen?

A: Of course this is possible, just google for "raspberry pi headless". There is a similar question here: raspberrypi.stackexchange.com


text:
Q: Find all records in a table where the most recent record in a join table has a column which is not equal to one is this table? Image the tables:
CREATE TABLE items (
  id INT,
  price INT
);

CREATE TABLE item_price_history (
  id INT,
  item_id INT,
  price INT
);

With the following data:
INSERT INTO items (id, price) VALUES (1, 199);
INSERT INTO items (id, price) VALUES (2, 159);
INSERT INTO items (id, price) VALUES (3, 129);
INSERT INTO items (id, price) VALUES (4, 119);

INSERT INTO item_price_history (id, item_id, price) VALUES (1, 1, 249);
INSERT INTO item_price_history (id, item_id, price) VALUES (2, 1, 239);
INSERT INTO item_price_history (id, item_id, price) VALUES (3, 1, 229);
INSERT INTO item_price_history (id, item_id, price) VALUES (4, 1, 199);
INSERT INTO item_price_history (id, item_id, price) VALUES (5, 2, 299);
INSERT INTO item_price_history (id, item_id, price) VALUES (6, 2, 259);
INSERT INTO item_price_history (id, item_id, price) VALUES (7, 2, 159);
INSERT INTO item_price_history (id, item_id, price) VALUES (8, 2, 109);
INSERT INTO item_price_history (id, item_id, price) VALUES (9, 3, 129);
INSERT INTO item_price_history (id, item_id, price) VALUES (10, 4, 159);
INSERT INTO item_price_history (id, item_id, price) VALUES (11, 4, 119);
INSERT INTO item_price_history (id, item_id, price) VALUES (13, 4, 99);

Now I would like to find all the items for which the items.price is not equal to the most recent item_price_history.price (id DESC) in item_price_history. In this case that should produce item with id 3 and 4. As their prices does NOT match the most recent price in item_price_history.
I did the following which works:
SELECT items.id, items.price i_price, item_price_history.id, item_price_history.price as ih_price
    FROM items
    LEFT JOIN item_price_history ON item_price_history.item_id = items.id
        AND item_price_history.id = (SELECT MAX(id) FROM item_price_history WHERE item_id = items.id)
    WHERE items.price != item_price_history.price
    LIMIT 100

However I have a table of about 2 million rows in items and 20 million rows in item_price_history which I need to scan through, so performance is important.
How would I write such a query in a more performant way e.g by using DISTINCT ON or something?
https://www.db-fiddle.com/f/wPkdHvvzS2tmZq2vKUwgNi/2

A: Here is a query to do it in bulk with DISTINCT ON:
SELECT items.id, items.price i_price, item_price_history.id, item_price_history.price as ih_price
  from items
  join (select distinct on (item_id) id, item_id, price from item_price_history order by item_id desc, id desc) item_price_history
on item_price_history.item_id = items.id
WHERE items.price != item_price_history.price;

It should be well supported by an index on item_price_history (item_id , id, price); which will let it do a presorted index-only scan.


text:
Q: Python; SciKit Learn; SVM; Shape Mismatch I have time series of 40,000 assets. i've split the data into training and target data. The training data has 119 days of returns and the target data has 59 days. I split it up this way on purpose.
Train: (119 rows of returns, 40000 different series)
Target:  (59 rows of returns, same 40000 series)
I ran the following code to FIT the model:
SVR_model = svm.SVR(kernel='rbf',C=100,gamma=.001).fit(t_train_scale.transpose(), t_test.transpose())
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-185-2a0fd827e2a4> in <module>()
      1
      2
----> 3 SVR_model = svm.SVR(kernel='rbf',C=100,gamma=.001).fit(t_train_scale.transpose(), t_test.transpose())

C:\Users\nnayyar\Anaconda\lib\site-packages\sklearn\svm\base.pyc in fit(self, X, y, sample_weight)
    174
    175         seed = rnd.randint(np.iinfo('i').max)
--> 176         fit(X, y, sample_weight, solver_type, kernel, random_seed=seed)
    177         # see comment on the other call to np.iinfo in this file
    178

C:\Users\nnayyar\Anaconda\lib\site-packages\sklearn\svm\base.pyc in _dense_fit(self, X, y, sample_weight, solver_type, kernel, random_seed)
    229                 cache_size=self.cache_size, coef0=self.coef0,
    230                 gamma=self._gamma, epsilon=self.epsilon,
--> 231                 max_iter=self.max_iter, random_seed=random_seed)
    232
    233         self._warn_from_fit_status()

C:\Users\nnayyar\Anaconda\lib\site-packages\sklearn\svm\libsvm.pyd in sklearn.svm.libsvm.fit (sklearn\svm\libsvm.c:1864)()

ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

From research I see the most common answer using SVM is that the shapes have to 'match up' but how do I fit the SVM with data of various size?
Edit: Still need some help with this, how do I forecast thousands of predictions, not just the next 1?

A: The problem is with your second parameter in the fit call.
As per documentation, the second parameter needs to be an array of n samples, where n is the number of instances, equal to the number of rows of the matrix that you pass as the first parameter (X).

fit(X, y, sample_weight=None)
X : {array-like, sparse matrix}, shape (n_samples, n_features)
y :
  array-like, shape (n_samples,)

So, if your first parameter has a size of 40.000 x 119 (since you transposed it), the second parameter needs to be an array of size 40.000 x 1.
But, judging by the error it is possible that your second parameter has more than 1 column (i.e. 2 columns).


text:
Q: Embed editable Google Docs spreadsheet without footer sheet toolbar I am sharing an editable Google sheet on my website (shared with any user on Google sheet side), using https://docs.google.com/spreadsheets/d/[hash]/edit?rm=minimal
Adding the rm=minimal allows to remove the Google navigation and toolbar at the top.
Is there a way to remove the bottom bar allowing to add new sheets?

A: No.
A document may be shared as editable, or shared as not editable, or not shared at all.
There is not fine grained control over prohibiting the addition/deletion of individual sheets in the document.
That's why there's no URI argument to hide the UI elements relating to this feature — the feature is one of the things you're explicitly granting access to, by making the share editable.


text:
Q: How do I add Blob to Typescript? I am attempting to save a file with FileSaver, which consequentially needs a Blob format. My app is being written in typescript.
When I tried to do
import * as Blob from "blob";

I received the error
Could not find a declaration file for module 'blob'. '/Users/path/to/project/node_modules/blob/index.js' implicitly has an 'any' type.

Try \npm install @types/blob` if it exists or add a new declaration (.d.ts) file containing `declare module 'blob';``

I cannot just import 'blob' because a @types/blob package does not exist.
I created a declaration file blob.d.ts with these contents
declare module 'blob' {
  function Blob(blobParts[, options]): any
  export = Blob
}

based on the MDN entry on the Blob constructor
This did not solve my issue for the one line of code I need Blob for
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});

it returned the error below
Argument of type '{ type: string; }' is not assignable to parameter of type '[any, any]'. Object literal may only specify known properties, and 'type' does not exist in type '[any, any]'.

This similar question is NOT a duplicate and its answer does not help me since that declaration file does not declare a module and does not export anything.

A: In your tsconfig.json, make sure to include webworker in your lib array:
{
  "compilerOptions": {
    ...
    "lib": ["webworker"],
    ...
  },
  ...
}

Even though it should have already been obvious from the reference links provided above, lib.webworker.d.ts contains the declarations necessary for Blob and related interfaces.
interface Blob {
    readonly size: number;
    readonly type: string;
    slice(start?: number, end?: number, contentType?: string): Blob;
}

declare var Blob: {
    prototype: Blob;
    new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
};


text:
Q: Non linear ODE Problems I encountered with this problem very recently  here it is
$\frac{dx}{dt}=-x$
$\frac{dy}{dt}=2x^2 y^2$
Find the critical points
find the different equation of paths
solve equation ti find the paths
I really dont know how to solve this equations, if it is linear format i can work out easily .

A: The first equation is linear, yielding $x(t)=x_0e^{-t}$.
You can put this into the second equation, giving
$$\frac{dy}{dt}=2x_0^2e^{-2t}y^2$$
which is separable.  Can you take it from there?

A: afther solved we have:
$$y(t)=\frac1{x_0^2 e^{-2t} +y_0 }$$


text:
Q: htaccess https off only for specified routes I want to force https://www.domain.com on my domain excluding some routes.
301 Redirections:

*

*domain.com => https://www.domain.com (not working)

*www.domain.com => https://www.domain.com (not working)

*http://www.domain.com => https://www.domain.com (not working)

Excludes:

*

*http://www.domain.com/init => http://www.domain.com/init

*http://www.domain.com/posts => http://www.comain.com/posts

*...

What I have done so far:
DirectoryIndex index.php
RewriteEngine on
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} ^(init|posts) [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

RewriteCond $1 !^(index\.php|robots\.txt|website|favicon\.ico|style\.css|sitemap.xml)
RewriteRule ^(.*)$ ./index.php?/$1 [L]

A: Its funny I am searching a day for a solution and just found that my excluding routes first get resolved to http://www.domain.com/index.php/init and don't match my condition so by adding the same rule to QUERY_STRING now works as expected:
DirectoryIndex index.php
RewriteEngine on
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !(init|posts) [NC]
RewriteCond %{QUERY_STRING} !(init|posts) [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

RewriteCond $1 !^(index\.php|robots\.txt|website|favicon\.ico|style\.css|sitemap.xml)
RewriteRule ^(.*)$ ./index.php?/$1 [L]


text:
Q: PyCharm can't seem to be able to import modules (random, webdriver) I recently installed MacOS BigSur, and updated to the latest version of PyCharm, but I think it totally broke it.
Indeed, I mostly use Selenium, and I had trouble installing the package, but I managed to do it via the mac terminal, using this command:
/Users/inakivignal/PycharmProjects/NikeFP/venv/bin/python -m pip install selenium
After that, it shows me errors from importing webdriver and even importing random. I don't know what else to do, because before it imported them directly from packages. I verified and selenium is indeed installed as an interpreter in this project.
I'll attach what it shows me when i put this code:
code
I really don't know what is wrong with my PyCharm, if any of you could help me I would really appreciate it.
Thanks

A: If you are sure that it is installed, you could right click on the error, then take the option "install package Selenium" looking like this: https://gyazo.com/2f7ed596192c772d164652e2a5fdbc0b
not sure if this helps but worth a try, also had problems with this


text:
Q: Application of Options for Graphics I have the code
Graphics[{Dashed, Green, Circle[{0, 0}, .4], Black,
  Circle[{0, 0}, .5], FaceForm[], EdgeForm[Black],
  Rectangle[{-1, -1}, {1, 1}]}]

Which gives the output

However, I do not want the outer circle to be dashed. The documentation example suggests that the options are only applied to the first object after those options. So why is Dashed[] being applied to the outer circle?

A: The documentation says:

Nested lists of graphics constructs can be given. Directive specifications such as GrayLevel remain in effect only until the end of the list that contains them.

So, include Dashed and the first circle in a nested list:
Graphics[{Green, {Dashed, Circle[{0, 0}, .4]}, Black, Circle[{0, 0}, .5],
FaceForm[], EdgeForm[Black], Rectangle[{-1, -1}, {1, 1}]}]


text:
Q: Mark as Obsolete I am trying to find all the unused methods of my project. I have search ways of doing this, but the most convincing answer I found was to declare all my functions as obsolete, and remove this attribute until I got no warnings.
The problem is that I don't know how to declare a function as obsolete. When I write:
   [Obsolete]
   class Vector3{

   };

VS2005 tells me that Obsolete does not exist.
Any suggestions?

A: In gcc you use __attribute__ ((deprecated)) to tag functions as deprecated.
It looks like __declspec(deprecated) may do the trick in VS. You'll also have to enable warning level 1 for it to result in a diagnostic.
See http://msdn.microsoft.com/en-us/library/044swk7y%28VS.80%29.aspx

A: I don't know the rest of your source code, but you should have a
using System;

at the top.


text:
Q: Devise/CanCan - Restricted Content Building a rails B2B application that will have various users. I'm pretty clear on restricting access for internal staff using Devise and CanCan but I want to be able to give suppliers and customers their own login as well. Customer will be fairly simple, however, I want to ensure the supplier (label) login enables them to view and amend their own product and sales data only.
The model is roughly:
User (as setup by Devise)
Label [has_many releases]
Release [belongs_to label / has_many products]
Product [belongs_release / has_many tracks]
Track [belongs_product]

I'm guessing I could add in a label_id field on the user model and associate that way but I need internal users (and customers) to have access to view all label data. I also need to allow a label to have many users.
Would it simply be a case of defining a 'label' role via Cancan that enforces the use of a label_id in the the views? If that's the correct approach how do I then lock down the content to that label_id in my controllers/views? Role based if statements?
Thanks in advance!

A: What you'd first have to do is define some CanCan roles, like supplier, customer and staff, and then create an interstitial controller to handle the forking:
class CheckingController < ApplicationController
  def index
    @path = case user.role
      when 'supplier'
        supplier_path
      when 'customer'
        customer_path
      when 'staff'
        staff_path
      else
        admin_sign_in_path #or whatever
    end

    redirect_to @path
  end
end

Then in your routes.rb file you can send users to either the root or index action of your controller by first sending them to CheckingController#index which will redirect based on your CanCan roles.


text:
Q: integrate asp.net services without api or web service call how do I send a request to a page that doesn't offer an API or web serviece like this one for example
http://arcgis.dmgov.org/extmapcenter/addresslookup.aspx
from inside my asp.net webapplication.
The problem is, how will I pass the information in my request. in the case above for example, I need to pass the address.

A: Each browser has a set of developer tools for monitoring HTTP requests. In Chrome you can hit ctrl+shift j, go to Network, and examine the HTTP request used when you hit the submit button on that page. Most often sending data to the server will use an HTTP POST which that site does. What is important is to see the variables they use to send the POST data. That site sends the following
ctl00$CPH4contentWindow$txtAddress:111 Street Name

With a content-type of application/x-www-form-urlencoded
You can try to mimic this by sending your own HTTP request with that information.
Client
$.ajax({
    url: '/api/Address/111%20Street%20Name',
    dataType: 'html',
    success: function (result) {
        // do something with result
    }
});

Controller
public class AddressController : ApiController
{
    public string Get(string address)
    {
        WebClient client = new WebClient();
        client.AddHeader("content-type", "application/www-form-urlencoded");
        string response = client.UploadString("http://arcgis.dmgov.org/extmapcenter/addresslookup.aspx", "ctl00$CPH4contentWindow$txtAddress=" + Uri.EscapeDataString(address));
        return response;
    }
}

If you don't need it to be sent asynchronously with ajax you can just put the logic for the Controller into your ASP.NET code behind.

A: You can use web browser addons like firebug for firefox to see what requests that page is making. For your sample case it is making a request to
http://arcgis.dmgov.org/extmapcenter/AutoComplete.asmx/GetLocAddressList
with
prefixText to "textInsindeTextbox"
make this request from your application. But that webservice may not allow you do that.

A: Issue a HTTP GET request: http://support.microsoft.com/kb/307023
or use IFRAME HTML tag if you want it on the client side.


text:
Q: ANSI C and sqlite3_get_table: How to pass results array back to calling function? I'm trying to pass the results array generated by sqlite3_get_table contained
in a function called by another function.  Everything is working fine except I
can't get the array back into the main function. What exactly do I replace the
char **sql_results with? Here's the code:
int main()
{
    char **sql_results = 0; // help here

    sql_select_table("GetAirports", query_string, AIRPORTS_DATABASE,
             sql_results, &RecordCount,
             &ColumnCount);

    for (int i = 0; i < ColumnCount; i++)
        printf("%s\n", sql_results[i]); // Generates "EXC_BAD_ACCESS"

}

void sql_select_table(const char *query_name, const char *sql_query,
              const char *sql_database,
              char **sql_results, int *RecordCount,
              int *ColumnCount)
{
    sqlite3_get_table(open_database, sql_query,
                 &sql_results, RecordCount,
                 ColumnCount, &error_msg);

}

A: You're trying to take the address of one of the sql_select_table arguments and that doesn't do what you think it does; &sql_results is just the address of a local variable, it won't let you modify the sql_results in main().
Instead, pass a char*** into sql_select_table like this:
/* Note that sql_results is now a char*** */
void sql_select_table(const char *query_name, const char *sql_query,
              const char *sql_database,
              char ***sql_results, int *RecordCount,
              int *ColumnCount)
{
    sqlite3_get_table(open_database, sql_query,
                 sql_results, RecordCount,
                 ColumnCount, &error_msg);

}

int main()
{
    char **sql_results = 0;

    /* Note the & on sql_results */
    sql_select_table("GetAirports", query_string, AIRPORTS_DATABASE,
             &sql_results, &RecordCount,
             &ColumnCount);

    for (int i = 0; i < ColumnCount; i++)
        printf("%s\n", sql_results[i]); // Generates "EXC_BAD_ACCESS"

}

Also, sqlite3_get_table is deprecated:

This is a legacy interface that is preserved for backwards compatibility. Use of this interface is not recommended.

So you might want to start using sqlite3_exec instead.


text:
Q: Java Script вывести количество элементов в списке Пытаюсь написать свое первое приложение. Не пойму, как посчитать динамически количество всех элементов в списке задач. Чтобы при удалении задачи счетчик уменьшался и наоборот увеличивался при добавлении задачи. Пробовал циклом, но не выходит.

'use strict';
const input = document.querySelector('#input-main');
const ul = document.querySelector('.list');
let li = document.querySelectorAll('.list li');
let tasks = [];

input.addEventListener('keypress', function (event) {
  if (input.value === '') {
    document.querySelector('#input-main').placeholder = 'Введите задачу...';
  } else {
    if (event.key === 'Enter') {
      newTask();
    }
  }
});

let newTask = () => {
  if (input.value !== '') {
    let task = document.createElement('li'),
      link = document.createElement('a'),
      newTask = input.value;
    task.innerHTML = newTask;
    link.appendChild(task);
    ul.appendChild(link);
    input.value = '';

    //Кнопка удалить
    let span = document.createElement('SPAN'),
      spanText = document.createTextNode('\u00D7');
    span.className = 'close';
    span.appendChild(spanText);
    link.appendChild(span);

    let filter = document.querySelector('.filter-list');
    filter.style.display = 'flex';

    //Чекбоксы
    let checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = 'checkbox-id';
    link.appendChild(checkbox);
    ul.appendChild(link);
    //Всего задач
    let allTask = document.querySelector('.all-count'),
      list = document.querySelectorAll('.list > a');
    tasks.push(list);
    let count = tasks.length;
    allTask.textContent = `Всего задач: ${[count]}`;

    //Функция удаления задачи
    span.addEventListener('click', function (event) {
      if (event.target.tagName === 'SPAN') {
        let close = event.target.parentNode;
        close.remove();
      }
    });
  }
};
body,
ul {
  margin: 0;
  padding: 0;
}

.todo {
  margin: 0 auto;
  max-width: 600px;
  margin-top: 80px;
}

.app {
  text-align: center;
  position: relative;
  display: flex;
  flex-direction: column;
}
header h1 {
  font-size: 50px;
  color: green;
  opacity: 0.5;
  font-weight: 600;
  margin-bottom: 30px;
  font-family: sans-serif;
}

input {
  width: 100%;
  padding: 15px;
  outline: none;
}

input.new-todo {
  font-size: 20px;
  padding: 14px 14px 14px 42px;
}

.list.editing #text {
  display: none;
}

.list.editing .new-todo {
  display: block;
}

ul.list {
  display: block;
}

.list {
  font-size: 26px;
  display: none;
}

.list li {
  padding: 14px;
  border: 1px solid #ccc;
  border-top: none;
  color: green;
}

.list li:hover {
  background-color: rgba(217, 245, 236, 0.973);
}

ul li.checked {
  background: rgb(158, 123, 123);
  color: #fff;
  text-decoration: line-through;
}

.close {
  position: relative;
  top: -43px;
  right: 15px;
  float: right;
  color: red;
  cursor: pointer;
  display: block;
  width: 20px;
  visibility: hidden;
}

ul#list-id.list a:hover span.close {
  visibility: visible;
}

.edit {
  float: right;
  position: relative;
  right: 75px;
  top: 6px;
  visibility: hidden;
  size: 10px;
  cursor: pointer;
  color: rgba(153, 102, 8, 0.584);
  display: block;
  font-size: 17px;
  text-align: center;
}

.list a .close:hover {
  visibility: visible;
}

#checkbox-id {
  float: left;
  width: 30px;
  margin: 7px;
  position: relative;
  top: -42px;
  font-size: 17px;
}

.checked {
  text-decoration: line-through;
  background-color: indianred;
}

#count {
  float: left;
  color: #969595;
}

a {
  text-decoration: none;
}

li {
  list-style-type: none;
}

ul.filter-list {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  margin-top: 5px;
  display: none;
}
.all-count {
  float: left;
  position: relative;
  left: -119px;
  color: #969595;
}
.filter-list li {
  padding: 5px;
  margin: 5px;
}

.filter-list a {
  color: #969595;
}

.arrow img {
  width: 3%;
  float: left;
  display: block;
  position: relative;
  top: 39px;
  left: 10px;
}

.arrow {
  position: relative;
  top: 36px;
  z-index: 1;
  left: 14px;
  cursor: pointer;
}

TODO LIST

        <input
          id="input-main"
          type="text"
          class="new-todo"
          autofocus=""
          placeholder="Есть важные дела?"
        />

Все

Активные

Завершенные

A:

'use strict';
const input = document.querySelector('#input-main');
const ul = document.querySelector('.list');
let li = document.querySelectorAll('.list li');
let tasks = [];

input.addEventListener('keypress', function (event) {
  if (input.value === '') {
    document.querySelector('#input-main').placeholder = 'Введите задачу...';
  } else {
    if (event.key === 'Enter') {
      newTask();
    }
  }
});

let newTask = () => {
  if (input.value !== '') {
    let task = document.createElement('li'),
      link = document.createElement('a'),
      newTask = input.value;
    task.innerHTML = newTask;
    link.appendChild(task);
    ul.appendChild(link);
    input.value = '';

    //Кнопка удалить
    let span = document.createElement('SPAN'),
      spanText = document.createTextNode('\u00D7');
    span.className = 'close';
    span.appendChild(spanText);
    link.appendChild(span);

    let filter = document.querySelector('.filter-list');
    filter.style.display = 'flex';

    //Чекбоксы
    let checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = 'checkbox-id';
    link.appendChild(checkbox);
    ul.appendChild(link);
    //Всего задач
    let allTask = document.querySelector('.all-count'),
      list = document.querySelectorAll('.list > a');
    tasks.push(list);

    // -------------- Дописано:
    updateCount();

    //Функция удаления задачи
    span.addEventListener('click', function (event) {
      if (event.target.tagName === 'SPAN') {
        let close = event.target.parentNode;
        close.remove();

        // -------------- Дописано:
        tasks.splice( tasks.indexOf(list), 1 );
        updateCount();
      }
    });
  }
};

// -------------- Дописано:
function updateCount(){
    let allTask = document.querySelector('.all-count');
    let count = tasks.length;
    allTask.textContent = `Всего задач: ${[count]}`;
}
body,
ul {
  margin: 0;
  padding: 0;
}

.todo {
  margin: 0 auto;
  max-width: 600px;
  margin-top: 80px;
}

.app {
  text-align: center;
  position: relative;
  display: flex;
  flex-direction: column;
}
header h1 {
  font-size: 50px;
  color: green;
  opacity: 0.5;
  font-weight: 600;
  margin-bottom: 30px;
  font-family: sans-serif;
}

input {
  width: 100%;
  padding: 15px;
  outline: none;
}

input.new-todo {
  font-size: 20px;
  padding: 14px 14px 14px 42px;
}

.list.editing #text {
  display: none;
}

.list.editing .new-todo {
  display: block;
}

ul.list {
  display: block;
}

.list {
  font-size: 26px;
  display: none;
}

.list li {
  padding: 14px;
  border: 1px solid #ccc;
  border-top: none;
  color: green;
}

.list li:hover {
  background-color: rgba(217, 245, 236, 0.973);
}

ul li.checked {
  background: rgb(158, 123, 123);
  color: #fff;
  text-decoration: line-through;
}

.close {
  position: relative;
  top: -43px;
  right: 15px;
  float: right;
  color: red;
  cursor: pointer;
  display: block;
  width: 20px;
  visibility: hidden;
}

ul#list-id.list a:hover span.close {
  visibility: visible;
}

.edit {
  float: right;
  position: relative;
  right: 75px;
  top: 6px;
  visibility: hidden;
  size: 10px;
  cursor: pointer;
  color: rgba(153, 102, 8, 0.584);
  display: block;
  font-size: 17px;
  text-align: center;
}

.list a .close:hover {
  visibility: visible;
}

#checkbox-id {
  float: left;
  width: 30px;
  margin: 7px;
  position: relative;
  top: -42px;
  font-size: 17px;
}

.checked {
  text-decoration: line-through;
  background-color: indianred;
}

#count {
  float: left;
  color: #969595;
}

a {
  text-decoration: none;
}

li {
  list-style-type: none;
}

ul.filter-list {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  margin-top: 5px;
  display: none;
}
.all-count {
  float: left;
  position: relative;
  left: -119px;
  color: #969595;
}
.filter-list li {
  padding: 5px;
  margin: 5px;
}

.filter-list a {
  color: #969595;
}

.arrow img {
  width: 3%;
  float: left;
  display: block;
  position: relative;
  top: 39px;
  left: 10px;
}

.arrow {
  position: relative;
  top: 36px;
  z-index: 1;
  left: 14px;
  cursor: pointer;
}

TODO LIST

        <input
          id="input-main"
          type="text"
          class="new-todo"
          autofocus=""
          placeholder="Есть важные дела?"
        />

Все

Активные

Завершенные


text:
Q: Updating issues I am trying to update some data on one APPlication  and sending the JMS Event to the different JBOSS server.
The listener will get the event and try to read the data using a  database view with dblink.
Initially this view has no data for that ID .I update the data using other Application and after comitting the JMS Event is sent  with that id. Once the listener received this id it will fetch the data using the database view.
My issue is that while reading with JPA/HIBERNATE it is still reading the old data which is comming as blank.
The service layer to call the dao layer is using the following transcation
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)

    The DAO Layer is using
    @PersistenceContext
    private EntityManager em;

    Query query = em.createNativeQuery(sbQuery.toString());

I tried with all the following option and it doesnt seems to be work.
    em.clear();
    em.getEntityManagerFactory().getCache().evictAll();
    em.flush();
    query.setHint("javax.persistence.cache.storeMode", CacheStoreMode.BYPASS);

Note: The only way it works is  that  after i received the event if I do a staright jdbc i can fetch the data from that view but with spring/hibernate configuration its comming as blank.
Any thought why it's not working on the normal behaviour and why do I need to do a staright jdbc to the call?

A: This looks like a standard scenario where the message is received before the transaction of the sender is committed. For it to work, you need to send the message after the transaction is committed. With spring you can do that via a TransactionSynchornization:
TransactionSynchronizationManager.registerSynchronization(new
         MessageQueueTransactionSynchronization(jmsSender, message));

where MessageQueueTransactionSynchronization implements TransactionSynchronization and sends the message when afterCompletion(..) is triggered with status = TransactionSynchronization.STATUS_COMMITTED


text:
Q: RxJS - switchMap not emitting value if the input observable is empty array I have the setup where I query firebase for list of user favourite posts.
Basically, at first I query for user likes and then for each like get the corresponding post - all in one observable sequence.
The problem arises when user dislikes the only left post. In that case (when the likes array becomes empty) nothing is fired from the observable and view is not updated (there is always at least one post present).
On the one hand, this behaviour seems logical and understandable, but on the other hand, I'm not sure how to make final Observable emit even if the input to the switchMap was empty. Maybe should change the operator.
getUserFavourites(userId = ""):Observable<Post[]>
{
  if (!this.userFavourites$) {
    this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
        query: {
          limitToFirst: 50
        }
      }) //Emits value here (even empty array)
      .switchMap((likes: any[]) => Observable.combineLatest(
        likes.map(like => this.af.database.object("/posts/" + like.$key).first())
      )) //Does not emit new value here if likes array was empty
      .map(p => {
        return p.map(cit => Post.unpack(p));
      }).publishReplay(1).refCount()
  }
  return this.userFavourites$;
}

A: Solved the problem by adding a condition inside switchMap:
Original - https://github.com/ReactiveX/rxjs/issues/1910
getUserFavourites(userId = ""):Observable<Post[]>
{
  if (!this.userFavourites$) {
    this.userFavourites$ = this.af.database.list('/ranks_by_user/' + userId, {
        query: {
          limitToFirst: 50
        }
      }) //Emits value here (even empty array)
      .switchMap((likes: any[]) => {
      return likes.length === 0 ?
        Observable.of(likes) :
        Observable.combineLatest(
          likes.map(like => this.af.database.object("/citations/" + like.$key))
      )
    }) //Emits either combined observables array or empty array
      .map(p => {
        return p.map(cit => Post.unpack(p));
      }).publishReplay(1).refCount()
  }
  return this.userFavourites$;
}

A: .switchMap((likes) => likes.length > 0 ?
   Observable.combineLatest(
    likes.map(like => this.af.database.object("/posts/" + like.$key).first():
   Observable.empty() // if emit empty() then .map() will not run
 )
 .map(...)


text:
Q: How to flash non Debian system to BeagleBoardBlack from microSD? I built a Linux system with Buildroot for my BeagleBoneBlack.
It boots well from the microSD.
How can I copy the whole microSD content (boot and rootfs) to the eMMC?

A: You should be able to just dd to the eMMC (usually appearing as /dev/mmcblk0 when booted from SD).
It might make more sense to adapt the eMMC flashing script used by the Debian images though.

A: you can see here link. a article guide how to create a sdcard boot kernel linux!!


text:
Q: Get no of attempts in quartz Can any one please tell me how can I get current attempt count in quartz.
Example :  if Quartz scheduler is started with repeat count of 5. I want to get the current repeat count.
Here is the Example I am trying with
 public class SimpleTriggerExample  implements Job
 {
  int count = 0;
 JobDetail job = null;
 JobDataMap data = null;

public static void main( String[] args ) throws Exception
{
     new SimpleTriggerExample().schedule();

}
public void schedule() throws ParseException, SchedulerException{
     job = JobBuilder.newJob(SimpleTriggerExample.class)
            .withIdentity("dummyJobName", "group1").build();
        Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("dummyTriggerName", "group1")
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
            .withIntervalInSeconds(10).withRepeatCount(3))

            .build();
        System.out.println("before in main jobdatamap");

        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);
}
public void execute(JobExecutionContext context)
        throws JobExecutionException {

            //count
     data = context.getJobDetail().getJobDataMap();
    System.out.println("after jobdatamap");

            int count1 = data.getInt("EXECUTION_COUNT");
            System.out.println("count1-->before"+count1);
            count1++;
            System.out.println("count1-->after"+count1);

            job.getJobDataMap().put("EXECUTION_COUNT", count1);

            count = count1;

            System.out.println("count"+count);

        }
}

A: Use JobDataMap along with @PersistJobDataAfterExecution annotation.
Make sure when you modify data in JobDataMap the key value should be same.
If you do like this you can persist your attempts as per your requirement.
Example Code Snippet:
package com.mss.quartz.demo;

 import java.text.SimpleDateFormat;
 import java.util.Date;

 import org.quartz.InterruptableJob;
 import org.quartz.Job;
  import org.quartz.JobBuilder;
 import org.quartz.JobDataMap;
 import org.quartz.JobDetail;
 import org.quartz.JobExecutionContext;
 import org.quartz.JobExecutionException;
 import org.quartz.JobKey;
 import org.quartz.PersistJobDataAfterExecution;
 import org.quartz.Scheduler;
 import org.quartz.SchedulerContext;
 import org.quartz.SchedulerException;
 import org.quartz.SimpleScheduleBuilder;
 import org.quartz.TriggerBuilder;
 import org.quartz.UnableToInterruptJobException;
 import org.quartz.impl.StdSchedulerFactory;
 @PersistJobDataAfterExecution
 public class HelloJob implements InterruptableJob
 {
SchedulerContext schedulerContext  = null;
testQuartz test = new testQuartz();

boolean result;
private boolean _interrupted = false;
private JobKey _jobKey = null;
Thread t = null;
//public static int count = 0;

public void interrupt() throws UnableToInterruptJobException {
    System.out.println("---" + this._jobKey + "  -- INTERRUPTING --");
    this._interrupted = true;
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
    Scheduler scd = context.getScheduler();

    JobDataMap dataMap = context.getJobDetail().getJobDataMap();

    String jobSays = dataMap.getString("test1");

    int myFloatValue = dataMap.getIntValue("id");

    System.out.println("In Job Class"+jobSays+ "  "+myFloatValue+"   Current time in

   Job class  "+new Date().toString());
    JobKey jobKey = context.getJobDetail().getKey();
    int attemps = dataMap.getInt("attempts");
    attemps++;
    dataMap.put("attempts", attemps);
    System.out.println("After putting count in job data map:"+dataMap.get("attempts"));

}

}

A: Try to add the @PersistJobDataAfterExecution annotation to SimpleTriggerExample class:
@PersistJobDataAfterExecution
 public class SimpleTriggerExample  implements Job
 { ...}


text:
Q: Homework: Conjunctive Normal Form
The way I understand CNF is as an expression containing AND's of OR's. So an AND-GATE with 3 inputs (A, B and C) should just be A AND B AND C. But apparently this is incorrect. Any guidance would be greatly appreciated, thank you.

A: The CNF has one term for each set of values of the inputs $A$ and $B$ for which
the output $C$ has value $0$.  Since $C = 0$ whenever at least one of $A$ and $B$
have value $0$, we have that
$$C = ({A} \vee {B})\wedge ({A} \vee \bar{B})\wedge (\bar{A} \vee {B}).$$
The first term on the right has value $0$ when $A = B = 0$, the second
when $A = 0, B = 1$, and the third when $A = 1, B = 0$. Thus, in all these cases,
one of the terms "being ANDed together" has value $0$ and hence the AND gives $0$.
The only case when all three terms on the right have value $1$ is $A = B = 1$,
and thus $C$ equals $1$ exactly when $A=B=1$.


text:
Q: How many ways can I connect labeled trees into a tree. Suppose I have the labeled trees $T_{1}, \ldots, T_{n}$ with $b_{1}, \ldots, b_{n}$ vertices respectively. I would like to know how many ways I can compose a tree from these trees by using all trees? In this problem editorial they claim that there are $\prod_{i=1}^{n}{b_{i}} \cdot \left( \sum_{i = 1}^{n}{b_{i}} \right)^{n - 2}$ such compositions. I don't know how to prove this and there is no proof linked on the editorial either. Could someone help me with this?

A: The problem is listed in Lovasz's problem book. This is problem 4 in chapter 4. The original solution is attributed to J. W. Moon, but I haven't managed to find the article describing this. The proof is fairly complicated so it's not a surprise that it's omitted from the editorial.
EDIT: Seems like Igor Pak shared the original book as well, although the book by Lovasz is more accessible and the proof is complicated but well presented.


text:
Q: Find the determinant and possible sizes of a matrix $A$, which satisfies the equation $A^2 - 2A + 4E = 0$ Let $A \in M_n(\mathbb{R})$ satisfy the equation:
$$A^2 - 2A + 4I = 0$$
(a) What is $\det A$? (3 points)
(b) What are possible sizes of a matrix $A$? (6 points)
My solution
We can derive 2 useful equations from the given one:
1) $A^2 = -2(2I - A)\Rightarrow (\det A)^2 = \det (-2(2I - A)) = (-2)^n \cdot \det (2I - A)$
2) $A(2I - A) = 4E \Rightarrow \det A \cdot \det (2I - A) = 4^n = 2^{2n}$
From the first we see that the size $n$ must be even. This is the answer to the question (b).
Now, let's build the system of equations, where $x = \det A$, $y = \det (2I - A)$. Also, we can replace $(-2)^n$ with $2^n$, because we know, that $n$ is even:
$$\begin{cases} x^2 = 2^n \cdot y, \\ xy = 2^{2n} \end{cases} \Rightarrow \begin{cases} y = x^2\cdot2^{-n}, \\ x\cdot(x^2\cdot2^{-n}) = 2^{2n} \end{cases} \Rightarrow x = (2^{2n}\cdot2^n)^{1/3} = 2^n$$
So, $\det A = 2^n$ and it depends on the size of the matrix. This is the answer to the question (a).
The question
Is this solution correct? I have big doubts about it, because the question (b) is worth twice more points than (a), but happened to be much easier and also order of tasks suggests, that we should solve (a) first.

A: Using eigenvalues: Let $x$ be an eigenvector of $A$ associated with $\lambda$.  Note that
$$
0 = 0x = (A^2 - 2A + 4I)x = (\lambda^2 - 2\lambda + 4)x
$$
so, each $\lambda$ must be a root of $x^2 - 2x + 4$, which is to say that each eigenvalue is either $1 + \sqrt{3}i$ or $1 - \sqrt{3} i$.  Since $A$ is real, its eigenvalues come in conjugate pairs.  So, $n$ must be even, and the eigenvalues $1+\sqrt{3}i$ and $1 - \sqrt{3}i$ must have the equal multiplicities $n/2$.
The determinant of $A$ is the product of its eigenvalues, so
$$
\det(A) = [(1 + \sqrt{3}i)(1 - \sqrt{3} i)]^{n/2} = 4^{n/2} = 2^n
$$


text:
Q: Combining percentages differences I would like to know the difference between two approaches of combining percentages.
I found an online example that match my situation; the example have been found in The University of Georgia page. It states:
"The data on 4 examinations showed scores of 75 percent correct, 87 percent correct, 69 percent correct, and 93 percent correct. The overall grade was determined by taking the Arithmetic Mean (or 'average') of these scores, reporting a combined percentage of 81.
75 + 87 + 69 + 93 / 4 = 81

Consider that the 4 examinations had:
24 correct out 32 questions for 75 percent
87 correct out of 100 questions for 87 percent
38 correct out of 55 questions for 69 percent
and 93 correct out of 100 questions for 93 percent.
Thus if the questions are of equal merit across the examinations, there are 242 questions answered correctly out of 287 for a percentage of 84.3."
I have similar situation on my research, and there is a difference between the percentages. I would like to understand the difference between these two computation.

A: The difference is that the first average regards each test as having equal weight, while the second average regards each question as having equal weight.
If it really doesn't matter how many questions are on a test, then the first average is better.
If it really doesn't matter how the question pool is divided up into tests, then the second average is better.
Long story short, neither is more correct without additional context.


text:
Q: Storing and searching data pairs in Solr I'm trying to figure out how to store and search data pairs. I have a document similar to that below and my goal is to perform a search that returns all documents with a given specialty and then sort the results by the matching specialty ability:
<doc>
    <id>123</id>
    <firstName>Joe</firstName>
    <lastName>Bloggs</lastName>
    <specialties>
        <specialty>
            <type>Foo</type>
            <ability>1</ability>
        </specialty>
        <specialty>
            <type>Bar</type>
            <ability>2</ability>
        </specialty>
        <specialty>
            <type>Baz</type>
            <ability>2</ability>
        </specialty>
    </specialties>
</doc>

I'm familiar with working indexing, searching and faceting simple documents but I am struggling to even find a starting point with this =(
Should I simply use two collections and join?

A: If the number of specialties is finite and known beforehand, you may try following.
Instead of having two fields storing specialty and ability, just have ONE field containing "ability_of_a_specialty"
For example,
<specialties>
    <Foo_ability> 1 </Foo_ability>
    <Bar_ability> 2 </Bar_ability>
    <Dummy_ability> 0 </Dummy_ability>
    ...
</specialties>

Now, it should be straightforward to transform the above attributes to a Lucene doc.


text:
Q: FILTER has mismatched range sizes. Expected row count: 49430. column count: 1. Actual row count: 1, column count: 1 I've been working on a document based on google forms answers to calculate picture revisions.
This is the formula that I am trying to use: =SORTN(FILTER('Raw Data'!G:G,'Raw Data'!C:C=B1,'Raw Data'!E:E,"No"),20,0)
What I am trying to accomplish, is to pull 20 pictures per day of "bad parking". So I use 2 filters: bad parking and reviewed date. Yet it gives me an error saying there is a missmatch. I have reviewed the size and the reference is the full row. I have tried numbering the range (like G1:G99999) but nothing works. I am under the impression that the error is misleading me, I had the same issue in the array I am using to importrange the responses and I solved it by cutting the range into 3 pieces.
Here is the link to the spreadsheet I am working on: https://docs.google.com/spreadsheets/d/1fc3RbMwPCI2Txcy67WfqoPLDGPrUFF0JYuTMKEnXDFI/edit#gid=1067703029

A: change
,"No"

to
="No"

=SORTN(FILTER('Raw Data'!G:G,'Raw Data'!C:C=B1,'Raw Data'!E:E="No"),20,0)


text:
Q: How to cope with missing data in logistic regression? I'm investigating optimal bidding in auctions, and am using logistic regression to predict the probability of winning an auction given a set of explanatory variables (e.g. the price I bid, number of competing bids etc).
One explanatory variable I want to use is the second highest price that was paid. However, by the design of the auction, I only observe the second highest price paid when I am the highest bidder (i.e. when I win the auction).
This missing data is a major issue as my dataset indicates that there is a winning bid only ~20% of the time, hence I don't know the second highest price paid 80% of the time. Yet intuitively, I don't want to drop this variable as it seems to me knowledge of the second highest bid is extremely valuable in determining my chances of being the winning bid.
Thus are there any standard methods to cope with this kind of missing data for logistic regression?

A: I am afraid you cannot expect to find some "canned" solution to your problem.  Most methods for handling missing data assumes "missing at random" or even "missing completely at random" (you can google those terms!).  Your problem seems definitely to be a problem of informative missingness.   Then you will need to model the mechanism of missingness,  and maybe model the "second highest bid" as a response, given some covariables (which might include the winning bid).
From there you can try to build a custom model.  You can google for "informative missingness" to get some ideas.

A: @Kjetil gave a good answer.
One possible simple alternative, if you have enough auctions, is to run two models: One with the data that has both highest and second highest and one that has just the highest.
An advantage of this approach would be that each model will be considerably simpler than a full model with both. But a disadvantage is that you won't be able to use the 2nd highest bid at all unless you actually have it.


text:
Q: C code, What is the meaning? I have this C code. Please somebody can explain this code?.
char szTemp[100];
unsigned char atr[40];
uint32_t uiApdu= 0;
len = sizeof(atr);
memset(szTemp, 0, sizeof(szTemp));

for (y = 0; y < len; y++){
     sprintf(szTemp + strlen(szTemp), "%02X", atr[y]);
}

In particular, What does this mean?
for (y = 0; y < len; y++){
         sprintf(szTemp + strlen(szTemp), "%02X", atr[y]);
    }

A: After each sprintf length(strlen(szTemp )) of szTemp will be increased by 2, so 40 bytes from atr are getting written in szTemp in hex form
atr array don't have any value assigned so its basically holding garbage values


text:
Q: http post not working on my code, but working on postman(rest api client) Here's the code:
$http({
            method  : 'POST',
            url     : 'mailer.php',
            data    : {fullname: "a", email: "b@c.c", confirmEmail: "a@ab.c", phone: "09", website: "a.c"} ,  // pass in data as strings
        })

        .success(function(data, status, headers, config) {
            console.log(data);
            console.log(status);
            console.log(headers);
            console.log(config);

            if (!data.success) {
                // if not successful, bind errors to error variables
                console.log('sending email error');
            } else {
                // if successful, bind success message to message
               // $scope.message = data.message;
               console.log('email sent');
            }
        })

I'm new in angular and php so please take it easy on me. :)
PHP Code:
$mailSend = null;

if (isset($_POST['email'])) {
    $fullname = (isset($_POST['fullname'])) ? $_POST['fullname'] : '';
    $email = (isset($_POST['email'])) ? $_POST['email'] : '';
    $confirmEmail = (isset($_POST['confirmEmail'])) ? $_POST['confirmEmail'] : '';
    $phone = (isset($_POST['phone'])) ? $_POST['phone'] : '';
    $website = (isset($_POST['website'])) ? $_POST['website'] : '';

    if (strlen($fullname) > 0 && strlen($email) > 0) {
        $to = 'adrian@example.com';

        $subject = 'Pricing Request';

        $header  = "From: " . strip_tags($email) . "\r\n";
        $header .= "Reply-To: ". strip_tags($email) . "\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: text/html; charset=UTF-8";

        $content = 'Full Name: ' . $fullname;
        $content .= '
E-mail: ' . $email;
        $content .= '
Phone: ' . $phone;
        $content .= '
Website: ' . $website;

        $mailSend = (mail($to, $subject, $content, $header));
    }
}

Console Ouput:
200
sending email error

A: You never return an object with success property... that's why data.success is false (cause it doesn't exist at all) :
if (!data.success) {
    // if not successful, bind errors to error variables
    console.log('sending email error');
}

But the request seems OK, you even get a 200 response status which mean "It Worked!".


text:
Q: Are these continued fractions of integrals known? Motivated by Bowman and McLaughlin (2000) on polynomial continued fractions, I considered an extension to functional continued fractions, where the numerator of each fraction is the integral of the previous fraction.
That is, define the continued fraction integral transform (CFIT) as \begin{align}\{\mathcal If(t)\}(s)=\dfrac{f(s)}{1+\dfrac{\int_0^s f(x)\,dx}{1+\dfrac{\int_0^s\int_0^u f(x)\,dx\,du}{1+\cdots}}}=\dfrac{f(s)}{1+\dfrac{f^{(-1)}(s)}{1+\dfrac{f^{(-2)}(s)}{1+\cdots}}}={\large{\mathop{\mathrm{K}}_{n=0}^{\infty}}}\frac{f^{(-n)}(s)}1\end{align} where $f\in C^\infty(\Bbb R)$ and $f^{(-k)}$ is Lagrange's notation for the $k$th antiderivative of $f$.
Some elementary properties of the transform include

*

*$\{\mathcal I(0)\}(s)=0$;

*$\{\mathcal If\}(0)=f(0)$;

*$\{\mathcal If\}(s)=\dfrac{f'(s)}{\{\mathcal If'\}(s)}-1$ for all non-constant $f$.
Considering the simplest, non-trivial case $f(t)\equiv1$, we have $f^{(-k)}(t)=t^k/k!$ so that $$\{\mathcal I(1)\}(s)=\dfrac{1}{1+\dfrac s{1+\dfrac{s^2/2!}{1+\cdots}}}.$$
We can see that as $n$ increases, $\mathcal I(1)$ produces more waves. As @PeterForeman mentioned in the comments, the limit $\lim\limits_{s\to-\infty}\mathcal I(1)$ does not exist since it is zero for odd $n$ and $+1$ for even $n$. However, I believe there are more things that can be investigated.

Questions

*

*Has the CFIT already been studied/discovered? If so, reference to literature would be appreciated.

*Going back to the example of $\{\mathcal I(1)\}(s)$, is it true that the maximum value of each wave increases as $s$ increases up to the first wave? Are there an infinite number of such waves, and is there a closed form for $\max\mathcal I(1)$?

A: Not an answer, but one more picture, with the functions for 100 and 150 terms superposed.

It is not clear what is happening on the left.
EDIT:
Here is the code (using sagemath):
def fun(x, N=150):
    L = [x**k/gamma(k + 1) for k in range(N, -1, -1)]
    resu = 1.0
    for t in L:
        resu = t / (1 + resu)
    return resu
P1 = plot(lambda x:fun(x, 100),-12, 3, aspect_ratio=1, color='red'); P1


text:
Q: Volumes of the solid of revolution around y axis The body which regards to the functions $\left\{0\le y\le x^{-2}\sin\left(\frac{1}{x}\right),\:x\in \left(0,1\right)\right\}$ is given. Please calculate the volume of the revolution of it around the y axis.
Now, I fully understand that
0 $\le x^{-2}\sin\left(\frac{1}{x}\right)$ iff $\frac{1}{\pi +2\cdot \:\pi \cdot \:n}\le \:x\le \frac{1}{2\cdot \:\pi \cdot \:n}$.
Hence, the integral should be:
$2\cdot \:\pi \int _{\frac{1}{\pi +2\cdot \:\pi \cdot \:n}}^{\frac{1}{2\cdot \:\pi \cdot \:n}}x^{-1}\sin \left(\frac{1}{x}\right)dx$ . It seems that the integral converges.
How can I solve it? Am I on the correct way?
EDIT= I think I need to find a function g(x) that bounds f(x) from above and converges.
EDIT #2= after changing the argument [1/x=t] I got this thing. $\sum _{n=0}^{\infty }\:\int _{2\pi n}^{2\pi n+\pi }\frac{\sin \left(x\right)}{x}$ Can anyone solve it?
Much obliged,

A: It seems that the best method here is the shell method.
In the shell method, since you are rotating the function about the y-axis, you have to set your function in terms of y, which is already given to you.
Your integral will then become: $$2\pi \int_{\frac{1}{\pi +2\cdot \:\pi \cdot \:n}}^{\frac{1}{2\cdot \:\pi \cdot \:n}}x^{-1}\sin \left(\frac{1}{x}\right)dx$$
Now you solve using integration by parts.
Make $u = 1/x$, and $dv = \sin\left(\frac{1}{x}\right)$
EDIT It doesn't seem that this integral can be solved using IBP.
take a look at this: http://www.wolframalpha.com/input/?i=integral+of+%281%2Fx%29*%28sin%281%2Fx%29%29
And this: http://mathworld.wolfram.com/SineIntegral.html


text:
Q: How to show the duplicate values in pivot table in SQL Server I having table call Specf and I have a view View1 and using these two I need to generate required output.
SPECf:
P1
P2
P3
P4
P5

View1:
Product SPESET      SPECf          Value
A1      ABCSET       P1         C1
A1      ABCSET       P2         C2
A1      XYZSET       P3         C2
A2      ABXSET       P1         C1
A2      ABXSET       P4         C4
A2      ABXSET       P2         C1
A3      CDESET       P5         C2

Output required:
Product SPESET      SPE_P1   SPE_P2    SPE_P3    SPE_P4    SPE_P5
A1      ABCSET       C1         C2       C2       null       null
A1      ABCSET       C1         C2       C2       null       null
A1      XYZSET       C1         C2       C2       null       null
A2      ABXSET       C1         C1       null      c4        null
A2      ABXSET       C1         C1       null      c4        null
A2      ABXSET       C1         C1       null      c4        null
A3      CDESET       null      null      null     null       c2

A: select V2.Product,
       V2.SPESET,
       P.P1 SPE_P1,
       P.P2 SPE_P2,
       P.P3 SPE_P3,
       P.P4 SPE_P4,
       P.P5 SPE_P5
from  (
      select V1.Product, V1.SPECf, V1.Value
      from View1 as V1
      ) as V1
pivot (
      max(V1.Value)
      for V1.SPECf in (P1, P2, P3, P4, P5)
      ) as P
inner join View1 as V2
  on P.Product = V2.Product


text:
Q: Expo: Unable to resolve module index.ts. None of these files exist I'm trying out this template located here (https://github.com/t3-oss/create-t3-turbo).
After installing the dependencies, I ran "pnpm dev" in the terminal. Expo gives this error
Error: Unable to resolve module ./index.ts from C:\Users\...\apps\expo/.:

None of these files exist:
   * index.ts(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.cjs|.native.cjs|.cjs)
   * index.ts\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.cjs|.native.cjs|.cjs)
     at ModuleResolver.resolveDependency (C:\Users\...\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:153:15)
     at DependencyGraph.resolveDependency (C:\Users\...\node_modules\metro\src\node-haste\DependencyGraph.js:276:43)
     at C:\Users\...\node_modules\metro\src\lib\transformHelpers.js:171:21
     at Server._resolveRelativePath (C:\Users\...\node_modules\metro\src\Server.js:1256:12)
     at async Server.requestProcessor [as _processBundleRequest] (C:\Users\...\node_modules\metro\src\Server.js:529:37)
     at async Server._processRequest (C:\Users\...\node_modules\metro\src\Server.js:449:9)

index.ts definitely exists in the expo folder. Why is there an error being thrown?
It looks like "main" in the expo folder's package.json is what's throwing this error. I tried changing it to different values, but nothing helped.
Is anyone at least able to confirm they've reproduced the issue? It may be a bug with the template

A: In case anyone else has this issue, the solution seems to be changing the versions of react and any other libraries that the console suggests.
I was getting a warning for 4 packages that said expo may not work as expected unless these version discrepancies are resolved.
I ignored that because it was my first time with a monorepo, and I thought the versions the template came with would work for everyone. From discussions with others, it seems like it works fine on ios, but not android


text:
Q: add LED indicator and fan to power supply just a Grade 4 Filipino student asking for help.
I'm kinda new to this and I'm not good at math..

Corrections and add-ons:
1. input is 220V AC
2. transformer is multi output(3v,4.5v,6v,9v,12v)(but I used the 12v output only), and is 750mA
3. 1uF EC is 10v
4. DC fan is 12v and 0.14A
is my circuit safe and functional? which part of the circuit should I put my LED indicator and fan?

A:
1uF EC is 10v

A 10V electrolytic on the output of a 7812 regulator is asking for trouble. Try using a 16V or higher rated voltage.
140mA through the 7812 will get it a little warm because the DC input to the 7812 will be about 15.6 volts hence its power dissipated is 3.6 volts x 0.14 amps = 0.5 watts so make sure it doesn't overheat.


text:
Q: SELECT all substrings (n-grams) of length n? How could I select all n-grams, ie. substrings of length n from a string using SQL? For example, the 3-grams of string example are exa, xam, amp, mpl, ple.
I'm using PostgreSQL to be more precise.

A: This does the trick:
SELECT SUBSTRING('example' FROM n FOR 3)
FROM GENERATE_SERIES(1, LENGTH( 'example' )-2, 1) n;
exa
xam
amp
mpl
ple

Here it is in a function:
CREATE OR REPLACE FUNCTION ngrams(varchar, integer) RETURNS SETOF TEXT AS $$
SELECT SUBSTRING($1 FROM n FOR $2)::TEXT
FROM GENERATE_SERIES(1, LENGTH($1)-($2-1), 1) n;
$$ LANGUAGE SQL;

Use it like:
SELECT ngrams('example', 3)

A: There is a module in PostgreSQL which supports trigrams (not n-grams). it is called pg_trgm.
Do the following:
CREATE EXTENSION pg_trgm;

then ...
SELECT show_trgm('hello');

The result will be
 {"  h"," he",ell,hel,llo,"lo "}

A: DECLARE @str varchar(MAX)
DECLARE @ngram int
DECLARE @i int

SET @i = 1
SET @ngram = 5
SET @str = 'Helloworldsed'

WHILE (@i <= (len(@str)-@ngram)+1)
BEGIN
SELECT SUBSTRING(@str,@i,@ngram)
SET @i = @i + 1
END


text:
Q: Always 'error writing output file' in openssl I created a 5 MiB random file using openssl with head:
$ openssl enc -aes-256-ctr -pass pass:1o0SxTnYvbtjFtKLiuv3ccPebLOJiUU -nosalt < /dev/zero | head -c 5M > /mnt/pny1/file1

It created a file of the correct size, but also gave an error message:
error writing output file

I tried it with dd and got the same result:
$ openssl enc -aes-256-ctr -pass pass:1o0SxTnYvbtjFtKLiuv3ccPebLOJiUU -nosalt < /dev/zero | dd of=/mnt/pny1/file2 bs=1M count=5 iflag=fullblock
5+0 records in
5+0 records out
error writing output file
5242880 bytes (5.2 MB) copied, 0.0194212 s, 270 MB/s

I then tried overwriting a loop device using openssl with cat:
# openssl enc -aes-256-ctr -pass pass:1o0SxTnYvbtjFtKLiuv3ccPebLOJiUU -nosalt < /dev/zero | cat > /dev/loop0
cat: write error: No space left on device
error writing output file

Always error writing output file.
Why is this error occurring and how do I prevent it?

A: It's openssls incorrect handling of SIGPIPE. head and also dd will close the pipe when they have recieved their 5 MB. This produces an EPIPE error on the write() system call when the openssl process tries to write to the pipe:

EPIPE    fd is connected to a pipe or socket whose reading end is closed. When this
         happens the writing process will also receive a SIGPIPE signal.

openssl then died due to a signal rather than exiting normally. You can check that in your example using:
$ openssl enc -aes-256-ctr -pass pass:password -nosalt < /dev/zero | head -c 5M >file
error writing output file
$ echo ${PIPESTATUS[@]}
1 0

The $PIPESTATUS array contains the exit values of the processes within the pipes. You see the openssl process exited with exit code 1.

However, to overcome that error, use head or dd before openssl in the pipe:
$ head -c 5M /dev/zero | openssl enc -aes-256-ctr -pass pass:password -nosalt >file
$ echo ${PIPESTATUS[@]}
0 0


text:
Q: Application tried to present a nil model view controller I'm currently trying to implement an introductory (tutorial) section in my application and I would like to give users the option to view it at any time. The main part of my app is made of UIViewController XIB files (ViewController_iPhone.xib, ViewController_iPad.xib) and for the purpose of my introductory views I found it easier to work with Storyboards. So in a quick summary: I am attempting to switch from the main ViewController (XIB) to the starting ViewController within the Storyboard, depending on the device type -> this all begin upon a UIButton tap.
Within my Storyboard I have assigned individual Storyboard ID's so whether it be an iPad, iPhone or iPhone-4inch, it would load the proper view:
Storyboard ID's: 3-Slide1 (iPad), 4-Slide1 (iPhone), 5-Slide1 (iPhone-4inch).

Here is the button code within ViewController.m:
NSString *nibName;
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            nibName = @"3-Slide1";
        } else {
            if ([UIScreen mainScreen].bounds.size.height == 480.0) {
                nibName = @"4-Slide1";
            } else {
                nibName = @"5-Slide1";
            }
        }

        IntroViewController *introViewController = [self.storyboard instantiateViewControllerWithIdentifier:nibName];

        [self presentViewController:introViewController animated:YES completion:nil];

The SIGABRT Error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'Application tried to present a nil modal view controller on target
<ViewController: 0x20865170>.

Why is this error appearing?
Note: there are plenty of posts with the same general SIGABRT error but all seem to have different issues.

A: Why is there a segue leading from your view controller to the info view controller if you are pushing it modally.
I would simply make separate segues to the view controllers (one will be in a different storyboard file, anyway), name the segues and use your logic to determine the correct segue. Then use performSegueWithIdentifier: rather than instantiateViewControllerWithIdentifier.
(I guess the nib name actually refers to the file name of a nib. Not sure, but the segue method is anyway the correct way to do this.)


text:
Q: ParseQueryAdapter on GitHub? Now that the Parse Android SDK is Open Source I went on there to find ParseQueryAdapter but couldn't find it in the project. Can anyone find it out there? Or are they not supporting it anymore?
I would like to contribute to it.

A: ParseQueryAdapter was moved to the ParseUI Android project
https://github.com/ParsePlatform/ParseUI-Android


text:
Q: Can I encrypt the ConfigStoreConnectionString when using In-role Window Azure Cache (dedicated role)? Is there a way to encrypt the ConfigStoreConnectionString when using In-role Window Azure Cache (dedicated role)?
Right now the ConfigStoreConnectionString is stored in the ServiceConfiguration file and it's in the clear. I've been asked to encrypt the connection string using aspnet_regiis for security reasons but when I use an encrypted string the caching doesn't know how to decrypt it. Here's the section of the service config file:
  <Role name="ConnectCacheWorker">
    <Instances count="2" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.NamedCaches" value="xxxxxx" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel" value="1" />
      <Setting name="Microsoft.WindowsAzure.Plugins.Caching.ConfigStoreConnectionString" value="xxxxxx" />

What's the best practice for encrypting Connection strings in the service config file?

A: I dont think this is possible. The cache plugin has to natively support this.