text:
Q: Proof check for $(X/M)^{*} \cong M^{\perp}$ I would like to know if the proof I have is correct.
Statement: Let $M$ be a closed subspace if a Banach space $X$. Let $\pi: X \rightarrow X/M$ be the quotient map. Put $Y= X/M$ for each $\varphi \, \in Y^{*}$ define $f \circ \varphi = \varphi\circ \pi$.
Prove that $f$ is well defined, linear isometry from $Y^*$ onto $M^{\perp}$
Attempted Proof:
(i) Well-defined: let $[x], \,[z] \in Y \, \mbox{s.t.} \, [x]=[z]$. Furthermore, let $\varphi \in Y^*$. Now since $[x]=[z]$ then $x+Y = z+Y \Rightarrow x-z \in Y$ and $\varphi(x) - \varphi(z) = \varphi (x-z) = 0 \Rightarrow \varphi(x) = \varphi(z)$ hence $f(\varphi(x)) = f(\varphi(z))$
(ii) Linearity: Let $\varphi, \, \psi \in Y^*\, \mbox{and} \, k \in \mathbb{C}$ then we have $f(k\varphi + \psi) = (k\varphi + \psi) \circ \pi = k\varphi\circ\pi + \psi\circ\pi = kf(\varphi) + f(\psi)$
(iii) Surjectivity (This is the one that seems the less correct): Let $x \in X$ and let $\varphi \in Y^*$ then $\pi(x) \in Y$ so $x\rightarrow \varphi(\pi(x))$ which is a continuous linear functional on $X$ and vanish if $x \in M$ so $f\circ \varphi \in M^{\perp}$
(iv) Isometry: Let $U$ be the unit ball in $X$ then $\pi(U) = U_{Y}$ is the unit ball in $Y$ , hence $\forall [x] \in U_Y \, \mbox{and} \, y \in [x]$ we have $\|f\circ\varphi([x])\| = \|\varphi\circ\pi(x)\| = \|\varphi\circ \pi(y)\| \leq \|\varphi\|\|y\| \Rightarrow \, |\varphi([x])| \leq \|\varphi\| \|[x]\| \, \mbox{hence} \, \|f\circ \varphi\| \leq \|\varphi\| $
Now to reverse the inequality,
$\forall x \in U_X \Rightarrow [x] \in U_Y$ which would imply that $\| f\circ \varphi\| \geq |f \circ \varphi([x])|= |\varphi(x)|$ so now we have $\| f\circ \varphi\| \geq \sup_{x\in U_X}|\varphi(x)| = \|\varphi\|$
so the inequalities are reversed hence isometric
Q.E.D.

A: You want to define a function $f:Y^*\rightarrow M^\perp$. That way, for $\varphi\in Y^*$ you must have an associated $f(\varphi)$ instead of $f\circ\varphi$.
Also, in (i), you have $[x],[z]\in Y$, so $x,\in X$ and $\varphi\in Y^*$, so you cannot compute $\varphi(x)$ nor $\varphi(z)$ (actually, this step is not necessary).
Surjectivity is not good at all. You simply showed that $f\circ\varphi\in M^\perp$.
Step (iv) seems ok, but you should write $f\circ\varphi(x)$.
I would do the following: In step (i), define $f:Y^*\rightarrow M^\perp$ by $f(\varphi)=\varphi\circ\pi$. There are no arbitrary choices in the definition of $f$, so you don't have to show that it is well-defined. Your proof of it being an isometry os ok, just try to write it more carefully. Linearity should be obvious (if not, prove it).
Now surjectivity: Let $\Lambda\in M^\perp$. Define $\varphi\in Y^*$ by $\varphi([x])=\Lambda(x)$ for every $x\in X$. You have to show that $\varphi$ is well-defined, and it is linear and continuous. Obviously, $f(\varphi)=\Lambda$.


text:
Q: HTML form won't send a field I have this form in HTML:
<form action="http://localhost/Curso/Practica/php/InsertUser.php" method="POST"  name="usuario">

Nombre:<input type="text" name="nombre">Apellidos:<input type="text" name="apellidos">

Nick:<input type="text" name="nick">

Contraseña:<input type="password" name="password">

<FORM ENCTYPE="multipart/form-data" ACTION="RecibirFichero.php" METHOD="post" name"SubFoto">
Foto de perfil: <INPUT NAME="FotoPerf" TYPE="file">

<input type="submit" onMouseDown="validar()">
<input type="reset" name="reset" value="Borrar">
</form>

PHP file InsertUser.php is:
<?php  $nombre=$_POST["nombre"];$apellidos=$_POST["apellidos"];$nick=$_POST["nick"];$password=$_POST["password"];echo($password);?>

The problem is that when I send data to InsertUser.php, the field "password" is empty. that means:
$_POST["password"]="";

And this message appears:

Notice: Undefined index: password in
  C:\xampp\htdocs\Curso\Practica\php\InsertUser.php on line 14

I don't know how to solve this problem.
Thanks for your answer.

A: You have got a form in a form.
<form action=...
[...]
<FORM ENCTYPE=...

Make sure you close a form tag before using a second one.

http://www.w3.org/TR/xhtml1/#prohibitions:

form must not contain other form elements.

A: You have two forms and one form is inside of the other. Make it just one form.
In the input password, try putting an attribute value="". It should work after you make these changes.

A: There are 2 problems with your code, the first one lies in the html portion, YOU CANNOT NEST A FORM, so the first form tag should be whatever it is, and then close it and begin another form, secondly the proper syntax to retrieve posted values is this
$variable_name=$_POST['value'];

Please notice the use of ' and not ", try this and it should work with no hitch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jqueryui slider not working - No errors thrown I am using jquery 1.8.2 and jqueryui 1.8.2.
Simple div.

and simple js:
$( "#slider" ).slider();

I was able to get this to work on jsfiddle.
but doesnt work within my joomla project.
I was suspecting multiple jquery instances. I checked for error in F12 --> console. There were no errors.
And still my div just stays like this:

nothing gets added to it.
if from the console i execute. $( "#slider" ).slider(); still nothing happens.
If i execute $( "#slider" ).datepicker() a datepicker nicely gets added.
Has anyone seen this before?

A: Yes. Happened to me before. I remember, after 2 hours of research and wasting time, I found out that jsfiddle uses jQuery UI.css automatically, without mentioning about it at all. (funny but true)
simply add this to your index.html:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

A: Ok problem found. was using an artisteer template which was also doing some stuff with the slider class. So that was preventing jqueryui to work. thanks guys.
Just wondering if there was smarter way to figure out that there was another piece of js acting on the same class.


text:
Q: solr boost relevant documents with more content I have documents containing few words, few sentences and documents containing a lot of text. When the user searches something, solr gives first the docs with least text as most relevant and at the end gives the docs with the most text. But concering the user, the relevance should be different. The first results should be relevant, but also needs to contain more text because the user needs to get the most relevant docs but with more text - to read something.
So how can I get relevant docs first, but those with more text first, not those with several words. I am using one text field and search inside it.

A: The DefaultSimilarity class used by Lucene, has a scoring algorithm, has a lengthNorm calcluation which boosts the text with less content over the ones with more content.
Basically based on the Number of Terms.
You can easily extend the Similarity class to provide a custom implementation for LengthNorm which renders the calculation based on NumOfTerms ineffective.
This class then can be then specified in the schema.xml for the core to use it.

"Sweet one computes to a constant norm for all lengths in the
  [min,max] range (the "sweet spot"), and smaller norm values for
  lengths out of this range. Documents shorter or longer than the sweet
  spot range are "punished"

The default of min and max is 1, so its not working for you.
Try to set the values e.g. :-
 <similarity class="org.apache.lucene.misc.SweetSpotSimilarity">
   <str name="paramkey">param value</str>
 </similarity>


text:
Q: how to disable SQL_SAFE_UPDATES in google cloud I am using Google Cloud SQL and when running the following query:
SELECT Counter
  FROM Ms_Counter
 WHERE Counter_Id= 'Cust'
   AND Cpy_Id= 'A001'
   AND Counter_Year=2019
   FOR UPDATE;

UPDATE Ms_Counter
   SET Counter= Counter+1,
       Usrup='Me',
       Dtup='2019-03-24'
 WHERE Counter_Id= 'Cust'
   AND Cpy_Id= 'A001'
   AND Counter_Year=2019;

Error trace

Error Code: 1175. You are using safe update mode and you tried to
  update a table without a WHERE that uses a KEY column To disable safe
  mode, toggle the option in Preferences -> SQL Editor and reconnect.

Update 1
Safe-update is turned off by default on Cloud SQL


text:
Q: Visualization of double induction. I have just learnt double induction and I want to make sure that my interpretation is correct.
Theorem
Let, $P(m,n)$ be a statement for $m,n\in \mathbb N$.Suppose,
$(1)$ $P(1,n)$ is true for all $n\in \mathbb N$ and $P(m,1)$ is true for all $m\in \mathbb N$.
$(2)$ For $m_0,n_0>1$, $P(m_0-1,n_0)$ and $P(m_0,n_0-1)$ are true $\implies$ $P(m_0,n_0)$ is true.
Then $P(m,n)$ is true for all $m,n\in \mathbb N$.
I want to give a visual interpretation of why this should be true.Consider the following diagram:

I want to conclude that for any $m_0,n_0\in \mathbb N$ the statement $P(m_0,n_0)$ is true.So,let us take an example when $(m_0,n_0)=(3,4)$,we claim that $P(3,4)$ is true.$P(3,4)$ is true if its left one and bottom one are true and they are true if their left and bottom ones are true which ultimately boils down to $(3,1),(2,1)$ and $(1,2),(1,3),(1,4)$ being true as the arrows suggest in the diagram.But these are indeed true because $P(m,1)$ and $P(1,n)$ are true for all $m,n\in \mathbb N$.Similarly for any $(m,n)$ in this array,we can reach $(m_0,n_0)$ by checking if the immediate left one and bottom one are true which ultimately lead to $P(1,n)$ and $P(,1)$ being true for all $m,n\in \mathbb N$.Is this explanation correct?


text:
Q: How to stretch StackPanel to FullScreen I have ItemDetailPage.xaml with FlipView, inside of DataTemplate i have Grid with come columns. One of columns contains StackPanel with some controls.
Example:
<FlipView.ItemTemplate>
    <DataTemplate>
        <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">
            <ScrollViewer x:Name="scrollViewer" Style="{StaticResource HorizontalScrollViewerStyle}" Grid.Row="1">
                <Grid Margin="120,0,20,20" x:Name="richTextColumns">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="250" />
                        <ColumnDefinition Width="30" />
                        <ColumnDefinition Width="400" />
                        <ColumnDefinition Width="30" />
                        <ColumnDefinition Width="400" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>

                    <StackPanel Orientation="Vertical" Grid.Column="2" Grid.Row="1" Margin="0,0,0,10" x:Name="ContentPanel">
                        <TextBlock FontSize="22" FontWeight="Light" Text="{Binding Title}" TextWrapping="Wrap" />
                        <Image x:Name="image" Width="200" Margin="0,10,0,10" Stretch="UniformToFill" Source="{Binding Image}"/>

                            <StackPanel Orientation="Horizontal" Margin="0,0,0,5">
                                <RichTextBlock x:Name="InformationOriginalName" Width="250"
                                           Style="{StaticResource ItemRichTextStyle}" IsTextSelectionEnabled="False">
                                    <Paragraph>
                                        <Run FontWeight="SemiLight" Text="{Binding EvaInformation.OriginalName}"/>
                                    </Paragraph>
                                </RichTextBlock>
                            </StackPanel>
                    </StackPanel>

                    ....

                </Grid>
            </ScrollViewer>
        </UserControl>
    </DataTemplate>
</FlipView.ItemTemplate>

How to stretch ContentPanel to FullScreen and hide all different controls, including Back button and title of page?


text:
Q: why is one of two floated divs are pushed to the next line? I have two divs which I want to place in one line, the first one with a fixed width and the second without a set width. If I try to set both to float:left, the second div would go to the the next line if it contains too many words. But if the second one is a non-floated one, it stays in the same line with the first div. Why?

.left {
    float: left;
    width: 250px;
    height: 300px;
    background-color: red;
}

.right {
    /*if set to float:left, it might goes the next line*/
    /*float: left;*/
    height: 300px;
    background-color: blue;
}

sidebar

I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents.

A: If the second div is non floated the blue div will remain full width and only the text will float around the red one. Reduce the height of the blue div to better understand what is happening:

.left {
    float: left;
    width: 250px;
    height: 200px;
    background-color: red;
}

.right {
    /*if set to float:left, it might goes the next line*/
    /*float: left;*/
    height: 300px;
    background-color: blue;
}

sidebar

I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents.

The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow ref

So the float element is above the blue div and only the text will wrap arround. If you decrease the height more the text will wrap to next line:

.left {
    float: left;
    width: 250px;
    height: 30px;
    background-color: red;
}

.right {
    /*if set to float:left, it might goes the next line*/
    /*float: left;*/
    height: 300px;
    background-color: blue;
}

sidebar

I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents.

Now if both element are floated, the first one is having fixed width but the second one will have its width calcuated using the shrink-to-fit algorithm:

If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.
Calculation of the shrink-to-fit width is similar to calculating the width of a table cell using the automatic table layout algorithm. Roughly: calculate the preferred width by formatting the content without breaking lines other than where explicit line breaks occur, and also calculate the preferred minimum width, e.g., by trying all possible line breaks. CSS 2.1 does not define the exact algorithm. Thirdly, find the available width: in this case, this is the width of the containing block minus the used values of 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width', 'margin-right', and the widths of any relevant scroll bars.
Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width). ref

In your case the available width is the width of the container and the preferred width is the width of the element without any line break and we take the min between. If we have a lot of text it will logically be the available width

.left {
    float: left;
    width: 250px;
    height: 200px;
    background-color: red;
}

.right {
    float: left;
    height: 300px;
    background-color: blue;
}

sidebar

I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents.

If you reduce the content you will reduce the preferred width and it will be picked since it will be the min value

.left {
    float: left;
    width: 250px;
    height: 200px;
    background-color: red;
}

.right {
    float: left;
    height: 300px;
    background-color: blue;
}

sidebar

I am contents. I am contents.

To avoid any random behavior simply fix the width of both elements:

.left {
    float: left;
    width: 250px;
    height: 200px;
    background-color: red;
}

.right {
    float: left;
    height: 300px;
    width:calc(100% - 250px);
    background-color: blue;
}

sidebar

I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents. I am contents.

A: Because left div has float:left style.. it will adjust automatically depends on window width.. Do u want the right div to next line. plz add this style.
css
.right {
 clear: both;
}


text:
Q: Append text to Blob in Azure After looking at this tutorial on blobs: channel 9, I was thinking of using a blob container to save a bunch of tweets (storing the json of each tweet that is). Ideally I would like to create a blob reference for each hour of the day, and append new tweets to this blob as they come in. The issue is that the method UploadText(string) overwrites the existing content of the blob, is there an easy way to append text to an existing blob ?
Thanks!
        fun (json:string) ->
                    let account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"))
                    let blobs = account.CreateCloudBlobClient();
                    let tempBlob = blobs.GetBlobReference("tweets/2010-9-26/17/201092617.txt")
                    tempBlob.Properties.ContentType <- "text/plain"
                    tempBlob.UploadText(json)

A: Azure now supports Append Blobs. When you create a new blob, you must define it as an Append Block. You can't append to existing block blobs.
Here's some simple code which you can use.
Append:
CloudAppendBlob appendBlob = container.GetAppendBlobReference("myblob.txt")
appendBlob.AppendText("new line");

Read:
appendBlob.DownloadText()

Technet contains a good tutorial on the subject. Also the official Azure documentation now includes help for using Append Blob.

A: Page Blobs are the way to go for this need. (vs block blobs)
You create the blob with a Put Blob operation:
http://msdn.microsoft.com/en-us/library/dd179451.aspx
Then you can add "pages" using a Put page operation:
http://msdn.microsoft.com/en-us/library/ee691975.aspx
Page Blobs will amend the page(s) added with a put immediately, more accurately mimicking traditional file systems.
Block blobs are going to expect a more ridig construction, and require a two-phase submit/commit construction.  Once compiled, you have to overwrite to ammend to the blob.  Block blobs are designed for streaming of static (loose definition) content, vs as a read/write store.  Page Blobs were added to support those scenarios.

A: You can try getting the list of committed blocks via the CloudBlockBlob.DownloadBlockList() method and then append the new content via CloudBlockBlob.PutBlock().


text:
Q: Check if key exists and iterate the JSON array using Python I have a bunch of JSON data from Facebook posts like the one below:
{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}

The JSON data is semi-structured and all is not the same.
Below is my code:
import json

str = '{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}'
data = json.loads(str)

post_id = data['id']
post_type = data['type']
print(post_id)
print(post_type)

created_time = data['created_time']
updated_time = data['updated_time']
print(created_time)
print(updated_time)

if data.get('application'):
    app_id = data['application'].get('id', 0)
    print(app_id)
else:
    print('null')

#if data.get('to'):
#... This is the part I am not sure how to do
# Since it is in the form "to": {"data":[{"id":...}]}

I want the code to print the to_id as 1543 else print 'null'
I am not sure how to do this.

A: I wrote a tiny function for this purpose. Feel free to repurpose,
def is_json_key_present(json, key):
    try:
        buf = json[key]
    except KeyError:
        return False

    return True

A: jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        print("to_id:", dest.get('id', 'null'))

Try it:
>>> getTargetIds(jsonData)
to_id: 1543
to_id: null

Or, if you just want to skip over values missing ids instead of printing 'null':
def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        if 'id' in to_id:
            print("to_id:", dest['id'])

So:
>>> getTargetIds(jsonData)
to_id: 1543

Of course in real life, you probably don't want to print each id, but to store them and do something with them, but that's another issue.

A: You can use a try-except
try:
   print(str.to.id)
except AttributeError: # Not a Retweet
   print('null')

A: It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.
For example create a helper method (or class JsonUtils with static methods) in json_utils.py:
def get_attribute(data, attribute, default_value):
    return data.get(attribute) or default_value

and then use it in your project:
from json_utils import get_attribute

def my_cool_iteration_func(data):

    data_to = get_attribute(data, 'to', None)
    if not data_to:
        return

    data_to_data = get_attribute(data_to, 'data', [])
    for item in data_to_data:
        print('The id is: %s' % get_attribute(item, 'id', 'null'))

IMPORTANT NOTE:
There is a reason I am using data.get(attribute) or default_value instead of simply data.get(attribute, default_value):
{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'

In my applications getting attribute with value 'null' is the same as not getting the attribute at all. If your usage is different, you need to change this.

A: import json

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    if 'to' not in data:
        raise ValueError("No target in given data")
    if 'data' not in data['to']:
        raise ValueError("No data for target")

    for dest in data['to']['data']:
        if 'id' not in dest:
            continue
        targetId = dest['id']
        print("to_id:", targetId)

Output:
In [9]: getTargetIds(s)
to_id: 1543

A: if "my_data" in my_json_data:
         print json.dumps(my_json_data["my_data"])

A: If all you want is to check if key exists or not
h = {'a': 1}
'b' in h # returns False

If you want to check if there is a value for key
h.get('b') # returns None

Return a default value if actual value is missing
h.get('b', 'Default value')


text:
Q: Get the period ending time for a timestamp? (round DateTime up) I'm trying to create a function that returns the period ending datetime for a timestamp, for a given resolution. For example if the resolution is 10 minutes (stored as a TimeSpan) and my timestamp is 2012-08-14 12:34 the period ending time would be 2012-08-14 12:40. Other examples below
Timestamp: 2012-08-14 1:15; Resolution: 01:00:00; Result: 2012-08-14 2:00
Timestamp: 2012-08-14 11:59; Resolution: 00:10:00; Result: 2012-08-14 12:00
Timestamp: 2012-08-14 12:00; Resolution: 00:10:00; Result: 2012-08-14 12:00
Timestamp: 2012-08-14 12:01; Resolution: 00:10:00; Result: 2012-08-14 12:10

I was trying to follow this article (written for t-sql) but was having trouble when it came to supporting resolutions of 15 minutes, 60 minutes and 1 day
Any idea how to make a dynamic solution that can support these multiple (and run time determined) resolutions?
EDIT
This is what I have so far, it works as long as your resolution is less than 60 minutes, but as soon as your resolution is 1 hour you divide the minutes by zero and get an exception.
    public static DateTime ConvertToPeriodEndingTimestamp(TimeSpan resolution, DateTime timestamp)
    {
        var modifiedDate = new DateTime();
        var baseDate = new DateTime(2008, 01, 01, 00, 00, 00);
        var cursor = baseDate;

        var nowToBaseDateDifference = timestamp.Subtract(baseDate).TotalMinutes;

        //SET @Result = DATEADD(MINUTE, (resolution.TotalMinutes * (nowtoBaseDateDifference / resolution.TotalMinutes)) + resolution.TotalMinutes, '20000101')
        modifiedDate =
            baseDate.AddMinutes(((resolution.TotalMinutes*(int)(nowToBaseDateDifference/resolution.TotalMinutes)) +
                                 resolution.TotalMinutes));

        if(timestamp.Minute % resolution.Minutes == 0)
            modifiedDate = modifiedDate.Add(-resolution);

        return modifiedDate;
    }

A: This answer works if your timespan is a factor of one day (864000000000 ticks).
Get the number of ticks in your timestamp and timespan. Take the modulus of the two, and this will give you the number of ticks so far inside the period. If this is zero then you may consider this to be the end of the previous period, and you are done. Otherwise, subtract that to give the start of the period, then add on the number of ticks in the timespan to give the end of the period.

A: Something like this? It uses an int, not a TimeSpan though...
public static DateTime TimeRoundUp(DateTime dt, int Interval)
{
    int nextMin = (int)(dt.Minute / Interval);
    int lowerEdge = nextMin * Interval;
    int upperEdge = lowerEdge + Interval;
    if (dt.Minute - lowerEdge < upperEdge - dt.Minute)
    {
        nextMin = lowerEdge - dt.Minute;
    }
    else
    {
        nextMin = upperEdge - dt.Minute;
    }
    if (nextMin > 59)
    {
        nextMin = 60 - dt.Minute;
    }
    dt = dt.AddMinutes(nextMin);
    dt = dt.AddSeconds(-dt.Second); // zero seconds
    return dt;
}

I have not thoroughly tested it though, but it can give you a start.


text:
Q: Nav bar using slidetoggle I have a Nav bar with a Login and Sign up. When i click on the a(also called the Trigger) the slide up and down but i dont hide the other "tab"
If i click the A("#login-trigger) i would like it to hide my Signup page if. and the other way around ofc with the signup-trigger.
i would be so happy if someone could help me since i have been trying for a few hours now, including trying some codes from here.
This is my entire Jquery script
$(document).ready(function () {
    $('#login-trigger').click(function () {
        $(this).next('#login-content').slideToggle();
        if ($(this).hasClass('active')) $(this).find('span').html('▲')
        else $(this).find('span').html('▼');
    })
    $('#signup-trigger').click(function () {
        $(this).next('#signup-content').slideToggle();
        if ($(this).hasClass('active')) $(this).find('span').html('▲')
        else $(this).find('span').html('▼');
    });
});

Thanks

A: Are you wanting something like this?
This toggles the clicked item but slides up the alternate.
http://jsfiddle.net/8A4T7/1/
$(document).ready(function () {
    $('#login-trigger').click(function () {
        $('#login-content').slideToggle();
        $('#signup-content').slideUp();
        if ($(this).hasClass('active')) $(this).find('span').html('▲')
        else $(this).find('span').html('▼');
    })
    $('#signup-trigger').click(function () {
        $('#login-content').slideUp();
        $('#signup-content').slideToggle();
        if ($(this).hasClass('active')) $(this).find('span').html('▲')
        else $(this).find('span').html('▼');
    });
});


text:
Q: How can I remove duplicates in SQL but keep one copy? I have the following table in SQL with lines of an order as follows:
RowId     OrderId     Type     Text
----------------------------------------
 1        1           5        "Sometext"
 2        1           5        "Sometext"
 3        2           4        "Sometext"
 4        3           5        "Sometext"
 5        2           4        "Sometext"
 6        1           3        "Sometext"

Each order cannot have a duplicate type, but can have multiple different types.
Rows 1 and 2 are duplicates for Order 1, but row 6 is fine.
Rows 3 and 5 are duplicates for Order 2.
I need to delete all of the duplicated data, so in this case I need to delete row 2 and row 5.
What is the best query to delete the data? Or even just return a list of RowID's that contain duplicates to be deleted (or the opposite, a list of RowID's to be kept)?
Thanks.

A: Try a simple approach:
DELETE FROM t
WHERE rowid NOT IN (
  SELECT min(rowid) FROM t
  GROUP BY orderid, type
)

Fiddle here.
Note that it seems you want to keep the lowers rowid when it is repeated. That's why I'm keeping the min.

A: ;with cte as
(
Select Row_Number() Over(Partition BY ORDERID,TYPE ORDER BY RowId) as Rows,
RowId   ,  OrderId   ,  Type  ,   Text from TableName
)
Select RowId   ,  OrderId   ,  Type  ,   Text from cte where Rows>1

Sql Fiddle Demo

A: Please try:
with c as
(
  select *, row_number() over(partition by OrderId, Type order by (select 0)) as n
  from YourTable
)
delete from c
where n > 1;


text:
Q: Kotlin - ArrowCore ensureNotNull in either.eager? I can utilize ensure, but not ensureNotNull in this MRE validation function. I cannot create a suspend fun, so I need to be able to use either.eager. The ability to utilize this would drastically increase the readability for my code.
fun isValid(integer: Int?): Either<Throwable, Int> = either.eager {
    ensure(true) {
        Exception()
    }

    ensureNotNull(integer) { // Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope.
        Exception()
    }

    integer // ^eager
}


text:
Q: how do I return a filtered list using linq? I'm not sure if my title is correct, but linq should pull the right experts in to help the title and answer the question.
If I have a list of People, how do I return a list of PeopleWrappers minus "Dave" and "Jane"?
query looks like this right now:
List<Person> People = CreatListofPersons();
People.Select(t => new PeopleWrapper(t)).ToArray();

A: People.Where( x => x.Name!="Dave" && x.Name!="Jane")
      .Select(t => new PeopleWrapper(t))
      .ToArray();

LINQ has a list of extension methods that allow you to filter or project (which you already to with Select()). In your case you can use Where() to specify which elements you want to let pass, in your example all persons whose name is neither Dave nor Jane.

does it matter if "Where" comes before
  "Select" or after?

You typically want to filter as soon as you can, otherwise you will have to iterate and/or project over items you don't want to have anyway.
Conceptually though, yes, you can put there where() filter later but in your case you are dealing with a PeopleWrapper after you project with Select() - since the Where() extension method is using this data type as input its condition I don't think it would make much sense - you would filter people wrappers, not persons.

A: return People.Where(p => p.Name != "Dave" && p.Name != "Jane");

A: You can use Where to get just the elements that match a condition:
People.Where(p => p.name != "Dave" && p.name != "Jane" ).Select(t => new PeopleWrapper(t)).ToArray()


text:
Q: Windows Phone Silverlight 8.0 - Specify ClientCredentialType to Basic on BasicHttpBinding I have a SOAP WebService that has authorizations and requires me to specify the ClientCredentialType to HttpClientCredentialType.Basic.
I normal .NET project I can specify this (either in code or in XML) to connect to my WebService:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
mySoapClient = new MySoapClient(binding, address);

The problem is that in a Portable Class Library (PCL) or in a Windows Phone 8.0 Silverlight C# project the property Transport does not exist.
Is there a workaround?
Thanks

A: Find out the answer.
Looks like all request must be performed within a OperationContextScope.
        private void InvokeWebMethod(Action webMethod, string username = null, string password = null)
        {
           using (OperationContextScope contextScope = new OperationContextScope(presenceServer.InnerChannel))
            {
                var bc = Encoding.UTF8.GetBytes(string.Format(@"{0}:{1}", username ?? this.Username, password ?? this.Password));
                HttpRequestMessageProperty httpProps = new HttpRequestMessageProperty();
                httpProps.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(bc);

                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpProps;
                webMethod();
            }
        }

THanks.


text:
Q: Dapper Multi-map next level I'm using multiple mapping for a current query and now I need to map another object on the initial query.
For example:
public class Part {
  public int Id { get; set; }
  public string Name { get; set; }

  public Address Address { get; set; }

}

public class Address {
  public int Id { get; set; }
  public string Street { get; set; }

  public SiteOu Ou { get; set; }
}

public class SiteOu
  public int Id { get; set; }
  public string Name { get; set; }
}

Dapper:
 connection.Query<Part, Address, Part>(sql, (part, address) => {
    part.Address = address;
  });

How do I get the Address class to have the SiteOu information?
This example isn't what I'm actually doing because I've actually got
Query<T1,T2,T3,T4,T5,TResult>();

I'm doing 1 select and 5 joins in my query.  So hopefully I don't need more overloads of Query.

A: Dapper allows you to map a single row to multiple objects, so you can just map SiteOu as part of the same query.
[Test]
public void TestSplitOn()
{
    var conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=true;Initial Catalog=db");
    conn.Open();
    const string sql = "select Id = 1, Name = 'My Part', " +
                       "Id = 2, Street = 'My Street', " +
                       "Id = 3, Name = 'My Site'";
    var result = conn.Query<Part, Address, SiteOu, Part>(sql, (part, address, siteOu) =>
    {
        part.Address = address;
        address.Ou = siteOu;
        return part;
    },
    commandType: CommandType.Text
    ).FirstOrDefault();

    Assert.That(result, Is.Not.Null);
    Assert.That(result.Address, Is.Not.Null);
    Assert.That(result.Address.Ou, Is.Not.Null);
}

Important Note: Dapper assumes your Id columns are named "Id" or "id", if your primary key is different or you would like to split the wide row at point other than "Id", use the optional 'splitOn' parameter.
If you have more that 5 types to map, another out of the box option is to use QueryMultiple extension. Here is an example from the Dapper docs.
var sql =
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id";

using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
   var customer = multi.Read<Customer>().Single();
   var orders = multi.Read<Order>().ToList();
   var returns = multi.Read<Return>().ToList();
   ...
}

Also check out this thread.


text:
Q: Functional equations with 3 variables What are the general solutions of the functional equations?
$$
f(x,y)+f(y,z)=\frac{1}{f(x,z)}
$$
$$
f(x,y)f(y,z)f(x,z)=1
$$

A: I am assuming the variables are real.
For the first, setting $x=y=z$ gives $2f(x,x)=\frac 1{f(x,x)}$, so $f(x,x)=\pm\frac {\sqrt 2}2$
As Ivan Loh points out, the sign choice must be the same for all $x$:
$\quad$$y=z$ gives $f(x,z)+f(z,z)=\frac1f{(x,z)}$
$\quad$$x=y$ gives $f(x,x)+f(x,z)=\frac 1{f(x,z)}$
$\quad$so $f(x,x)=f(z,z).$
Assume $f(x,x)=\frac {\sqrt 2}2$:
$\quad$Setting $x=z$ gives $f(x,y)+f(y,x)=\sqrt 2$
$\quad$Setting $y=z$ gives $f(x,z)+\frac {\sqrt 2}2 = \frac 1{f(x,z)}$
$\quad$This has solutions $f(x,z)=\frac {\sqrt 2}2, -\sqrt 2$
$\quad$But only the first satisfies the original equation
Now if $f(x,x)=-\frac{\sqrt 2}2$
$\quad$Setting $x=z$ gives $f(x,y)+f(y,x)=-\sqrt 2$
$\quad$Setting $y=z$ gives $f(x,z)-\frac {\sqrt 2}2 = \frac 1{f(x,z)}$
$\quad$This has solutions $f(x,z)=-\frac {\sqrt 2}2, \sqrt 2$
$\quad$But only the first solves the original equation
So $f(x,y)$ is the same for all $x,y$ and is $\pm \frac {\sqrt 2}2$
For the second, setting $x=y=z$ gives $f(x,x)=1$
Setting $x=z$ we get $f(x,y)f(y,x)=1$ or $f(x,y)=\frac 1{f(y,x)}$
Setting $x=y$ we have $f(x,z)^2=1$
So $f(x,y)=\pm 1$ for all $x,y$
As Hagen von Eitzen points out, we can divide the reals into two equivalence classes in any way we want (including one of them empty).  Let $a,b$ be representatives of the two classes.  We have $f(a,a)=f(b,b)=1, f(a,b)=f(b,a)=-1$

A: Under the false assumption that they need to both hold,
From the first equation, $f$ is never zero.  From the second equation, $f(x,y)f(y,z)=\frac{1}{f(x,z)}$; combining with the first we get $$f(x,y)+f(y,z)=f(x,y)f(y,z)$$
Taking $x=y=z$ we get $2f(x,x)=f(x,x)^2$; since $f(x,x)\neq 0$ we have $f(x,x)=2$ for all $x$.  Taking $x=y$ we get $2+f(y,z)=2f(y,z)$ so $f(y,z)=2$ for all $y,z$.  But this doesn't satisfy the second equation, so there are no solutions.

A: There are infinitely many(whose cardinality is $2^\Bbb R$)
solutions $f:\Bbb R\to \Bbb R$ of the simple functional equation
$$
f(x)^2=1.
$$
Let $A$ be an arbitrary subset of $\Bbb R$. Then,
$f(x)=1$ for $x\in A$, $f(x)=-1$ for $x\in A^c$
are the solutions of the equation.
Therefore, the above proof(by Millikan) makes no sense.


text:
Q: Push new object at specific index using immutability helper I have tried to do this:
 const rowObj = {key: value};
    const rowIndex = 2;

    this.setState({
          data: update(this.state.data,
              { [rowIndex] : { $push : [rowObj] } }
          )
    })

But, It throw error like this:
Uncaught Error: update(): expected target of $push to be an array; got undefined.

A: Try like this
const rowArray = [{key: value},{key: value},{key: value}];
const obj = {key: value}
const rowIndex = 2;
rowArray.splice(rowIndex, 0, obj);
this.setState({ data: update(this.state.data,{rowArray : {$set : rowArray}} ) });

A: Since you want to push to an array i.e data, you would not want to specify the index and write it like
const rowObj = {key: value};

this.setState({
      data: update(this.state.data,
           { $push : [rowObj] }
      )
})

or else if you want to set a value to a particular index in the array, you should use $set
const rowObj = {key: value};
const rowIndex = 2;

this.setState({
      data: update(this.state.data,
          { [rowIndex] : { $set : rowObj } }
      )
})

A: Based on this answer here's a version that uses immutability helper itself
const rowArray = [{
  key: value
}, {
  key: value
}, {
  key: value
}];
const obj = {
  key: value
}
const rowIndex = 2;
this.setState({
  data: update(this.state.data, {
    rowArray: {
      $splice: [
        [rowIndex, 0, obj]
      ]
    }
  })
});


text:
Q: Is there any way or javascript function that can be written to scroll scrollbars that are part of an element eg: table/div In my application there has 2 scroll bar .one is web page scroll bar and another one is inner table scroll bar.
My task is only to scroll down table scroll bar.So for that I used JavaScript
WebElement element = driver.findElement(By.id("table id"));
((JavascriptExecutor)driver).executeScript("argument[0].scrollIntoView(true);", element);

My test cases are getting passed but scroll bar doesn't move down of table. So please anyone can help me would be more appreciatable.
Thanks,
I am looking solution of inner scroll scroll down and up.

A: You're probably trying to scroll an already visible element and that's why it's not scrolling. So first, try giving an element in the table that isn't visible, something like:
WebElement element = driver.findElement(By.id("table id"));
WebElement lastTableElement = element.findElement(By.cssSelector("tr:last-child"));
((JavascriptExecutor)driver).executeScript("argument[0].scrollIntoView(true);", element);

And for scrolling up to the first child again:
    WebElement lastTableElement = driver.findElement(By.cssSelector("tr:first-child"));

You can also do scrolling by pixels:
((JavascriptExecutor)driver).executeScript("argument[0].scrollTop += 100;", element);


text:
Q: MS ACCESS count/sum number of rows, with no duplicates I have the following table which I need to count the total number of rows without including any duplicate records.
CustomerID
test1
test1
test2
test3
test4
test4

As you can see, the total number of rows is 6 but there are two test1 and two test4, and I wish the query to return 4.  IOW, I want to count unique values in CustomerID.
I've tried sub query but didn't get it to work for me.
-- Update 27/06/2012 --
Thanks, both worked for me:

*

*SELECT COUNT(*) FROM ( SELECT CustomerID FROM TheTable GROUP BY CustomerID ) as

*SELECT COUNT(*)
  FROM
  (
      SELECT DISTINCT CustomerID FROM TheTable
  ) AS sub;

I now need a query to keep only those CustomerID which were added today, then count them.
For example,
CustomerID DateAdded
test1 25/06/2012
test1 25/06/2012
test2 26/06/2012
test3 27/06/2012 - Today
test4 27/06/2012 - Today
test4 27/06/2012 - Today

then it needs to return 3.
I've tried adding in the following query into the two solutions provided, but couldn't get either of them to work/return the value I want.

HAVING (([TheTable].DateAdded)=Date());

A:
This would work in SQL, I think it should also in Access:
SELECT COUNT(DISTINCT CustomerID) FROM TheTable

Edit: Per Jeff in comments, Access doesn't support the above syntax.
This should work for sure though:
SELECT COUNT(*) FROM ( SELECT CustomerID FROM TheTable GROUP BY CustomerID ) a

To restrict by date
SELECT COUNT(*) FROM (
    SELECT TheTable.CustomerID FROM TheTable GROUP BY CustomerID
    WHERE TheTable.DateAdded >= Date()
) a

A: The second suggestion in dbaseman's answer looks correct to me.  This alternative should also work.
SELECT COUNT(*)
FROM
    (
        SELECT DISTINCT CustomerID FROM TheTable
    ) AS sub;

I don't know whether it offers any advantage over dbaseman's GROUP BY.  If you decide to test both approaches, please add a comment to tell us what you find.
Based on your comment, you want to evaluate "only those records that were added today".  Since you didn't give us enough information about your table, I will pretend it includes a Date/Time field named date_added.  And each time you add a record you store the current date, with the time component as midnight, in that field.  In that case you can add a WHERE clause to the subquery to ask the db engine to consider only those rows where date_added is equal to today's date.  The Date() function will give you today's date, with midnight as the time component.
SELECT COUNT(*)
FROM
    (
        SELECT DISTINCT CustomerID FROM TheTable
        WHERE date_added = Date()
    ) AS sub;

Once you replace date_added with your field name, that should work provided my assumptions were correct.  However if your date_added values include any time component other than midnite, you will have to revise the WHERE clause to capture all Date/Time values from today.
WHERE date_added >= Date() AND date_added < (Date() + 1)


text:
Q: Vertical Pod Autoscaling on Azure Kubernetes Service Is Vertical Pod Autoscaling supported on Azure Kubernetes Service? I am unable to find any links or page on msdn with the details about it.

A: The Vertical Autoscaler is not supported in AKS, as the feature is still in Alpha in the upstream Kubernetes project. As the features matures in upstream it will be integrated into the service.


text:
Q: Is it correct way to return from method with subscription inside (Angular) Is it correct way to return value like in method below?
  private canView(permission: string, resource: string): boolean {
    let result: boolean;

    this.accessChecker.isGranted(permission, resource)
      .pipe(
        take(1)
      )
      .subscribe(
        granted => {
          result = granted;
        }
      );

    return result;
  }

The method is called to set show property for menu item:
    @Component({
      selector: 'ngx-pages',
      styleUrls: ['pages.component.scss'],
      template: `
        <ngx-one-column-layout>
          <nb-menu [items]="menu"></nb-menu>
          <router-outlet></router-outlet>
        </ngx-one-column-layout>
      `,
    })
    export class PagesComponent {
    menu: NbMenuItem[] = [
    {
      title: 'Admin area',
      icon: 'settings-outline',
      show: this.canView('view', 'it_only'),
      children: [
        {
          title: 'config.json',
          link: '/pages/admin-it/config-json',
        },
        {
          title: 'JWT',
          link: '/pages/admin-it/jwt',
        },
      ]
    }]

    constructor(private accessChecker: NbAccessChecker) { }

    private canView(permission: string, resource: string): boolean {
      // see above
    }

Can I have a situation when result returned before it value will be set in the subscription (for as i know subcribe is asynchronous)?
If yes what is the correct way?

A: are you using this to create boolean for different canView permissions? If so you can just turn those booleans into Observables.
canViewElement1$ = this.canView('element1', 'res1');
canViewElement2$ = this.canView('element2', 'res2');

private canView(permission: string, resource: string): Observable<boolean> {
    return this.accessChecker.isGranted(permission, resource);
}

on the template, if you use it for ngIf, call it with async pipe. you won't have to worry about unsubscribing or take(1) this way:
<div *ngIf="canViewElement1$ | async">
...
</div>

A: Result might not have the value from the subscription in that point of time

A: You may want to make canView as an async function, convert the Observable returned by isGranted to promise using toPromise(), then await for the result
  private async canView(permission: string, resource: string): Promise<boolean> {
    let result: boolean = await this.accessChecker.isGranted(permission, resource)
      .pipe(
        take(1)
      ).toPromise();
    return result;
  }


text:
Q: Python: TCP Server with public IP My code:
sIP = "20.20.20.20" #My original IP comes from here > whatismyip.com
sPort = 4567
bSize = 2048

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((sIP, sPort))

My error:
Traceback (most recent call last):
  File "/home/d0nkey/Scripts/TCPServer.py", line 19, in <module>
    s.bind((sIP, sPort))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 99] Cannot assign requested address

The same code works fine using localhost and my local ip instead.
How to set up a TCP server on my public IP?
[OS: Linux elementaryOS 86x64]

A: You have to bind it to your local IP (depending on which network card to use) and make use of port forwarding (NAT) in your router to forward the traffic of the public IP (for the TCP server) to your local IP. In that way your TCP server will be available remotely.

A: You can only bind to an address that is available on the network interfaces of the operating system that is running your program. You have a Linux. So try to open a terminal and type in "ifconfig" to see all available interfaces and their addresses. It is also possible to bind to all available addresses, using the special "0.0.0.0" address. Please note that whatismyip.org tells you the public ip that connects your inner network to the internet. If you are behind a firewall/NAT then you need to setup port forwarding, and redirect requests from the firewall/gateway address to the local address where your program is listening. If you have no access to the firewall settings, then you cannot listen on its public address.


text:
Q: How can I install Wine (i386) on Ubuntu 19.10? Since Canonical decided not to include i386 packages support and I get errors during Playonlinux / Crossover / wine installations, what is a workaround to address this issue?
It's a known issue, and I'm asking if someone solved it.

A: Execute the following commands for a Wine installation:
sudo dpkg --add-architecture i386
wget -qO - https://dl.winehq.org/wine-builds/winehq.key | sudo apt-key add -
sudo apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ disco main'
sudo apt-get update
sudo apt install --install-recommends winehq-stable


text:
Q: What is the best way to represent the below data and highlight in UI For example I have the following data,
var expectedValuesObj = [ "a.com","testid1","200.00" ];

var actualValuesObj = [
                        ["a.com","testid1","200.00"],
                        ["a.com","testid1","200.00"],
                        ["a.com","testid1","200.00"],
                        ["b.com","testid2","200.00"],
                        ["a.com","testid1","200.00"],
                        ["c.com","testid1","200.00"],
                        ["a.com","testid1","400.00"],
                        ["a.com","testid1","200.00"],
                        ["a.com","testid1","200.00"]
                    ];

by using the above data I need compare the data with expectedValuesObj against actualValuesObj , each and every value in those objects, if found any mismatch then I have to highlight  the records which are mismatching from the expectedValuesObj .
For e.g in expectedValuesObj[0] I will compare with actualValuesObj[0]
, I didn't find any mismatch because
actualValuesObj[0] = ["a.com","testid1","200.00"]  all the values are matching with expectedValuesObj[0] = ["a.com","testid1","200.00"]. records
If any record found to be a mismatch then that record I have to highlight.
I preferring any good suggestion and idea using js, bootstrap, jquery, dataTables and laodash.
Note :   For comparing two datasets, if you want you can change the dataFormat as per your comfortable, If you feel the given dataSet is not comparable.
mainPage.html

 This Div will have DataTable rendered by below js script file i.e File1.js , And this will Contain the child rows as well which will have the href link and I will open the new window on click of that link , it will open  the mainPage2.hmtl with File2.js loaded .

mainPage2.hmtl

 Here I want render the Data which is mismatched  and and I have to highlight.


text:
Q: Jmeter Beanshell post processor not writting anything to csv file I have simple code like this-
import java.io.FileOutputStream;

import java.io.BufferedWriter;

import java.io.FileWriter;
num1 = vars.get("num");

log.info("num1");

 FileWriter fstream = new FileWriter("C:\abc\\r.csv", true);
 BufferedWriter out = new BufferedWriter(fstream);
 out.write(vars.get("num"));
 out.write(System.getProperty("line.separator"));
 out.close();
 fstream.close();

however it is not working and nothing gets to the csv file.  I can see the number printed in the log file with log statement. Also there are no errors.

A: *

*Make sure that num1 variable is not null, in order to check it amend the line which prints it out as:
log.info(num1);

You need to remove quotation marks around num1 to see the actual value

*You need to escape "abc" folder name with double backslash:
FileWriter fstream = new FileWriter("C:\\abc\\r.csv", true);

*Maybe it would be easier to use FileUtils class like:
import org.apache.commons.io.FileUtils;
FileUtils.writeStringToFile(new File("C:\\abc\\r.csv), vars.get("num"), true);
FileUtils.writeStringToFile(new File("C:\\abc\\r.csv"), System.getProperty("line.separator"), true);

*You can print a lot of Beanshell debugging into STDOUT by adding debug(); directive at the very beginning of your Beanshell script. Also consider using Debug Sampler and View Results Tree listener combination to check JMeter Variables and Properties values. See How to debug your Apache JMeter script article for more details.

A: Try this one:
import java.io.FileOutputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException; //import IOException, you'll need it later
import java.io.File; // this too :)

int num1 = vars.get("num"); // you need to declare variable type, int in your case, othrewise it's an error
log.info(String.valueOf(num1)); //use String.valueOf() to convert int to String before logging

try {
    // you need to escape '\', or better use linux-style paths
    File myCsv = new File("C:/abc/r.csv");

    FileWriter fstream = new FileWriter(myCsv, true);
    BufferedWriter out = new BufferedWriter(fstream);
    out.write(num1);
    out.write(System.getProperty("line.separator"));
    out.close();
    fstream.close();
} catch (IOException exc) {
    // in case any error occurs, catch it and log
    log.error("Failed to write to file!\r\n" + exc.getMessage());
}

Not sure, if you need to add all those imports, theoretically jmeter should get them automatically, but I don't have any meanings to check right now.
Update:
Make sure the directory where your r.csv is exists and you have permissions to write there.


text:
Q: Meaning of "the fifty-yard line" He was everywhere: he was at the communion rail,

the fifty-yard line

, he played the oboe with the Chamber Music Club, drove the fire truck, served on the school board and rode the 8:03 into New York every morning

A: The fifty-yard line is the center line of a football field (American football).  To be "at the fifty-yard line" is to be a player in a football team, and actually take part in the game (and not on the sidelines), most likely the beginning, which starts in the center of the field.
EDIT: As StoneyB pointed out, the game starts by a kick-off (unlike the soccer game that starts at the center).  So, the fifty-yard line separates the "home-visitors" zones, as you are on the field and at it, you're in the middle point from your end zone to the opponent's.  Spectator seats closest to the fifty-yard line offer the best view of the game.
Whether "he" was a player or a spectator should be clearer from the context.


text:
Q: Interrupt Handler Stops Working After Kernel Module Reload (Xilinx FPGA / PCIe) I am currently working on a PCI driver for the Xilinx Kintex 7 board using the Xilinx PCI IP core (AXI Memory Mapped to PCIe).
One problem is, that the interrupt handler stops working when I reload the kernel module. In more detail:

*

*Fresh boot of my machine

*Load the kernel module and monitor the kernel messages with dmesg

*/proc/interrupts shows the expected interrupt ids

*I trigger the HW interrupt and everything works as expected; I can see the interrupt handler working.

*rmmod my_module

*/proc/interrupts removed the interrupt ids as expected

*insmod my_module and trigger interrupt

*Now the interrupt handler is silent and /proc/interrupts does not increase the counter

I reboot my machine and everything works again. The fact that I do not have to restart the FPGA lets me assume that I do something wrong in the kernel module and its probably not an HW problem.
I've already used /sys/pci/devices/.../reset, /sys/bus/pci/devices/.../remove and /sys/bus/pci/rescan to try to reach a state which is equivalent to freshly booted machine. But nothing worked.
Relevant module code:
#define VENDOR_ID 0x10EE
#define DEVICE_ID 0x7024

static dev_t pci_dev_number;
static struct cdev * driver_object;
static struct class * pci_class;
static struct device * pci_prc;
static struct device * pci_irq_0;
static struct device * pci_irq_1;

static int msi_vec_num = 2; // Number of requested MSI interrupts
static int msi_0 = -1;
static int msi_1 = -1;

// Used for poll and select
static DECLARE_WAIT_QUEUE_HEAD(queue_vs0);
static DECLARE_WAIT_QUEUE_HEAD(queue_vs1);

static irqreturn_t pci_isr_0(int irq, void * dev_id) {
  printk(KERN_NOTICE "codec IRQ: interrupt handler 0. IRQ: %d\n", irq);
  wake_up_interruptible(&queue_vs0);
  return IRQ_HANDLED;
}

static irqreturn_t pci_isr_1(int irq, void * dev_id) {
  printk(KERN_NOTICE "codec IRQ: interrupt handler 1. IRQ: %d\n", irq);
  wake_up_interruptible(&queue_vs1);
  return IRQ_HANDLED;
}

static void* bars[PCIE_BARS] = {0};

static int device_init(struct pci_dev * pdev, const struct pci_device_id * id) {
  int i = 0; // loop var
  if (pci_enable_device(pdev))
    return -EIO;

  // Request memory regions for bar 0 to 2
  for (i = 0; i < PCIE_BARS; i++) {
    if (pci_request_region(pdev, i, "codec_pci") != 0) {
      dev_err( & pdev - > dev, "Bar %d - I/O address conflict for device \"%s\"\n", i, pdev - > dev.kobj.name);
      return -EIO;
    }
  }

  // DEBUG: Check if we are in memory space (which we should) or io space
  if ((pci_resource_flags(pdev, 0) & IORESOURCE_IO)) {
    printk(KERN_NOTICE "codec INIT: in io space\n");
  } else if ((pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
    printk(KERN_NOTICE "codec INIT: in mem_space\n");
  }

  // This request enables MSI_enable in the hardware
  msi_vec_num = pci_alloc_irq_vectors(pdev, 1, msi_vec_num, PCI_IRQ_MSI);

  // msi_N will contain the IRQ number - see /proc/interrupts
  msi_0 = pci_irq_vector(pdev, 0);
  msi_1 = pci_irq_vector(pdev, 1);
  printk(KERN_NOTICE "codec INIT: nvec: %d\n", msi_vec_num);
  printk(KERN_NOTICE "codec INIT: msi_0: %d\n", msi_0);
  printk(KERN_NOTICE "codec INIT: msi_1: %d\n", msi_1);

  if (request_irq(msi_0, pci_isr_0, IRQF_SHARED, "codec_pci", pdev)) {
    dev_err( & pdev - > dev, "codec INIT: IRQ MSI %d not free.\n", msi_0);
    goto cleanup;
  };
  if (request_irq(msi_1, pci_isr_1, IRQF_SHARED, "codec_pci", pdev)) {
    dev_err( & pdev - > dev, "codec INIT: IRQ MSI %d not free.\n", msi_1);
    goto cleanup;
  };

  for (i = 0; i < PCIE_BARS; i++) {
    // Last parameter is the address space/length of each bar. Defined in the PCIe core.
    bars[i] = pci_iomap(pdev, i, pci_resource_len(pdev, i));
    if (bars[i] == NULL) {
      printk(KERN_ERR "codec INIT: bar %d allocation failed\n", i);
      goto cleanup;
    }
    printk(KERN_NOTICE "codec INIT: bar %d pointer: %p\n", i, bars[i]);
  }

  printk(KERN_NOTICE "codec INIT: loaded\n");

  return 0;
cleanup:
    for (i = 0; i < PCIE_BARS; i++) {
      if (bars[i] != NULL)
        pci_iounmap(pdev, bars[i]);
      pci_release_region(pdev, i);
    }

  return -EIO;
}

static void device_deinit(struct pci_dev * pdev) {
  int i = 0; // loop var

  if (msi_0 >= 0)
    free_irq(msi_0, pdev);

  if (msi_1 >= 0)
    free_irq(msi_1, pdev);

  pci_free_irq_vectors(pdev);

  // release bar regions
  for (i = 0; i < PCIE_BARS; i++)
    pci_release_region(pdev, i);

  for (i = 0; i < PCIE_BARS; i++) {
    if (bars[i] != NULL)
      pci_iounmap(pdev, bars[i]);
  }
  pci_disable_device(pdev);
}

// File operations not in this snipped
static struct file_operations fops = {
  .owner = THIS_MODULE,
  .open = device_open,
  .read = device_read,
  .write = device_write,
  .poll = device_poll
};

static struct pci_device_id pci_drv_tbl[] = {
  {
    VENDOR_ID,
    DEVICE_ID,
    PCI_ANY_ID,
    PCI_ANY_ID,
    0,
    0,
    0
  },
  {
    0,
  }
};

static struct pci_driver pci_drv = {
  .name = "codec_pci",
  .id_table = pci_drv_tbl,
  .probe = device_init,
  .remove = device_deinit
};

static int __init mod_init(void) {
  int i = 0;
  if (alloc_chrdev_region( & pci_dev_number, 0, MAX_DEVICES, "codec_pci") < 0)
    return -EIO;
  driver_object = cdev_alloc();
  if (driver_object == NULL)
    goto free_dev_number;
  driver_object - > owner = THIS_MODULE;
  driver_object - > ops = & fops;
  if (cdev_add(driver_object, pci_dev_number, MAX_DEVICES))
    goto free_cdev;
  pci_class = class_create(THIS_MODULE, "codec_pci");
  if (IS_ERR(pci_class)) {
    pr_err("codec MOD_INIT: no udev support available\n");
    goto free_cdev;
  }

  pci_prc = device_create(pci_class, NULL, MKDEV(MAJOR(pci_dev_number), MINOR(pci_dev_number) + 0), NULL, "%s", "codec_prc");
  pci_irq_0 = device_create(pci_class, NULL, MKDEV(MAJOR(pci_dev_number), MINOR(pci_dev_number) + 1), NULL, "codec_irq_%d", 0);
  pci_irq_1 = device_create(pci_class, NULL, MKDEV(MAJOR(pci_dev_number), MINOR(pci_dev_number) + 2), NULL, "codec_irq_%d", 1);

  if (pci_register_driver( & pci_drv) < 0) {
    for (i = 0; i < MAX_DEVICES; i++)
      device_destroy(pci_class, MKDEV(pci_dev_number, i));
    goto free_dev_number;
  }

  return 0;
free_cdev:
    kobject_put( & driver_object - > kobj);
free_dev_number:
    unregister_chrdev_region(pci_dev_number, MAX_DEVICES);
  return -EIO;
}

static void __exit mod_exit(void) {
  int i = 0;
  pci_unregister_driver( & pci_drv);
  device_unregister(pci_prc);
  device_unregister(pci_irq_0);
  device_unregister(pci_irq_1);
  for (i = 0; i < MAX_DEVICES; i++) {
    device_destroy(pci_class, MKDEV(pci_dev_number, i));
  }
  class_destroy(pci_class);
  cdev_del(driver_object);
  unregister_chrdev_region(pci_dev_number, MAX_DEVICES);
}

module_init(mod_init);
module_exit(mod_exit);

Error handling routines could be better, but they don't get triggered anyway.

A: I guess I found the cause of my problem. I took a look at the PCI configuration space while executing each of the steps of my original post. The configuration space when interrupts are working:
# lspci -xxx | grep Xilinx
23:00.0 Memory controller: Xilinx Corporation Device 7024
00: ee 10 24 70 *07* 04 10 00 00 00 80 05 10 00 00 00
. . .

And when it's broken:
# lspci -xxx | grep Xilinx
23:00.0 Memory controller: Xilinx Corporation Device 7024
00: ee 10 24 70 *03* 04 10 00 00 00 80 05 10 00 00 00
. . .

What I found is that the command register value changes after the kernel module reload (marked with *). When the interrupt works the command register value is 0x0407, after the module reload it is 0x0403. Why? I don't know. It is probably just the way the Xilinx AXI Memory Mapped to PCIe core is implemented.
Anyway, you can set the values of the PCI configuration space using setpci(8).
The wanted value of the command register is 0407 so you execute:
# setpci -d <vendor_id>:<device_id> command=0407

#read back to check if it worked
# sudo setpci -d <vendor_id>:<device_id> command
0407

Afterwards the interrupts are working again, and I do not need to reboot.
Within the kernel module you can e.g. use pci_write_config_byte(...) to set the command register (or any other) to the required value. The corresponding functions to access the configuration space can be found here: Linux Device Drivers - Accessing the Configuration Space


text:
Q: Excel Index Match and Date Array Formula returns same value I am trying to get all dates from the first column for which the number 1 is displayed in the next column, using INDEX MATCH and an Array formula.
I can't seem to find what I am doing wrong, the dates returned repeat themselves a number of times. I want only each individual date once.
Formula:
{=INDEX(D1:E7, MATCH(1,E1:E7,0), 1)}

D1:E7 contain from 01.01.2022 to 01.07.2022

E1:E7 contain 0,1,0,1,1,0,1

Result :
02.02.2022
02.02.2022
04.02.2022
04.02.2022
05.02.2022
07.02.2022
07.02.2022

Expected result :
02.02.2022
04.02.2022
05.02.2022
07.02.2022

Thanks

A: If you have a recent version of Excel, you can use FILTER, like this:

Formula in G2:
=FILTER($D$1:$D$7,$E$1:$E$7=1)

A: This Answer is related to Excel versions older than 2021. If you are using recent Excel version, see the other answer which provide much more easier formula.
You get this result because you don't have locked ranges D1:D7 and E1:E7.
Here you see your result and formula which produces them
02.01.2022  {=INDEX(D1:D7,MATCH(1,E1:E7,0),1)}
02.01.2022  {=INDEX(D2:D8,MATCH(1,E2:E8,0),1)}
04.01.2022  {=INDEX(D3:D9,MATCH(1,E3:E9,0),1)}
04.01.2022  {=INDEX(D4:D10,MATCH(1,E4:E10,0),1)}
05.01.2022  {=INDEX(D5:D11,MATCH(1,E5:E11,0),1)}
07.01.2022  {=INDEX(D6:D12,MATCH(1,E6:E12,0),1)}
07.01.2022  {=INDEX(D7:D13,MATCH(1,E7:E13,0),1)}

Use Evaluate formula tool to see each step of calculation
I suppose, you are using older version of Excel (because you are still using array formulas). So we have to omit new useful formulas as SORT or UNIQUE.
Use this Array formula and stretch it down
{=IFERROR(INDEX($D$1:$D$7,SMALL($E$1:$E$7*ROW($E$1:$E$7),ROWS($D$1:$D$7)-SUM($E$1:$E$7)+ROW(D1)-ROW($D$1)+1)),"")}

How it works:

*

*$E$1:$E$7*ROW($E$1:$E$7) returns an array with row numbers of where is 1 in range E1:E7 and zeroes. In our case: 0,2,0,4,5,0,7

*Then we use SMALL  function for array from 1. to get only values higher than zero. You can imagine that SMALL sort the input array and return value on given position. In our case is the sorted array 0,0,0,2,4,5,7

*Now we want skip leading zeroes. It's done by ROWS($D$1:$D$7)-SUM($E$1:$E$7)which returns in our case 7-4=3

*And we want to get item by item from SMALL, so we need some sequence (+1) for each next row. Its done by ROW(D1)-ROW($D$1). If you stretch it down it gives sequence 0,1,2...

*Getting 2-4 together we get ROWS($D$1:$D$7)-SUM($E$1:$E$7)+ROW(D1)-ROW($D$1)+1) which represents position of wanted item in SMALL sorted array (see 1)

*Now we have formula which stretched down returns row numbers for rows where is 1 in E:E7 SMALL($E$1:$E$7*ROW($E$1:$E$7),ROWS($D$1:$D$7)-SUM($E$1:$E$7)+ROW(D1)-ROW($D$1)+1)

*So we can use this formula from 6 in INDEX function. INDEX($D$1:$D$7,SMALL($E$1:$E$7*ROW($E$1:$E$7),ROWS($D$1:$D$7)-SUM($E$1:$E$7)+ROW(D1)-ROW($D$1)+1))

*If you try to stretch formula from 7 to more rows than is 1 values in E1:E7, you get an error there. This is solved by IFERROR function which returns empty text "" if there is an error.

PS: If your data in columns D and E are not starting in 1st row, you need to adjust the formula. But I'm sure, you know how by now.


text:
Q: Panda 3d Collada help c++ So I'm  new to Panda 3D in c++ and I have created collada files or dae files to show in panda 3d. When I view them in pview, they show up without color or texture. So if I press the L hotkey, color and texture shows up. I know this has to do with lighting. The same applies to after I do a dae2egg conversion. When I load my model into my actual program, it is white with no color. The shape is as it should be though. If I use set_color(...), color will appear, but only the solid color that I define then, of course. So I was curious as to how to correct this issue of no color.

A: Your object presumably has a material.  If you have a material, you need to add one or more light sources to your scene graph for it to show up; that's just how it works.  Alternatively, remove the material or disable it using set_material_off(1).


text:
Q: Twitter oauth php problems I'm writing some backend script for a twitter app and heres how it's going

*

*On the app you click a button that sends you to login.php on my server which logs into my database connects to twitter with my consumer key and secret: $to = new TwitterOAuth($consumer_key, $consumer_secret);
$tok = $to->getRequestToken();
$request_link = $to->getAuthorizeURL($tok);
and then writes the token and secret to the database, sets a session equal to the id in the database of the token and secret and then redirects to the "$request_link"

*You then go through the process of logging in and such on twitter and it redirects you to callback.php on my server

*Callback.php consists of logging into the database again, getting the new token and secret, and then writing the new token and secret to the database and then prompts you to go back to the app

*Then on the app, all I'm trying to do is access the basic credentials$to->get('account/verify_credentials') and it keeps coming back "could not authenticate you"
What am I doing wrong?? Thank you for all the help :)

A: This is how your last $to should be built before calling verify_credentials:
$to = new TwitterOAuth($consumer_key, $consumer_secret, $tok['oauth_token'], $tok['oauth_token_secret']);
$to->get('account/verify_credentials');

Make sure $tok is the oauth_token and oauth_token_secret you got from:
$tok = $to->getAccessToken();

I assume all the calls are from the same server so there should not be any time sync issues.


text:
Q: What's the manga with a exiled former sage? When I first read this it was only a chapter or two that was out.
Story goes a former sage/hero who looks like a child, lives in some mansion in the middle of nowhere with 4 maids who are some type of monster or demon. Some guy tries to rob the place with his old magic sword that's how you find out he is the former hero/sage who defeated the demon king or something like that.
it is not an isekai! The robber guy (just some scrub who dies to show who the MC and his minter maids really are) stole the sword. The sword originally belonged to the former hero/sage.
I read it on m.manganelo.com, the manga had a more serious tone to it like a Seinen, the MC was living in exile with the monster/demon maids. I am not really sure what else I can add since it was only 2 chapters released when I read it.

A: Since Guest hasn't elaborated on his answer, Shindou Yuusa to Maid Onee-san does match.

After defeating the Demon King and saving the world, Shion was exiled to the border. Here, the strongest Hero enjoyed his slow life with 4 capable oneesan maids.

In the first chapter of the manga, it establishes that Shion did indeed defeat the Demon King, but languishes in anonymity because royals took credit for the feat. It ends with the robber confronting him.
 (click to enlarge)
In the second chapter, we see the magic sword the robber wields.
 (click to enlarge)


text:
Q: Wireshark filter payload after completed dissection I'm trying to write a dissector where I need to filter the packets after a dissection depending on the values on a certain field.
For example, I have the following tree after my dissector is finished:
  Header
     Msg_Length: 10
     Car_Model: 1334
     Car_Speed: 25
     Error_Code: 1 (True)
  Content
     Distance_Left: 20
     Engine_Fail: 0

I would like to filter my capture so that Wireshark only displays the packets with a "Car_Speed" higher than 30. Preferably when writing something like: "my_proto.car_speed > 30"  in the display filter search box.
P.S I have several different types of messages in my capture and I'd like to be able to filter on different criteria in each. D.S


text:
Q: Why does an acoustic guitar body amplify all notes and not just certain ones? We all heard that acoustic guitar body acts as the amplifier of the sound created by wire plucking and strumming. This is because an acoustic guitar body is some kind of resonator.
Every resonator amplifies just certain frequencies while it inhibits all others.
So why then when an acoustic guitar is played we hear all notes amplified and not just certain ones? Shouldn't there be some notes louder and some other notes quieter?

A:
Every resonator amplifies just certain frequencies while it inhibits all others.

This is true only for very simple resonators. The shape of the guitar body is such that it has a different size at different angles. This corresponds to different resonant frequencies. In addition, the top has a supporting bracing that is very different on different models and is critical for the sound.
Furthermore, a guitar is nor necessarily a resonator, but a converter of the mechanical energy of the strings to the acoustic energy of the air. You are absolutely correct that a strong resonance at a certain frequency would help this frequency at the expense of other frequencies and thus would be detrimental for the sound of a broad spectrum instrument. Therefore the objective of the guitar design (counter intuitively at first) is not to create, but to avoid strong resonances.
There are two parts in a guitar relevant here. One is the top made either of softer ceder for a warmer sound or harder spruce for a brighter sound (sometimes a two-layer top has both). The purpose of the top is to move air with its large area thus converting the mechanical energy of the strings to the acoustical energy of the sound. However, the top radiates both forward and back, plus the sound radiated back is out of phase with the sound radiated forward.
The second important part is the body. Historically the most popular material for the body had been the Brazilian rosewood before Brazil prohibited exporting it. Similar results are achieved with the rosewood from India, Madagascar, and other areas. Mahogany is also popular along with other wood species.
The main purpose of the body is to reflect forward (through the sound hole) the sound emitted back by the top and do it while inverting the phase, so that the sound emitted by the sound hole would be in phase with the sound emitted forward by the desk. Thus the guitar body is not a resonator, but a phase inverter very similar to common speakers with a PORT. Phase inversion depends on the internal dimensions of the body and is a compromise in order to optimize all frequencies equally. Although this is more important for lower frequencies (again, similarly to speakers).
The materials, shape, and bracing have been perfected by generations of guitar makers resulting in specific sound signatures. One example is the 1A model with a ceder top by Jose Romirez. Its sound is mesmerizing.
Bass Reflex


text:
Q: ssh Tunnel (-w) "Tunnel device open failed." on mac os if i do
macos - ssh server1 -A
server1 - sudo -HE ssh root@server2 -w 0:0

all work fine
tun device up success
ifconfig -a

#contain

tun0: flags=4240<POINTOPOINT,NOARP,MULTICAST>  mtu 1500
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 500  (UNSPEC)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

but if i try to do it from macos (10.15.7 (19H15))
sudo ssh root@server2 -w 0:0
Tunnel device open failed.
Could not request tunnel forwarding.
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-42-generic x86_64)

with -vvv
debug1: sys_tun_open: /dev/tun0 open failed: No such file or directory
Tunnel device open failed.
Could not request tunnel forwarding.

it's fail(
please tell me what's wrong?
------ update -------
Now everything is sad, mac os does not contain Tun Tap software, found the tuntaposx project but it does not work, Apple "remakes" KPIs (kernel programming interfaces) https://developer.apple.com/support/kernel-extensions/
I have not found alternatives yet.
And it is not yet clear how realistic this is - if ssh relies on files, objects of tun / tap adapters

A: Enable tunneling on server2 by editing the config file /etc/ssh/sshd_config
Set PermitTunnel yes
Then restart SSH daemon


text:
Q: Regex para valores monetários Gostaria de saber como faço um regex para capturar um valor monetário com pontos e vírgulas. Ex: 7.300.250,00

A: Para validar se a string está neste formato, você pode usar ^[1-9]\d{0,2}(\.\d{3})*,\d{2}$:

*

*^ e $ são marcadores para o início e fim da string. Assim você garante que a string só vai ter o que está especificado na regex

*[1-9] é uma classe de caracteres. Os colchetes indicam que você quer qualquer coisa que esteja dentro deles. No caso, 1-9 é "qualquer dígito de 1 a 9"

*\d é um atalho para [0-9] (dígitos de 0 a 9) e {0,2} é um quantificador que significa "entre zero e duas ocorrências"

*

*portanto [1-9]\d{0,2} quer dizer que eu tenho um dígito de 1 a 9, seguido de zero, um ou dois dígitos de 0 a 9. Isso garante que a string não começa com zero

Em seguida, temos (\.\d{3})*:

*

*\. significa o caractere ponto (.). O ponto tem significado especial em regex (significa "qualquer caractere"), mas com a \ antes, ele "perde seus poderes" e vira um caractere comum.

*\d{3} são 3 ocorrências de qualquer dígito de 0 a 9

*

*a sequência "ponto seguido de 3 dígitos" está entre parênteses e em seguida temos o *, que significa "zero ou mais ocorrências". Isso quer dizer que podemos ter várias ocorrências (ou nenhuma) de "ponto seguido de 3 dígitos" (isso serve para verificarmos a sequência .300.250 da sua entrada). O * também verifica se há zero ocorrências, o que é útil para valores menores que 1000.

*por fim, temos a vírgula seguida de 2 dígitos (,\d{2})

Isso garante que a entrada estará no formato desejado. Veja aqui a regex funcionando.

Mas isso só valida se a string toda corresponde ao valor monetário. Se quiser extrair tais valores de um texto, basta modificar um pouco:
import re

texto = "lorem ipsum 7.300.250,00 blabla 123 etc 1.234,12 blabla 45"
print(re.findall(r"[1-9]\d{0,2}(?:\.\d{3})*,\d{2}", texto)) # ['7.300.250,00', '1.234,12']

Retirei o ^ e $, assim ele busca em qualquer parte do texto. E usando findall, ele retorna uma lista com todas as ocorrências. Só lembrando que os parênteses formam um grupo de captura, e neste caso findall retornaria somente os grupos, por isso tive que modificar para um grupo de não-captura, adicionando ?: depois do (.

Para obter o valor numérico, você pode simplesmente remover tudo que não for dígito e converter para int. Para isso, usamos a regex \D (que é o oposto de \d, ou seja, é tudo que não for dígitos de 0 a 9).
Com isso você terá a quantidade total de centavos. Abaixo eu transformo o valor para int, já que é melhor usar tipos inteiros para trabalhar com valores monetários. Se quiser o valor sem os centavos, basta dividir por 100, e se quiser o valor dos centavos, use o operador %:
import re

s = "7.300.250,00"
# se está no formato desejado
if re.match(r"^[1-9]\d{0,2}(\.\d{3})*,\d{2}$", s):
    # retira tudo que não for dígito e converte para int
    valor = int(re.sub(r"\D", "", s))
    print("Valor (quantidade total de centavos): {}".format(valor))
    print("Valor sem os centavos: {}".format(valor // 100))
    print("Valor dos centavos: {}".format(valor % 100))

A saída é:

Valor (quantidade total de centavos): 730025000
Valor sem os centavos: 7300250
Valor dos centavos: 0

Apenas um detalhe sobre o \d: ele também pode corresponder a outros caracteres que representam dígitos, como por exemplo os caracteres ٠١٢٣٤٥٦٧٨٩ (veja esta resposta para mais detalhes).
Exemplo:
s = "1٩,10"
if re.match(r"^[1-9]\d{0,2}(\.\d{3})*,\d{2}$", s):
    valor = int(re.sub(r"\D", "", s))
    print("Valor (quantidade total de centavos): {}".format(valor))

Eu usei o caractere ٩ (arabic-indic digit nine), que apesar de parecer com o dígito 9, é um outro caractere. A saída é:

Valor (quantidade total de centavos): 1910

Isso porque o \d também pega este caractere. Se quiser que somente os dígitos de 0 a 9 sejam considerados, troque \d por [0-9]:
if re.match(r"^[1-9][0-9]{0,2}(\.[0-9]{3})*,[0-9]{2}$", s):
    ... o resto é igual

Outro detalhe é que a regex só funciona para valores maiores que 1,00. Se quiser considerar também valores como 0,15 (15 centavos), tem que incluir uma condição para considerar somente um zero antes da vírgula:
if re.match(r"^(0|[1-9]\d{0,2}(\.\d{3})*),\d{2}$", s):
    ... o resto é igual

Agora eu uso alternância (o caractere |, que significa "ou") para indicar que antes da vírgula pode ter somente um zero, ou toda a expressão que já vimos anteriormente).

A: Você pode usar essa expressão:
 ^(([1-9]\d{0,2}(\.\d{3})*)|(([1-9]\.\d*)?\d))(\,\d\d)?


text:
Q: Oracle Linked Server in Azure SQL Database Managed Instance I am migrating my On Premise SQL Server to Azure SQL Database Managed Instance. But I have linked server to Oracle database in my SQL Server.
Can we create linked server to an On Premise Oracle Database in SQL Azure Database Managed Instance? Can anyone please guide?
If not, what is the alternative?

A: Linked servers in Managed Instance support a limited number of targets. Supported targets: SQL Server and SQL Database Not supported targets: files, Analysis Services, and other RDBMS. For more information, please read this documentation.
You may consider to try with SQL Server installed on Azure VM using a private VNET instead of using a Managed Instance.


text:
Q: Wait for 2 events. If one of them happens, do something How can I wait for 2 events in R so that if one of them happens, do something?
I want to wait for a window to be closed, with tkwait.window(myWindow), or wait for a variable to be changed, with tkwait.variable(myVar).
I tried this but it doesn't work
blablabla_1
tkwait.variable(myVar) | tkwait.window(myWindow)
blablabla_2

Any ideas?
Thank you

A: You can add a binding to your toplevel window to trigger something when that window gets closed (i.e., "destroyed"). What gets triggered is a change in the value of the variable you're waiting on.
Here I assume that your window is called myWindow and that the variable is called myVar.
    tkbind(myWindow, "<Destroy>", function() tclvalue(myVar) <- 2)

Above, myVar is assigned a 2, but you could use pretty much any value, as long as it leads to a change.


text:
Q: Is it necessary to use super().__init__() in this case? EDIT:
Oh, sorry guys. This question is a duplicate one, but not the dup of the linked one. I've found what i need in this question, maybe i should try more key word to search next time.Subclassing dict: should dict.init() be called?
In my case, I implement update, __setitem__ in the class StrKeyDict(dict), and __new__ inherited from dict may create a empty dict to ensure update can work, I don't think it's necessary to use super().__init__() again.
The code is from Fluent Python
example-code/attic/dicts/strkeydict_dictsub.py
import collections.abc

class StrKeyDict(dict):

    def __init__(self, iterable=None, **kwds):
        super().__init__()
        self.update(iterable, **kwds)

    def __missing__(self, key):
        if isinstance(key, str):
            raise KeyError(key)
        return self[str(key)]

    def __contains__(self, key):
        return key in self.keys() or str(key) in self.keys()

    def __setitem__(self, key, item):
        super().__setitem__(str(key), item)

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

    def update(self, iterable=None, **kwds):
        if iterable is not None:
            if isinstance(iterable, collections.abc.Mapping):
                pairs = iterable.items()
            else:
                pairs = ((k, v) for k, v in iterable)
            for key, value in pairs:
                self[key] = value
        if kwds:
            self.update(kwds)

When we use
d = StrKeyDict(a=1,b=2)

for example, to create instance d,  the real happening is:
1.Call __new__ which inherited from the superclass dict to create a empty dict instance
2.Call __init__ to initialize the instance
Just like I said, I implement update, __setitem__ in the class StrKeyDict(dict). So is it necessary to use super().__init__() here.
 Thank you!

A: In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class (dict).
It typically creates its underlying data structure.

A: The superclass' __init__() might or might not be doing something necessary to initialise it. If you know what's the case you can make an informed decision. If you don't know your best bet is to call it just in case.
Now if you don't call it because it is not necessary and the implementation of the base class changes in a way that make it necessary then you will have to fix it.
On the other hand there are a few cases where calling the superclass __init__() is a bad idea, for example if it does heavy calculations very specific to the superclass and that are different in the subclass.
FWIW my approach is always call super().__init__() unless I have a good reason not to call it.


text:
Q: Send raw image through JNI I'm building an Android app which uses a C++ core. I want to save images from Java through the core and JNI. I can get a byte array with the image data, but can't find a good way to send this through JNI. The jbyteArray I get on the JNI side isn't easily read with null bytes in the array.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100 /*quality*/, stream);
byte[] bytes = stream.toByteArray();

Any tips on how I do this?


text:
Q: cookie not in request with ios12 device so since I upgraded my phone to ios12, I'm unable to login to a site i'm developing (.net core 2); I login via facebook, and when facebook redirects to my endpoint, the cookies are not in the request, so when this line runs:
ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();

its always null, I checked the request and there is no cookies, while on other devices/pc the login works perfectly, its only ios12 thats giving me this problem atm
I saw another post that said to set cookies to SameSite = None
services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.Path = "/";
            options.Cookie.SameSite = SameSiteMode.None;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.SlidingExpiration = true;
            options.AccessDeniedPath = "/Welcome";
        });

but this did not work, anything else I could try?

A: so I fix it, it's a similar solution but if you use external login, you have to configure the external cookie to be SameSite = SameSiteMode.None
services.ConfigureExternalCookie(options =>
        {
            options.Cookie.SameSite = SameSiteMode.None;
        });

A: Expanding on Rob's answer...
Adding the following to my OpenIdConnect authentication block resolved the issue:
.Services.ConfigureExternalCookie(options => {
    options.Cookie = new Microsoft.AspNetCore.Http.CookieBuilder
    {
        SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None
    };
});

It looks like the fix will be added to 2.3 - External authentication failing on iOS 12 #2595


text:
Q: facebook group info using url For a public group https://www.facebook.com/groups/359484787507661/, i am getting the  group info by the followong code:
Group group = facebookClient.fetchObject("359484787507661", Group.class);

But I cant access the group info of the following public group url https://www.facebook.com/groups/therealheronarendramodi.
Group group = facebookClient.fetchObject("therealheronarendramodi", Group.class);

I got the following error:
Exception in thread "main" com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#803) Some of the aliases you requested do not exist: therealheronarendramodi (code 803, subcode null)

How to get facebook public group info by username? Is there any way to get group by it's username in restfb api?

A: You can use the Search API to get a group ID by a name:
/search?type=group&q={group-name}

Of course you may get more than one group, it´s a list of groups with their IDs.


text:
Q: How to manipulate AMP State based on responses from a drop down There is a nice example https://ampbyexample.com/advanced/linked_dropdowns/ on the AMP By Example site and this works well however I'm trying to understand how to make this more general and have more than two drop downs and am finding it hard to find the correct syntax to manipulate the AMP.setState.
In the example

<amp-list width="auto"
    height="25"
    layout="fixed-height"
    src="https://ampbyexample.com/json/linked_dropdowns.json">
    <template type="amp-mustache">
      Country:
      <select id="country"
        on="
      change:
        AMP.setState({
          cities: dropdown.items[0].countries.filter(x => x.name == event.value)[0]
        })">
        <option value="">Choose a country</option>
        {{#countries}}
        <option value="{{name}}">{{name}}</option>
        {{/countries}}
      </select>
    </template>
  </amp-list>
  <amp-list width="auto"
    height="25"
    layout="fixed-height"
    [src]="cities || 'https://ampbyexample.com/json/linked_dropdowns.json'"
    src="https://ampbyexample.com/json/linked_dropdowns.json">
    <template type="amp-mustache">
      City:
      <select [disabled]="!cities"
        disabled
        id="city">
        {{^cities}}
        <option value=""></option>{{/cities}} {{#cities.0}}
        <option value="">Choose a city</option>{{/cities.0}} {{#cities}}
        <option value="{{.}}">{{.}}</option>{{/cities}}
      </select>
    </template>
  </amp-list>
  <amp-state id="dropdown"
    src="https://ampbyexample.com/json/linked_dropdowns.json"></amp-state>

It had takes the result of the dropdown and usesd that to create a new element in setState of cities that is then used in the next amp-list.
I can't tell from the code and description how to repeat this so that when the second element is selected that allows a further selection (sub selection to be made).
The element:

on="change:AMP.setState({cities: dropdown.items[0].countries.filter(x => x.name == event.value)[0]})"

And

<amp-list width="auto"
    height="25"
    layout="fixed-height"
    [src]="cities || 'https://ampbyexample.com/json/linked_dropdowns.json'"
    src="https://ampbyexample.com/json/linked_dropdowns.json">

works but doesn't explain what is happening and how this could be used to take the second result and extract further options.
Anyone have any ideas or examples on how this might be made to work?

A: First, I am going to assume when you say "take the second result and extract further options" that you are intending to add an additional select option to filter (e.g. museums within a city).
In order to do this, first you need a data set which accommodates the additional information. This could be a modification of the current data set or an entirely new data set endpoint.
For ease sake, let's modify the current set of data like so. Once we have the new set of data, we can create the correct markup to show three dropdowns in a sequence (example on Codepen).
NOTE: Currently there is a bug that resets the city select right after selecting. My guess is there is something triggering the change event on the country select (which resets the city select), but did not have a chance to dig into the issue (help welcome).


text:
Q: How do you use induction with tactics/Isar in Isabelle/HOL? I am struggling to understand why each of the examples below either works or doesn't work and more abstractly how induction interacts with tactics vs Isar. I'm working on 4.3 in Programming and Proving in Isabelle/HOL (Dec 2016) on Windows 10 with the latest Isabelle/HOL (2016-1)
There are 8 cases: the lemma is either long (includes explicit name) or short, structured (using assumes and shows) or unstructred (using the arrows) and the proof is either structured (Isar) or unstructured (tactical).
theory Confusing_Induction
  imports Main
begin

(* 4.3 *)
inductive ev :: " nat ⇒ bool " where
  ev0: " ev 0 " |
  evSS: " ev n ⟹ ev (n + 2) "

fun evn :: " nat ⇒ bool " where
  " evn 0 = True " |
  " evn (Suc 0) = False " |
  " evn (Suc (Suc n)) = evn n "

1. Structured short lemma & structured proof
(* Hangs/gets stuck/loops on the following *)
(*
lemma assumes a: " ev (Suc(Suc m)) " shows" ev m "
proof(induction  "Suc (Suc m)" arbitrary: " m " rule: ev.induct)
*)

2. Unstructured short lemma & structured proof
(* And this one ends up having issues with
   "Illegal application of proof command in state mode" *)
(*
lemma " ev (Suc (Suc m)) ⟹ ev m "
proof(induction " Suc (Suc m) " arbitrary: " m " rule: ev.induct)
  case ev0
  then show ?case sorry
next
  case (evSS n)
  then show ?case sorry
qed
*)

3. Structured long lemma & structured proof
(* And neither of these can apply the induction *)
(*
lemma assumes a1: " ev n " and a2: " n = (Suc (Suc m)) " shows " ev m "
proof (induction " n " arbitrary: " m " rule: ev.induct)

lemma assumes a1: " n = (Suc (Suc m)) " and a2: "ev n " shows " ev m "
proof (induction " n " arbitrary: " m " rule: ev.induct)
*)

(* But this one can ?! *)
(*
lemma assumes a1: " ev n " and a2: " n = (Suc (Suc m)) " shows " ev m "
proof -
  from a1 and a2 show " ev m "
  proof (induction " n " arbitrary: " m " rule: ev.induct)
    case ev0
    then show ?case by simp
  next
    case (evSS n) thus ?case by simp
  qed
qed
*)

4. Unstructured long lemma & structured proof
(* And this is the manually expanded form of the Advanced Rule Induciton from 4.4.6 *)
lemma tmp: " ev n ⟹  n = (Suc (Suc m)) ⟹ ev m "
proof (induction " n " arbitrary: " m " rule: ev.induct)
  case ev0 thus ?case by simp
next
  case (evSS n) thus ?case by simp
qed

lemma " ev (Suc (Suc m)) ⟹ ev m "
  using tmp by blast

**5. Structured short lemma & unstructured proof*
(* Also gets stuck/hangs *)
(*
lemma assumes a: " ev (Suc (Suc m)) " shows " ev m "
  apply(induction  "Suc (Suc m)" arbitrary: " m " rule: ev.induct)
*)

6. Unstructured short lemma & unstructured proof
(* This goes through no problem (``arbitrary: " m "`` seems to be optional, why?)  *)
lemma " ev (Suc(Suc m)) ⟹ ev m "
  apply(induction  "Suc (Suc m)" arbitrary: " m " rule: ev.induct)
  apply(auto)
  done

7. Structured long lemma & unstructured proof
(* But both of these "fail to apply the proof method" *)
(*
lemma assumes a1: " n = (Suc (Suc m)) " and a2: " ev n" shows " ev m "
  apply(induction " n " arbitrary: " m " rule: ev.induct)

lemma assumes a1: " ev n "  and a2: " n = (Suc (Suc m)) " shows " ev m "
  apply(induction " n " arbitrary: " m " rule: ev.induct)
*)

8. Unstructured long lemma & unstructured proof
lemma " ev n ⟹  n = (Suc (Suc m)) ⟹ ev m "
  apply(induction  " n " arbitrary: " m " rule: ev.induct)
  apply(auto)
  done

end

A: I posted this to the cl-isabelle-users@lists.cam.ac.uk and received the following response from Larry Paulson. I've reproduced it below.

Thanks for your query. Some of your problems have to do with supplying premises to the induction in the correct way, but there are at least two big problems here.
(* 1. Structured short lemma & structured proof *)
(* Hangs/gets stuck/loops on the following *)

lemma assumes a: "ev (Suc(Suc m))" shows "ev m"
proof(induction  "Suc (Suc m)"  rule: ev.induct)

Doing it this way, your assumption is not visible, the goal is simply "ev m", so induction isn't applicable. But it's absolutely bad that this mistake causes the induction method to loop.
(* 2. Unstructured short lemma & structured proof *)
(* And this one ends up having issues with
   "Illegal application of proof command in state mode" *)
lemma "ev (Suc (Suc m)) ⟹ ev m"
proof(induction "Suc (Suc m)"  rule: ev.induct)
  case ev0
  then show ?case
    sorry
next
  case (evSS n)
  then show ?case sorry
qed

Here you are getting the error "Failed to refine any pending goal", which breaks the rest of the proof. The reason you are getting this error message is that for some reason there is a mismatch between the goals you have and the goals that the induction methods thinks you have. In fact this proof can be written straightforwardly, but its shape is quite unexpected. This is also very bad.
lemma "ev (Suc (Suc m)) ⟹ ev m"
proof(induction "Suc (Suc m)"  rule: ev.induct)
  show "⋀n. ev n ⟹
         (n = Suc (Suc m) ⟹ ev m) ⟹
         n + 2 = Suc (Suc m) ⟹ ev m"
    by simp
qed

Your (3,7,8) is the same problem as your (1) except that the induction method (correctly) fails. Clearly the argument "Suc (Suc m)" is causing the induction method to loop for some reason, as in your (5).
(* 6. Unstructured short lemma & unstructured proof *)
(* This goes through no problem (``arbitrary: " m "`` seems to be optional, why?)  *)

It is simply that only some proofs need "arbitrary", namely when the induction hypothesis involves variables that need to be generalised.
Your (7) can be written like this:
lemma assumes "ev n" and " n = (Suc (Suc m)) " shows " ev m "
  using assms
proof(induction " n " arbitrary: " m " rule: ev.induct)
  case ev0
  then show ?case
    sorry
next
  case (evSS n)
  then show ?case
    sorry
qed

That is, you can supply the assumptions to the proof as shown ("using"). We even get the right cases doing it this way.
We are in a new release phase, but I hope that the problems involving the induction method and non-atomic terms can be fixed promptly.
Larry Paulson