text:
Q: what ordinals were used in proving unique factorization over $\mathbb{Z}$ I don't fully understand this other question, but there's a clear relationship between logic and number theory
the strength of saying "each sentence of true arithmetic has a recursive proof"
Here's a statement: every integer $n \in \mathbb{Z}\backslash\{0\}$ has a unique prime factorization which could be thought of as defining a tree structure on the integers.
For a theoretical computer scientist this is just like any other tree, which can be iterated through or breadth-first search or DFS, etc.  The fact that the nodes are integers is almost immaterial.
All I know is that certain number theory statements could be be proven with first order logic and others with second order logic, but I doubt anyone details which logic structures were actually used.
Even more basic, does the Euclidean algorithm define a recursive structure on pairs of integers or sequence of integers?

A: Let me first address the specific issue of how statements in number theory correspond to recursive "infinitary tree proofs."
Well, first of all, the point is that every true statement about natural numbers has a recursive proof. So asking whether something like the (statement of the effectiveness of the) Euclidean algorithm has a recursive proof, will always receive the answer "yes." Here's an example of a recursive proof of the Euclidean algorithm's correctness and termination:

*

*For each specific natural number $n$, we can prove using PA that the Euclidean algorithm "works" on $n$ (or that $n=0$). Moreover, we may effectively find the first proof (in some reasonable indexing) of this fact, $\pi_n$.

*The function $f$ taking $n$ to $\pi_n$ - "search until you find a proof that EA works for $n$" - is recursive; and so constitutes a "level-one" recursive proof. That is, we only need one use of the recursive $\omega$-rule.

*The overall structure of this proof is a tree: it has a root, branching $\omega$-many times, and at each branch we have a usual first-order proof. (Note that this tree really doesn't come from the details of the algorithm at all, just the fact that PA can prove each specific instance of it working; the complexity of the algorithm is not necessarily related to the complexity of the recursive proof.)
Note that indeed, this picture applies to any true $\Pi^0_1$ sentence (in particular, it works regardless of whether that sentence is provable in PA alone). More complicated statements require more uses of the recursive $\omega$-rule, leading to more complicated trees of rank up to $\omega^2$ (I believe that bound is sharp).
EDIT: By a small tweak, we can in fact show that any true $\Sigma^0_3$ sentence $\exists x\forall y\exists z\varphi(x, y, z)$ (with $\varphi$ having only bounded quantifiers) has a recursive proof of height 1, as follows:

*

*Begin the proof by guessing correctly the right value of $x$. We don't have a good way of knowing what $x$ should be, but this is just one bit of information - so "coding it in" to the recursive proof doesn't break anything. (This is exactly analogous to how the set $\{x:$ the Riemann hypothesis is true and $x=0\}$ is computable, even though we don't know if it is $\emptyset$ or $\{0\}$.)

*Now, consider a function $f$ which - on a given $y$ - searches for some $z$ such that $\varphi(x, y, z)$ holds together with a proof ("certificate") of this fact. Since such a $z$ always exists, and whether $\varphi(x, y, z)$ holds can be effectively tested since $\varphi$ has only bounded quantifiers, a proof that such a $z$ works also exists, and moreover the function $f$ can be taken to be recursive.

*But then this $f$ (basically) constitutes a recursive proof.
So it's at the $\Pi^0_3$ level that things first can become interesting - the idea being that we somehow need to "guess correctly" at the existential quantifier in the middle not once but infinitely many times, one for each possible value of the outermost "$\forall$;" so the "guess $x$ correctly" trick above doesn't work. Moreover, telling whether a given guess works is a $\Pi^0_1$ (noneffective, that is) question, so even if by luck we happen to have guessed the right witness, we can't obviously verify its correctness, and that's necessary for a recursive proof.
So this is the subtlety of the Shoenfield completeness theorme: the naive idea of just "bootstrapping" up the $\Pi^0_1$ idea (which does work if we replace the recursive $\omega$-rule with the full $\omega$-rule, and then every true sentence has a proof of finite height!) doesn't work, and something more complicated has to be done.

Now what do ordinals have to do with all this? Well, the linked question is about the difficulty of proving "Every true statement has a recursive proof," and specifically asks how much transfinite induction is needed to prove this (and the stronger statement that only height $\omega^2$ is needed). Well, in order to formalize transfinite induction principles in PA, we need some way to talk about ordinals (e.g. how do you write "$\epsilon_0$ is well-founded" in the language of arithmetic alone?), so this is what the "appropriate coding of ordinals" is about. And if you look at Franzen's paper, you'll see how this shows up in the statement and proof of the result.
This, of course, leaves off an important question: why are transfinite induction principles the right metric to use to gauge how hard it is to prove something? This is a general theme in proof theory (and elsewhere), that transfinite induction principles help you prove statements about the existence (or non-existence) of well-founded labelled trees with certain properties; e.g. here it's about the existence of well-founded labelled trees which correspond to recursive proofs, while in ordinal analysis it's about the nonexistence of finite labelled trees corresponding to proofs of $0=1$ from specific families of axioms.
In particular, the analysis of the Euclidean algorithm case is provable in PA alone (and indeed much less), so no ordinal strength at all is needed to show that that statement has a recursive proof (and indeed, I believe the vast majority of statements in basic number theory will have recursive proofs provably in PA alone, although I'm not an expert here so don't quote me on that).


text:
Q: How can I exclude an object from my array so a foreach loop avoids it? I'm using a foreach loop to get images from the graph API in facebook.
Here is the return from my json decode:
{
   "data": [
      {
         "name": "Person 1",
         "id": "12345678",
         "picture": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/123456789_123456_789456.jpg"
      },
      {
         "name": "Person 2",
         "id": "12345679",
         "picture": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/123456789_123456_789457.jpg"
      }
   ],
   "paging": {
      "next": "https://graph.facebook.com/me/friends?access_token=.....&fields=name,id,picture&limit=5000&offset=5000&__after_id=..."
   }
}

Here's my PHP:
        $url  = "https://graph.facebook.com/". $uid ."/friends?access_token=". $access_token ."&fields=name,id,picture";
        $users = json_decode(file_get_contents($url));

        echo $access_token .'

';

        foreach ($users as $name => $value) {
            foreach ($value as $entry) {
                //Loop for profile pics
                if ($entry->picture) {
                    echo 'id . '" target="_blank">' . 'picture . '" class="profile-thumb' . $entry->name . '" id="'. $entry->id .'">';
                }
            }
        }

This is fine as it pulls the paths to the images correctly, but it gives me this error:
Notice: Trying to get property of non-object in C:\inetpub\wwwroot\feref.com\facebook\test-app\friends.php on line 50

Which I assume is as a result of the 'paging' object in the array.
How can I prevent this error? That is, how can I exclude the 'paging' object from my loop?

A: Try if (isset($this->picture)) instead. That'll test if the picture property exists at all.

A: Rather than iterating over your entire result, only iterate over the data array.
Add this line after you declare $users;
$data = $users->('data');

Then do
foreach($data as $entry){
    if(isset($entry->picture)){
        echo ...
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opening Other Email Accounts using MailKit I'm trying to access to an IMAP account (Not My Default) using MailKit (created by jstedfast)
I can access my exchange email account using Imap fine and loop through the folders.
What I really need to do is access other email accounts I have rights to so I can monitor them for unread email that matches a certain query
I cannot figure out how to open a different mailbox then my own using my credentials.
In outlook I just add the additional mailboxes
How would be the best way to do it without using the other email account user?

A: You aren't limited to a single ImapClient instance, so you can just create multiple ImapClient objects to connect to multiple accounts (1 account per ImapClient).


text:
Q: StoryBoard Autoreverse Binding Is there anyway to modify the Autoreverse property of a story board. I'd like to bind it to a control's property but can't find a way...
My code so far:
public class MyProgressBar : ProgressBar
{
    public bool IndeterminateAutoReverse
    {
        get { return (bool)GetValue(IndeterminateAutoReverseProperty); }
        set { SetValue(IndeterminateAutoReverseProperty, value); }
    }

    // DependencyProperty as the backing store for IndeterminateAutoReverse
    public static readonly DependencyProperty IndeterminateAutoReverseProperty = DependencyProperty.Register(
        "IndeterminateAutoReverse",
        typeof(bool),
        typeof(MyProgressBar),
        new PropertyMetadata(true)
    );
}

And the style in Theme\Generic.xaml:
<Style TargetType="{x:Type local:MyProgressBar}">
        <Setter Property="Foreground" Value="#FF06B025" />
        <Setter Property="Background" Value="#FFE6E6E6" />
        <Setter Property="BorderBrush" Value="#FFBCBCBC" />
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MyProgressBar}">
                    <Grid x:Name="TemplateRoot">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Indeterminate">
                                    <Storyboard x:Name="TheStoryBoard" RepeatBehavior="Forever" AutoReverse="{Binding IndeterminateAutoReverse, RelativeSource={RelativeSource TemplatedParent}}">
                                        <PointAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransformOrigin)"
                                                                      Storyboard.TargetName="Animation">
                                            <EasingPointKeyFrame KeyTime="0" Value="-0.5,0.5" />
                                            <EasingPointKeyFrame KeyTime="0:0:1" Value="0.5,0.5" />
                                            <EasingPointKeyFrame KeyTime="0:0:2" Value="1.5,0.5" />
                                        </PointAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Background="{TemplateBinding Background}" />
                        <Rectangle x:Name="PART_Track" />
                        <Grid x:Name="PART_Indicator"
                              ClipToBounds="true"
                              HorizontalAlignment="Left">
                            <Rectangle x:Name="Indicator"
                                       Fill="{TemplateBinding Foreground}" />
                            <Rectangle x:Name="Animation"
                                       Fill="{TemplateBinding Foreground}"
                                       RenderTransformOrigin="0.5,0.5">
                                <Rectangle.RenderTransform>
                                    <TransformGroup>
                                        <ScaleTransform ScaleX="0.25" />
                                    </TransformGroup>
                                </Rectangle.RenderTransform>
                            </Rectangle>
                        </Grid>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsIndeterminate" Value="true">
                            <Setter Property="Visibility" TargetName="Indicator" Value="Collapsed" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

With this, AutoReverse is always false...
I also tried to change it withing the ControlTemplate Triggers like that:
<ControlTemplate.Triggers>
    <Trigger Property="IsIndeterminate" Value="true">
        <Setter Property="Visibility" argetName="Indicator" Value="Collapsed" />
    </Trigger>
    <Trigger Property="IndeterminateAutoReverse" Value="true">
        <Setter Property="AutoReverse" TargetName="TheStoryBoard" Value="True" />
    </Trigger>
</ControlTemplate.Triggers>

But it doesn't compile...
Any idea ?

A: Unfortunately binding inside a ControlTemplate animation is not supported (source: https://msdn.microsoft.com/en-us/library/ms742868.aspx#Anchor_9).
You can achieve what you want by using two different states. Here's a working sample:
[TemplateVisualState(Name = "IndeterminateAutoReverse", GroupName = "CommonStates")]
public class MyProgressBar : ProgressBar
{
    static MyProgressBar()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyProgressBar), new FrameworkPropertyMetadata(typeof(MyProgressBar)));
    }

    public MyProgressBar()
    {
        var isIndeterminateProperty = DependencyPropertyDescriptor.FromProperty(IsIndeterminateProperty, typeof(MyProgressBar));
        isIndeterminateProperty?.AddValueChanged(this, (s,e) => SetIndeterminateState());
    }

    public bool IndeterminateAutoReverse
    {
        get { return (bool)GetValue(IndeterminateAutoReverseProperty); }
        set { SetValue(IndeterminateAutoReverseProperty, value); }
    }

    public static readonly DependencyProperty IndeterminateAutoReverseProperty =
       DependencyProperty.Register(
           "IndeterminateAutoReverse",
           typeof(bool),
           typeof(MyProgressBar),
           new PropertyMetadata(true, (o, e) => (o as MyProgressBar)?.SetIndeterminateState()));

    private void SetIndeterminateState()
    {
        if (!IsIndeterminate)
        {
            return;
        }

        VisualStateManager.GoToState(
            this,
            IndeterminateAutoReverse ? "IndeterminateAutoReverse" : "Indeterminate",
            true);
    }
}

Generic.xaml
<Style TargetType="{x:Type local:MyProgressBar}">
    <Setter Property="Foreground" Value="#FF06B025" />
    <Setter Property="Background" Value="#FFE6E6E6" />
    <Setter Property="BorderBrush" Value="#FFBCBCBC" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyProgressBar}">
                <Grid x:Name="TemplateRoot">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Indeterminate">
                                <Storyboard RepeatBehavior="Forever">
                                    <PointAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransformOrigin)"
                                                                  Storyboard.TargetName="Animation">
                                        <EasingPointKeyFrame KeyTime="0" Value="-0.5,0.5" />
                                        <EasingPointKeyFrame KeyTime="0:0:1" Value="0.5,0.5" />
                                        <EasingPointKeyFrame KeyTime="0:0:2" Value="1.5,0.5" />
                                    </PointAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="IndeterminateAutoReverse">
                                <Storyboard AutoReverse="True" RepeatBehavior="Forever">
                                    <PointAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransformOrigin)"
                                                                  Storyboard.TargetName="Animation">
                                        <EasingPointKeyFrame KeyTime="0" Value="-0.5,0.5" />
                                        <EasingPointKeyFrame KeyTime="0:0:1" Value="0.5,0.5" />
                                        <EasingPointKeyFrame KeyTime="0:0:2" Value="1.5,0.5" />
                                    </PointAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Border BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}" />
                    <Rectangle x:Name="PART_Track" />
                    <Grid x:Name="PART_Indicator"
                          ClipToBounds="true"
                          HorizontalAlignment="Left">
                        <Rectangle x:Name="Indicator"
                                   Fill="{TemplateBinding Foreground}" />
                        <Rectangle x:Name="Animation"
                                   Fill="{TemplateBinding Foreground}"
                                   RenderTransformOrigin="0.5,0.5">
                            <Rectangle.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform ScaleX="0.25" />
                                </TransformGroup>
                            </Rectangle.RenderTransform>
                        </Rectangle>
                    </Grid>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsIndeterminate" Value="true">
                        <Setter Property="Visibility" TargetName="Indicator" Value="Collapsed" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

MainWindow.xaml
<Grid>
    <local:MyProgressBar IsIndeterminate="True" IndeterminateAutoReverse="{Binding IsChecked, ElementName=TheCheckBox}"/>
    <CheckBox x:Name="TheCheckBox" />
</Grid>


text:
Q: Declaring variables from object property I have a simple object with constants.
{
  KEY1: "value1",
  KEY2: "value2"
}

I want to make them accessible globally.

I make this object globally, use it like Config.KEY1
But I am trying to find a way so that I only use KEY to get the value.
app.js
const express = require('express')
const app = express()

//load app config variables
const config = require('config') //this returns the plain object with config keys and dvalues
...config //oops, can't do this :(

If I could do somthing like below, I think it should work.
const express = require('express')
const app = express()

//load app config variables
const KEY1 = "value1"
const KEY2 = "value2"

A: Destructure the config object when you import it, so that you have standalone variable names:
const { KEY1, KEY2 } = require('config');

You can also combine the config with the global object, allowing you to use those standalone variable names anywhere without importing the config everywhere, but it's not such a good idea IMO:
const util = require('./util');
Object.assign(global, util);

(make sure you don't have any properties that conflict with properties on the global object)


text:
Q: how to enlarge the size of an image fetched from database using only php I want to know is there any inbuilt function in php through which I can display an image greater than the size stored in database(i.e. greater than the original size).
I know it can be done using the HTML/CSS properties height and width but I want it done through php only.
I tried imagecreatefromjpeg($filename); but it takes file or directory name in place of $filename and my image is in a database.
Here is a part of my code:
    while( $result=mysqli_fetch_array($runquery))
    {
        echo'<img src="data:image/jpeg;base64,'base64_encode($result['image']).'"/>';
    }

A: Load your image with imagecreatefromstring. Then resize it with imagecopyresized.
Also I would suggest you to only save the paths to your image in the database.

A: Get Imagick ready and call following function
bool Imagick::setImageExtent ( int $columns , int $rows )

Reference: Imagick::setImageExtent


text:
Q: Zsh's standard completion works fine, so why do people recommend to load compinit module? If I put these lines and nothing else in my ~/.zshrc I get all the completion features I expected.
# For autocompletion with an arrow-key driven interface
zstyle ':completion:*' menu select
# report what kind of completion zsh doing
zstyle ':completion:*' format 'Completing %d'
# show ls style colours on file completions
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
# report position when autocompleting lists bigger than available screen
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s%p

So why do people recommend you load compinit?, i.e.
autoload -Uz compinit
compinit

# completion  config directives  go here

My testing shows it doesn't improve zsh's completion, and it doesn't fix the zsh completion that is broken but works in bash (i.e. curl).

A: The completion system activated by compinit does improve the basic one. The basic system is for the most part not aware of context, and completes only file names almost everywhere. The "new" completion system activated by compinit knows that it should complete options for many commands when the argument starts with -, that it should complete commands in $PATH (in root's PATH, even) rather than file names after sudo, that it should complete host names after ssh, etc.
I don't know why you say that the completion for curl is "broken". Maybe it's because it isn't installed? Older versions of zsh had completion for curl, but newer versions rely on the completion script included in the curl distribution. Check that your curl installation includes _curl somewhere under /usr/local/share/zsh/functions or /usr/share/zsh/functions (some distributions are missing this file).


text:
Q: Flexbox don't resize when use % for height for child div elements Currently I have these codes
.tomorrow
  display: flex

  .imagediv
    width: 100%
    height: 200px

In this case, the container class '.tomorrow' resizes itself to fit every of it's child's height.
But, in the next case, it does not resize itself anymore:
.tomorrow
  display: flex

  .imagediv
    width: 100%
    height: 100%  // the issue is right here

Is there any way that we can make the container class '.tomorrow' fits when we put the % value into the '.imagediv' 's height? Thank you.


text:
Q: Flutter app not building due to gradle issue I am facing a problem while importing an already made flutter app in my android studio and IntelliJ IDE.
Whenever I try to build any flutter app, it says:
FAILURE: Build failed with an exception.

* Where:
Script '/Users/krishnakc/Downloads/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1102

* What went wrong:
Execution failed for task ':app:compileFlutterBuildRelease'.
> Process 'command '/Users/krishnakc/Downloads/flutter/bin/flutter'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 46s
Running Gradle task 'assembleRelease'...                          217.7s
Gradle task assembleRelease failed with exit code 1
Process finished with exit code 1

But when I create any new flutter APK by wizard then it builds successfully.
What I did:
Cleaning flutter, deleting flutter whole project, file, and reinstalling flutter properly. Reinstalling gradle and android studio. I tried all possible solutions for it and researched the internet so much and I cannot build app. Please help me regarding this. I am using macbook pro 10.15.7
Thank you


text:
Q: Converting Full Month Name String into MMM format I am getting month number as integer and want to convert it to MMM format
here is what i have tried but its giving me full month name
public String getMonth(int month) {
         return new DateFormatSymbols().getMonths()[month-1];
            }

it gives me April in return  but i want Apr

A: The correct way to do this is
new DateFormatSymbols().getShortMonths()[month-1];

as described in the Javadoc

A: Use subString method or you can change Date Formatter.
public String getMonth(int month) {
         return new DateFormatSymbols().getMonths()[month-1].subString(0,2);
            }

Using Date Formatter:
public String getMonth(int month) {
             return new DateFormatSymbols().getShortMonths()[month-1].subString(0,2);
                }

A: You can try using Calendar and SimpleDateFormat as below...
public String getMonth(int month) {

    String monthName="";

    try {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, monthNumber);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
        simpleDateFormat.setCalendar(calendar);
        monthName = simpleDateFormat.format(calendar.getTime());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return monthName;
}


text:
Q: WPF - Set string as asterisk (everything) i have a rpcservice and i can query items, but now i want to query a container's name with a location on the container.
Like:
Table hase 2 location: A side = 321323 ; and B side = 321324
For now i have itemId and everything defined for my command, but it works
only if itemId is given,but on the webside if i just put * as itemId
it loads everything. With query if i set itemId as * and run the method it
want to start to find itemId with name = *
My first method was that:
        Command_queryItem cmd = new Command_queryItem();
        cmd.itemId = "*";
        cmd.locationInContainer = query.Text;
        res.Text = rpc.executeCommand(cmd.GetCommand, cmd.GetParameters);

So i made a new one:
        Command_queryItem cmd = new Command_queryItem();
        char[] fff = new char[0];
        fff[0] = '*';
        cmd.itemId = fff.ToString();
        cmd.locationInContainer = query.Text;
        res.Text = rpc.executeCommand(cmd.GetCommand, cmd.GetParameters);

But it still doesn't work. Any ideas?
Thank you in advance!


text:
Q: How to prove that $\sin^2{x} \leq 2|x| $ for all $x \in \mathbb R$ using derivatives I'm supposed to define a function, $f(x) = \sin^2{x} - 2|x|$ and take the $1^{st}$ derivative to find the sign of $f'(x)$. Since $|x|$ is not diff at $0$, I'm stuck and have no idea how to approach it after taking the derivative. Could you please give a hint?

A: You just need to show that $f(x)\le 0$ for all $x$. As Martin R mentions in the comments, the statement is true for $x=0$, and since $f(-x)=f(x)$, it suffices to prove the statement is true for $x>0$. So consider any $x_0>0$. Since $f$ is continuous on $[0,x_0]$ and differentiable on $(0,x_0)$, the mean value theorem ensures that there is an $\alpha\in(0,x_0)$ such that
$$
f(x_0)=f(0)+f'(\alpha)x_0
$$
On the interval $(0,\infty)$, we have $f'(x)=2\sin x\cos x-2=\sin(2x)-2$, and so $f'(\alpha)$ is negative. Thus, $f(x_0)=f(0)+f'(\alpha)x_0<f(0)=0$, completing the proof.


text:
Q: How to identify source of requests and which files are being accessed in Firebase? We use Firebase for file storage to host images and other media for our users. I'm seeing large spikes in our Cloud Storage egress costs. It looks like Networking Traffic Egress GAE/Firebase Storage is the culprit. I'm trying to understand where these requests are coming from and what files are being accessed during these spikes. Which logging would I need to setup to answer this question and debug the cause for these spikes.

A: Data Access Audit Logs are the right logs to determine this. See https://cloud.google.com/logging/docs/audit
You can turn them on by following these instructions: https://cloud.google.com/logging/docs/audit/configure-data-access
IAM & Admin > Audit Logs > search for "storage" > For Cloud Storage for Firebase API and Google Cloud Storage, turn on Data Read and Data Write in the right panel > hit save
Now that you're collecting them, you can view the logs by following instructions here: https://cloud.google.com/logging/docs/audit
Logging > Logs Explorer > In Query > Resource > pick GCS Bucket for your project
In the Log name filter, select data_access


text:
Q: GLFW fails to load all GL ES 2.0 functions I am trying to set up GLFW to create window and OpenGL ES 2.0 context,as I need something out of the box to manage input callbacks etc.
The problem is this,if I use the following setup:
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    glfwindow  = glfwCreateWindow(width, height, "Window Title", NULL, NULL);
    if (!glfwindow)
    {
        glfwTerminate();
        exit(1);
    }

    glfwMakeContextCurrent(glfwindow);

Using GLFW_NATIVE_CONTEXT_API for GLFW_CONTEXT_CREATION_API hint gives me the following info on the vendor:

GL version:OpenGL ES 3.2 NVIDIA 368.69 GL vendor:NVIDIA Corporation GL
  renderer:GeForce GTX 960M/PCIe/SSE2 GLSL version:OpenGL ES GLSL ES
  3.20

Then it fails even to create a shader (glCreateShader()) returns 0.
But if instead that hint flag I use GLFW_EGL_CONTEXT_API , I manage to get through of most of the GL routines like shaders loading,program compile and link,GL VBO setup etc.But then I fails on glDrawElements().
And if I print the vendor info with this setup I can see this:

GL version:4.5.0 NVIDIA 368.69 GL vendor:NVIDIA Corporation GL
  renderer:GeForce GTX 960M/PCIe/SSE2 GLSL version:4.50 NVIDIA

So,it is quite weird to me that when EGL should suppossedly be the underlying API for context creation,I get desktop OpenGL set.
Also if I try to retrieve function pointer for glDrawElements manually,it returns null.
PFNGLDRAWELEMENTSPROC func = reinterpret_cast<PFNGLDRAWELEMENTSPROC>
(eglGetProcAddress("glDrawElements"));

I would like to understand what can be the problem and how to use GLFW for GL ES context creation the right way.

A: As no one answered my own question,and because I had figured out the root of the problem a long time ago,here is the explanation:
GLFW works just fine for GLES context initialization.The problem is with the libraries linked.One must not link with opengl32.lib when emulating GLES on Windows.In my case I use PowerVR SDK and its ES2 and ES3 libs.Therefore,the following libs are mandatory:
glfw3.lib
libEGL.lib
libGLESv2.lib
In my linker,because by default I was using desktop OpenGL,I was also linking with opengl32.lib ,which had probably a precedence before the other GL libs.Make sure you exclude it when running GLES on the desktop platform.


text:
Q: Adding numbers with a click function Good evening,
I am trying to create a simple app to calculate insurance rates. The 1st input is for the value of the item (whole numbers), the 2nd is for the insurance rates which will be in decimal numbers, once the numbers are entered it will do some additional math to get the charges and then post the total on a document on the web page. I can't seem to get the total to appear on the input field. Any help will be greatly appreciated being that this is my very 1st project.
Thank you,
Edwin

total.addEventListener('click',() => {
    const rte1 = parseFloat(document.getElementById('val$').value);
    const rte2 = parseFloat(document.getElementById('valRate').value);
    const surCharge = rte1 * rte2;
    const ept = surCharge * .036;
    const totalCharge = surCharge + ept;

    document.getElementById('price').innerHTML = totalCharge;
});

Enter Value:

 <input id="val$" type="text" name="rate1">

Enter Insurance Rate:

 <input id="valRate" type="text" name="rate2">

 <button onclick="total" type="button" class="btn btn-primary active d-block mx-auto mt-4">Calculate</button>

Total charges including IPT:

 <input id="price" type="text">

A: Just use onClick in the HTML element to call a Javascript function:

function total() {
    const rte1 = parseFloat(document.getElementById('val$').value);
    const rte2 = parseFloat(document.getElementById('valRate').value);
    const surCharge = rte1 * rte2;
    const ept = surCharge * .036;
    const totalCharge = surCharge + ept;

    document.getElementById('price').value = totalCharge;
};

Enter Value:

 <input id="val$" type="text" name="rate1">

Enter Insurance Rate:

 <input id="valRate" type="text" name="rate2">

 <button onclick="total()" type="button" class="btn btn-primary active d-block mx-auto mt-4">Calculate</button>

Total charges including IPT:

 <input id="price" type="text">

You also need to use .value instead of .innerHTML to set the text in an input.

A: document.getElementById('price').innerHTML = totalCharge;

should be
document.getElementById('price').value = totalCharge;


text:
Q: How to retrieve multiple NDJSON objects from the same file using ArduinoJson? I am trying to use ArduinoJson to parse Google's quickdraw dataset, which contains .ndjson files with multiple objects inside. I figured how to retrieve the first of the objects in the file using the following simple code:
DeserializationError deserialization_error = ArduinoJson::deserializeJson(doc, as_cstr);
if (deserialization_error) {
    printf("deserializeJson() failed: %s\n", deserialization_error.c_str());
}

However, this only parses the first object in the ndjson file.
According to the website, I get the sense that something else should happen automatically:
NDJSON, JSON Lines
When parsing a JSON document from an input stream, ArduinoJson stops reading as soon as the document ends (e.g., at the closing brace).

This feature allows to read JSON documents one after the other; for example, it allows to read line-delimited formats like NDJSON or JSON Lines.

{"event":"add_to_cart"}
{"event":"purchase"}

Is there some way to get the byte length of the parsed object to I can continue using the cstring to parse consecutive objects? I did print out the cstring and it does contain the entirety of the ndjson file.

A: I found it.
just call multiple times:
  DeserializationError error = deserializeJson(doc, sceneFile);

or:
  deserializeJson(docline1, sceneFile);

  deserializeJson(docline2, sceneFile);

  deserializeJson(docline3, sceneFile);


text:
Q: TypeError: lemmatize() missing 1 required positional argument: 'word (WordNetLemmatizer) I am facing a problem with WordNetLemmatizer.
What I am doing is filtering out useless words like int and int + str by using CountVectorizer.
Without further ado. My code is following:

letters_only is a function to give me Fales if a word contains int, or int + str

groups = fetch_20newsgroups()
cleaned = []
all_names = set(names.words())

for post in groups:
  cleaned.append(''.join([lemmatizer.lemmatize(word.lower())
  for word in post.split()
  if letters_only(word)
  and word not in all_names]))

Just in case, I tried this as well:
for post in groups.data:
  for word in post.split():
    if letters_only(word) and word not in all_names:
      cleaned.append(''.join(lemmatizer.lemmatize(word.lower()))

Two separate codes give me the same error which is "TypeError: lemmatize() missing 1 required positional argument: 'word".

A: I'm not fully certain, because you didn't include the piece of code where lemmatizer was initialised, but I think this is the error you're experiencing:
from nltk import WordNetLemmatizer

lemmatizer = WordNetLemmatizer
word = "Arguments"
print(lemmatizer.lemmatize(word.lower()))

Which outputs:
Traceback (most recent call last):
  File "c:\...\nltk_70755449.py", line 11, in <module>
    print(lemmatizer.lemmatize(word.lower()))
TypeError: lemmatize() missing 1 required positional argument: 'word'

As you can see from the WordNetLemmatizer documentation, you must initialize the class WordNetLemmatizer, and then call the class method lemmatize on that. Right now, lemmatizer is just a reference to the class WordNetLemmatizer, instead of an instance of this class. Luckily, this is an easy fix, as we can initialize this class with WordNetLemmatizer():
from nltk import WordNetLemmatizer

lemmatizer = WordNetLemmatizer() # <- Notice the class initialization with ()
word = "Arguments"
print(lemmatizer.lemmatize(word.lower()))

This outputs:
argument

That should solve your problem.


text:
Q: Null-coalescing operator in a foreach declaration using C#7 I was looking at this code example in C# 7.0 and I was not sure about what was going on under the hood and the performance of this loop.
foreach (var c in text ?? throw new ArgumentNullException(nameof(text)))
{
    ...
}

My questions:

*

*Does the conditional statement get hit once or multiple times (on
each iteration)?

*The new syntax looks different, what are the benefits to doing it this way?

A: In terms of "how foreach works", conditional statement will only be calculated once.
You may want to read more about how foreach loops work in these questions:
How do foreach loops work in C#?
Does foreach evaluate the array at every iteration?
Thanks to Svek for explaining that it is a new C# 7.0 feature, which will be released after Visual Studio 2017 RC:
http://structuredsight.com/2016/09/01/c-7-additions-throw-expressions/
I think that "what are benefits" is a sort of opinion-based question.
In my opinion, it brings nothing good and is just ugly in terms or code readability.
I would recommend using a widely-used common good practice:
if (text == null) // or string.IsNullOrEmpty for strings
    throw new ArgumentNullException(nameof(text));

foreach (var c in text)
{
    // ...
}

Probably, we will see null-coalescing + throw exception usage in a couple years and it will become a new standard :)

A: You should understand foreach inner code for understanding this C# feature. A right part of expression in foreach statement must implement IEnumerable(<T>) interface, and whole loop is, internally, a simple while, something like this:
// here can be NullReferenceException
var en = text.GetEnumerator();
while(en.MoveNext())
{
    var c = en.Current;
    {
        ...
    }
}

As you can see, there is a point in this code the NRE can occur, so you need to check the enumerable before entire loop or Enumerable extensions class, like this:
if (text.IsNullOrWhitespace())
{
    throw new ArgumentNullException(nameof(text));
}

// while loop here or text.SomeLinqCodeHere()

There are some lines of code here which aren't really unnecessary, adding some entropy without real value. In case of simple foreach it really opinion-based decision about code standards, but the real purpose of this feature is chaining it with other new things in C#7, like ?. operator, like this:
int? length = customers?.Length ?? throw new ...;
Customer first = customers?[0] ?? throw new ...;
int? count = customers?[0]?.Orders?.Count() ?? throw new ...;

In such cases throwing the exception is similar to comment at the end of the line of code:
int? length = customers?.Length; // should not be null
Customer first = customers?[0]; // should not be null
int? count = customers?[0]?.Orders?.Count(); // should not be null

but it adds some strict contract-like rules for your code.
As for the performance for foreach loop with such expressions, as already said, it doesn't suffer as getting the enumerator occurs only once, and before the real loop.


text:
Q: Monitoring replication status from the subscriber I have two databases that are populated by our vendor using replication from their databases. I do not have access to their distributor db. But I want to monitor from our end whether the data has been refreshed as per schedule.
Is there a way to do this? All the blogs/posts I have seen require access to the distribution db.

A: You can use the canary method to monitor replication status on the subscriber. Check it out here in the "Easy Replication Monitoring: Alert on Latency with Canary Tables" section.
With this method, you would be writing to a table on the publisher that has just one column. Update the table every minute with CURRENT_TIMESTAMP. Monitor the table on the subscriber and fire off an alert if the difference between the table and the current time has exceeded your threshold.

A: If your replicated environment are supposed to assume the same amount of work and be exactly the same as your vendor's, you could maybe turn on the MySQL queries logging, so you can see all the SQL statements hitting your database, by monitoring the queries logs you can have accurate data about the database and know if it is refreshed and when.
Implementing some kind of automatic methods to filter the queries you are interested in should allow you to know all you need. For example you could count the total amount of "INSERT" and "UPDATE" type quereis and draw graphs with that information.
This is just an idea, but maybe you could make use of some opensource monitoring tool to get the most value out of it and even draw graphs, reports...
Hope this helps.


text:
Q: What should i do in order to print level also in Breadth first search Algo. What can be done in the below algo in order to print values level wise in binary tree.
BinarySearchTree.prototype.breadthFirstTraversal = function() {
    console.log("Breadth First Traversal");

    var q = []
    q.push(this.root);//You don't need to write the root here, it will be written in the loop
    while (q.length > 0)
    {
        var n = q.shift();
        console.log(n.value); //Only write the value when you dequeue it
        if (n.left !=null)
        {
            q.push(n.left);//enqueue the left child
        }
        if (n.right !=null)
        {
            q.push(n.right);//enque the right child
        }
    }
};

A: Store level for each node,  and print them only when level changes:
BinarySearchTree.prototype.breadthFirstTraversal = function() {
    console.log("Breadth First Traversal");

    var q = [];
    var prevLevel = -1; // monitor level switch
    var byLevel = []; // store node values for printing
    this.root.level = 0; // set root level
    q.push(this.root);//You don't need to write the root here, it will be written in the loop
    byLevel.push(this.root.value);
    while (q.length > 0)
    {
        var n = q.shift();
        // Next level, print and reset
        if (n.level > prevLevel) {
            console.log(byLevel);
            byLevel = [];
            prevLevel = n.level;
        }
        if (n.left !=null)
        {
            n.left.level = n.level + 1;
            q.push(n.left);//enqueue the left child
            byLevel.push(n.left.value);
        }
        if (n.right !=null)
        {
            n.right.level = n.level + 1;
            q.push(n.right);//enque the right child
            byLevel.push(n.right.value);
        }
    }

    if (byLevel.length > 0) {
        console.log(byLevel);
    }
};

A: Just wanted to add this since it doesn't require the storage of the level of each corresponding node as in the solution above so it doesn't require you to add a property to your object. If you think about it the queue will have, at most, two different levels in it. So you only need one global marker to let you know if you are dealing with a new level and a flag to let you know if you should mark the new right or left node being pushed.
BinarySearchTree.prototype.breadthFirstTraversal = function() {
        console.log("Breadth First Traversal");

var q = new Array();
q.push(this.root);

var printArray = [];
var printArray.push(this.root.value);

var newlevel = false;
var marker = 1;
var level = 0;

while(q.length > 0){

    if(marker==1){
        console.log("level: " + level);
        console.log(printArray);
        newlevel = true;
    }

     var n = q.shift();
     printArray.shift();

     marker -= 1;
     //console.log(n.value);

    if(n.left != null){
        q.push(n.left);
        printArray.push(n.left.value);

        if(newlevel){
            marker = q.length;
            level+=1;
            newlevel = false;
        }
    }

    if(n.right != null){
        q.push(n.right);
        printArray.push(n.right.value);

        if(newlevel){
            marker = q.length;
            level+=1;
            newlevel = false;
        }
    }

}
};


text:
Q: Can one propose a new SE site for a topic which has been already closed as a beta? There was a proposal for an Arabic Language SE closed after 61 days in beta.
Can one suggest to re-open such a closed beta site after several years? There may be increased attention and public interest in the topic.

A: In this meta Area 51 answer Robert states:

Closing a site does not mean folks cannot try again… if they have reason to believe they can make a better go of it the second time around. I'm not speculating whether this particular subject is ready to try again, but we could just as easily have closed Big Data in the proposal stage. When we close proposals for lack of an audience, we often encourage users to gather more support to try again. Big Data simply got a bit further along than most.
At times, we may close proposals/sites that simply should not be their own Q&A. But I don't believe sites closed for other reasons should be used as a head-on-a-stack gesture that they should never become sites at all — "We already tried this; it didn't work. Go away!" That's not how Area 51 works.

Then about four minutes after that answer was posted the OP of the question left a comment on the answer:

I see the proposal has been reopened. Thanks! – user72809  May 10, 2013 at 15:56

Where the proposal was Data Science which was launched five years ago.
On the beta page for the Arabic language proposal it has this text:

This site has been
Closed
This proposal didn't have enough activity during the beta. It was closed 7 years ago.
You could try proposing a variation of this site that you think will have a better chance.

Clicking that link leads to a form for a new proposal. If there is belief that there would be enough community support for such a site then it can be proposed.


text:
Q: convert string to time-format in R language I have strings like this:
100
200
...
2300

how to transfer this to time format?
01:00:00
02:00:00
...
23:00:00

do I have to add 0 to the string?
I have tried
Data$Time <- formatC(Data$Time, digits = 6, flag = "0")

But it's not working

A: We can use sprintf to do the formatting and then convert to Time with as.ITime
library(data.table)
as.ITime(sub("(..)", "\\1:", sprintf("%04d:00", v1)))
#[1] "01:00:00" "02:00:00" "23:00:00"

As @Claudio mentioned, if it is a vector of strings, replace the %04d with %04s
data
v1 <- c(100, 200, 2300)


text:
Q: Failed to access to Firebase Firestore from Cloud Functions I would like to write some data into Firebase Firestore from Cloud Functions, however, it was failed and I got following error message.
Missing or insufficient permissions.
Since it looks security rule issue, I changed the Firestore security rule like below.
It must be the loosest security rule.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

In addition, I wait for a few minutes because it takes time to apply the new security rule.
However, still failed...
Following the Cloud functions code.
const admin = require('firebase-admin');
admin.initializeApp()
const firestore = admin.firestore();

exports.sampleAPI = functions.https.onRequest((request, response) => {
    const text = request.body.text

    writeText(text).then(value => {
        console.log("==== Operation DONE ====")
        response.status(200).send("OK")
        return null
    }).catch(error => {
        console.error("xxxxxx Operation FAILED xxxxxxx")
        console.error(error)
        response.status(500).send(error)
    })
}

async function writeText(text) {
    const textRef = firestore.collection('texts')

    return textRef.add({
        text: text,
    }).then(docRef => {
        const id = docRef.id
        return id
    }).catch(error => {
        throw error
    })
}

How can I fix this issue ??

A: You might want to review this documentation.
2 things about your approach:
1) The syntax for the allow line in the security rule doesn't look correct for what you are trying to do as it is missing the  if <condition> clause, based on the examples on that page above it should read:
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Having tried this, though, omitting this does appear to generate a warning that the database is open to all, so it is unlikely to be the problem.
2) That page also makes clear that cloud functions do not rely on the security rules for the database and instead depend on IAM, so you might want to check the identity that the function is runnning as as well as the roles that identity has.  (More here).  However, generally the defaults should work here (especially if you are only using firebase and not the regular Google cloud console).
One last thing, in your function code you never actually require the functions module.  You need to include a line like this as well:
const functions = require('firebase-functions');

This, of course, should fail during deployment with an error like "ReferenceError: function is not defined" as the javascript will not parse.
If this doesn't help, please provide more information about the error you are getting (when is it being generated -- on deployment?  when the function is executed?, is there any stack trace, etc).


text:
Q: Some basic questions about SQL and TLS 1.0 and 1.2 (I don't believe this is a duplicate of any other TLS-related question, like the authoritative question about SQL Compatibility with TLS or its many duplicates, or questions about specific TLS-related issues you might encounter with SQL CLRs or Classic ASP or SSRS or whatever. This question is a bit more broad.)
All our SQL servers (SQL 2012-2017) are on recent patch levels that support TLS 1.2 (see first link above), and yet when we disabled TLS 1.0 on our SQL servers, nearly all our applications broke (SharePoint farms, web apps, dot.net apps, PowerShell scripts, many vendor apps, heck, even some SQL jobs running on the same box failed).
I thought that clients already tried to negotiate the most secure encryption protocol that both the app and SQL support (TLS 1.2), but that's clearly not the case here.
So... what am I missing? Is there a master switch at the Windows OS level on our application servers that was never flipped to tell applications they should start using TLS 1.2? (We run Windows 2012 R2 and 2016.) Are there different registry entries for enabling "client" TLS 1.2 vs enabling "server" TLS 1.2?
I believe MS components like .Net are up to date as well. I know we will eventually need to look at individual applications, but I can't help but think there is something more obvious going on here.
Also, is there a SQL query that can tell me what connection method was attempted by each application (none vs TLS 1.0 vs TLS 1.2)? This page suggests encrypt_option from sys.dm_exec_connections, but that appears to be a boolean, not one that tells me the type (plus all my rows show FALSE, so I don't think that's right).
Update: Added bounty for more attention. I have determined that at least a couple of our older SQL servers are Windows 2012 (not R2), which (I believe) does not have TLS 1.2 enabled by default, where it should be for Windows 2012 R2 and later?? Is that right?
Also still interested if anyone has a query and/or other method to determine what protocols different clients are using when they attempt their first connection to SQL; or would that be a network-layer tool?

A: This might be different for each client, so you need to test them separately.
First of all for most clients (since they use SChannel) your Windows machines need to be recent enough to support TLSv1.2 (I.e. Server 2008 R2 and later). For those you also need to make sure TLSv1.2 is actually turned on in the Schannel registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client
    Dword: DisabledByDefault = 0

Some clients might need client software updates, this includes a certain minimum .Net Framework (before 4.6 all need patches) as well as a specific SQL Server Native Client version.
And also, if you have a Java application the JVM must actually be recent in order to be TLSv1.2 able (and have it enabled by default). Some Java applications might turn the TLSv1.2 protocol off despite it beeing enabled in Java 8, then you need to check the application.
But in regards to your assumption it requires other things to be negotiated, I don't think so: in all cases TLSv1.2 will be negotiated if it is supported on both sides. If you are sure your SQL Server is capable then it's the client configuration.
The TLSv1.2 KB article lists quite a few known issues and required patches (including client requirements):
https://support.microsoft.com/en-us/help/3135244/tls-1-2-support-for-microsoft-sql-server
In some cases you might also need to exchange provider=SQLOLEDB with SQLNCLI11.


text:
Q: Extract First Word of a Paragraph R I'm trying to remove apostrophes from a Corpus, but only when they are the first character in a paragraph. I have seen posts about finding the first word in a sentence, but not a paragraph.
The reason I'm trying this is because I'm analyzing text. I want to strip all the punctuation, but leave apostrophes and dashes only in the middle of words. To start this, I did:
library(tm)
library(qdap)
#docs is any corpus
docs.test=tm_map(docs, PlainTextDocument)
docs.test=tm_map(docs.test, content_transformer(strip), char.keep=c("'","-"))
    for(j in seq(docs.test))
{
  docs[[j]] <- gsub(" \'", " ", docs[[j]])

}

This successfully removed all of the apostrophes except those that start on new lines. To remove those on new lines, I have tried:
for(j in seq(docs.test))
{
  docs[[j]] <- gsub("\r\'", " ", docs[[j]])
  docs[[j]] <- gsub("\n\'", " ", docs[[j]])
  docs[[j]] <- gsub("<p>\'", " ", docs[[j]])
  docs[[j]] <- gsub("</p>\'", " ", docs[[j]])

}

In general, I think it would be useful to find a way to extract the first word of a paragraph. For my specific issue, I'm trying it just as a way to get at those apostrophes. I'm currently using the packages qdap and tm, but open to using more.
Any ideas?
Thank you!

A: You didn't supply a test example, but here is a function that keeps intra-word apostrophes and hyphens.  It's in a different package, but as the example at the end shows, is easily coerced to a regular list if you need it to be:
require(quanteda)

txt <- c(d1 = "\"This\" is quoted.",
         d2 = "Here are hypen-words.",
         d3 = "Example: 'single' quotes.",
         d4 = "Possessive plurals' usage.")

(toks <- tokens(txt, removePunct = TRUE, removeHyphens = FALSE))
## tokens from 4 documents.
## d1 :
## [1] "This"   "is"     "quoted"
##
## d2 :
## [1] "quanteda's"  "hypen-words"
##
## d3 :
## [1] "Example" "single"  "quotes"
##
## d4 :
## [1] "Possessive" "plurals"    "usage"

You can get back to a list this way, and of course back to documents if you need to be by sapply()ing a paste(x, collapse = " "), etc.
as.list(toks)
## $d1
## [1] "This"   "is"     "quoted"
##
## $d2
## [1] "quanteda's"  "hypen-words"
##
## $d3
## [1] "Example" "single"  "quotes"
##
## $d4
## [1] "Possessive" "plurals"    "usage"


text:
Q: horizontal navigation bar done in CSS * {
border: 0px;
margin: 0px;
padding: 0px;
}
body {
background-color: #FFC;
}
#wrapper {
width:70%;
margin: 0% auto;
}

#header {
background-color: #C1D1FD;
padding: 3%;
}

#nav {

clear:both;
padding: auto;
position:inherit;
background-color:#F0D5AA;
width: auto;

}
#nav ul {
list-style-type:none;

}

#nav a {
display:block;
float:left;
padding:0%;
width:20%;
background-color:#F60;
border-bottom:1px #fff solid;

}

#content {
padding:7%;
margin-left: 20%;
background-color:#fff;

}

#footer {
background-color: #C1D1FD;
padding: 2%;
text-align:center;
}

HTML CODE:
<form id="form1" runat="server">

Welcome to our Website

Home

Products

Services

Contact

Page Heading

welcome

welcome

welcome

Copyright 2010

</form>

Hi this is my CSS & HTML code, im trying to make my navigation bar below the header bar. but navbar result appears as zagged like stairs. How can i make my navbar buttons straight?
Thank you for the advice,

A: You can see here,
http://www.cssnewbie.com/super-simple-horizontal-navigation-bar/
Example Here:
http://www.cssnewbie.com/example/horizontal-menu/

A: I eradicated the stairstep problem by removing one line in the original CSS code. Comment out the position:inherit; statement within the #nav block.

A: Try to remove this :display:block;
and set #nav ul li to display:inline;
this code is woking, but you may change it to fit your needs:
#nav {
background-color:#F0D5AA;
}
#nav ul {
list-style-type:none;
padding-top:3px;
padding-bottom:3px;
}
#nav ul li {
display:inline;
}
#nav a:link, a:visited {
text-align:center;
padding:3px;
}


text:
Q: Chrome Extension Save File Dialog Please I am new to building Chrome Extensions. After the user installs the extension, I want them to configure it by specifying a directory where the app can save files. I want to do this by opening a save file dialog so they can browse to the folder of their choice. How do I do this?

A: The answer is that there is no means in the Chrome Extension API to write files outside of the sandboxed file system provided by Chrome. This could theoretically be done by writing an interface in C and then call that, but so far I have not yet seen a successful implementation.


text:
Q: Graphics.DrawImage shrinking image on display?
edit: Thank you for all the responses, I just found that bmpSize fixed the size. I also added an array per Plutonix's suggestion. Thank you everyone!

Developing a game using Visual Studio, new to using C# for programming. I am generating a map from a text file using a switch statement and the Graphics.DrawImage method. The images are scaled at 24x24 pixels, and the canvas is 979x571. For some reason, my images are displaying very small. I've tried resizing using the Graphics.DrawImage method given, but it creates scaling on only a strip of the tiles. ((I can add the code I tried to implement this as well. Trying to keep this brief.))
I have a larger player object on the map for size reference, the map should be sized larger like the yellow player.
                case 'W':
                    e.Graphics.DrawImage(Properties.Resources.wall, countCol, countRow);
                    countCol = countCol + 8;
                    break;
                case 'G':
                    e.Graphics.DrawImage(Properties.Resources.grass, countCol, countRow);
                    countCol = countCol + 8;
                    break;
                case 'P':
                    e.Graphics.DrawImage(Properties.Resources.player, countCol, countRow);
                    countCol = countCol + 8;
                    break;

The map scaled much smaller.


text:
Q: How to import routes in polka js similar to express.Route() I am trying to import route logic from another file. In express js this is achievable via express.Route(), when i tried polka.Route() an error pops up saying Route doesn't exist in polka.
Express Implementation
server.js
const express = require('express');
const users = require('./routes/api/users');
const app = express();
app.use('/users', users);

user.js
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({ msg: 'works' }));
module.exports = router;

When /users/test is hit the output is {msg:'works'}. This works for the express implementation. For the polka implementation i changed the word express to polka installing it. The issue arises on the line polka.Router() of user.js. How do i enable this functionality of importing route logic from another file in polka.

A: The polka micro web server does not implement a difference between routers and the app. In your users.js file simply setup your routes as you would in your server.js file and then module.export. See Below:
Polka Implementation
server.js
const polka = require('polka');
const users = require('./routes/api/users');
const app = polka();
app.use('/users', users);

user.js
const polka = require('polka');
const router = polka();
router.get('/test', (req, res) => res.end(JSON.stringify({ msg: 'works' })));
module.exports = router;

Hope this help!
Also, here is a good link to see other differences between Express.js and Polka.js: https://github.com/lukeed/polka#comparisons


text:
Q: How should I go about implementing MVVM architecture pattern in my project? I know this is a very documented topic, but I couldn't find a way to implement it in my project, even after spending hours trying to figure it out.
My root problem is that I have a RecyclerView with an Adapter whose content isn't updating as I'd like. I'm a beginner in Android, so I didn't implement any MVVM or such architecture, and my project only contains a repository, fetching data from Firebase Database, and passing it to a list of ShowModel, a copy of said list being used in my Adapter to display my shows (In order to filter/sort them without modifying the list with all shows).
However, when adding a show to the database from another Activity, my Adapter isn't displaying the newly added show (as detailed here)
I was told to use LiveData and ViewModel, but even though I started understanding how it works after spending time researching it, I don't fully get how I should use it in order to implement it in my project.
Currently I have the following classes:
The Adapter:

class ShowAdapter(private val context: MainActivity, private val layoutId: Int, private val textNoResult: TextView?) : RecyclerView.Adapter<ShowAdapter.ViewHolder>(), Filterable {
    var displayList = ArrayList(showList)

    class ViewHolder(view : View) : RecyclerView.ViewHolder(view){
        val showName: TextView = view.findViewById(R.id.show_name)
        val showMenuIcon: ImageView = view.findViewById(R.id.menu_icon)
    }

    @SuppressLint("NewApi")
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("NewApi", "WeekBasedYear")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentShow = displayList[position]
        val index = holder.adapterPosition

        holder.showName.text = currentShow.name

        holder.itemView.setOnClickListener{ // Display show content
            val intent = Intent(context, DetailsActivity::class.java)
            intent.putExtra("position", index)
            startActivity(context, intent, null)
        }

        holder.showMenuIcon.setOnClickListener{
            val popupMenu = PopupMenu(context, it)
            popupMenu.menuInflater.inflate(R.menu.show_management_menu, popupMenu.menu)
            popupMenu.show()
            popupMenu.setOnMenuItemClickListener {
                when(it.itemId){
                    R.id.edit -> { // Edit show
                        val intent = Intent(context, AddShowActivity::class.java)
                        intent.putExtra("position", index)
                        startActivity(context, intent, null)
                        return@setOnMenuItemClickListener true
                    }
                    R.id.delete -> { // Delete show
                            val repo = ShowRepository()
                            repo.deleteShow(currentShow)
                            displayList.remove(currentShow)
                            notifyItemRemoved(index)
                            return@setOnMenuItemClickListener true
                    }
                    else -> false
                }
            }
        }
    }

    override fun getItemCount(): Int = displayList.size

    // Sorting/Filtering methods
}

The fragment displaying the adapter:
class HomeFragment : Fragment() {
    private lateinit var context: MainActivity
    private lateinit var verticalRecyclerView: RecyclerView
    private lateinit var buttonAddShow: Button
    private lateinit var showsAdapter: ShowAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)

        context = getContext() as MainActivity

        buttonAddShow = view.findViewById(R.id.home_button_add_show)
        buttonAddShow.setOnClickListener{ // Starts activity to add a show
            startActivity(Intent(context, AddShowActivity::class.java))
        }

        verticalRecyclerView = view.findViewById(R.id.home_recycler_view)
        showsAdapter = ShowAdapter(context, R.layout.item_show, null)

        verticalRecyclerView.adapter = showsAdapter

        return view
    }
}

The MainActivity:
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        loadFragment(HomeFragment())
    }

    private fun loadFragment(fragment: Fragment){
        val repo = ShowRepository()

        if(showsListener != null) databaseRef.removeEventListener(showsListener!!)

        repo.updateData{
            val transaction = supportFragmentManager.beginTransaction()
            transaction.replace(R.id.fragment_container, fragment)
            transaction.addToBackStack(null)
            if(supportFragmentManager.isStateSaved)transaction.commitAllowingStateLoss()
            else transaction.commit()
        }
    }
}

The repository:
class ShowRepository {

    object Singleton{
        val databaseRef = FirebaseDatabase.getInstance().getReference("shows")
        val showList = arrayListOf<ShowModel>()
        var showsListener: ValueEventListener? = null
    }

    fun updateData(callback: () -> Unit){
        showsListener = databaseRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                showList.clear()

                for(ds in snapshot.children){
                    val show = ds.getValue(ShowModel::class.java)
                    if(show != null) showList.add(show)
                }
                callback()
            }

            override fun onCancelled(p0: DatabaseError) { }
        })
    }

    fun insertShow(show: ShowModel){
        databaseRef.child(show.id).setValue(show)
    }

    fun deleteShow(show: ShowModel){
        databaseRef.child(show.id).removeValue()
    }
}

From what I understand of LiveData and ViewModel, what I should do is creating a ShowViewModel containing a MutableLiveData<List<ShowModel>> containing the shows, and then observe it in my HomeFragment and update the adapter depending on the changes happening. However, everytime I start something to implement it, I encounter a situation where I'm lost and don't know what I should do, which leads me back to square one once again. I've been trying this for more than a week without progressing even a little bit, and that's why I'm here, hoping for some insight.
Sorry for the silly question and the absurd amount of informations, and hoping someone will be able to help me understand what I do wrong/should do.

A: (this ended up longer than I meant it to be - hope it's not too much! There's a lot to learn, but you don't have to make it super complicated at first)
Broadly, working backwards, it should go like this:
Adapter

*

*displays whatever the Fragment tells it to (some kind of setData function that updates its internal list and refreshes)

*passes events to the Fragment (deleteItem(item), showDetails(item) etc.) - don't have the Adapter doing things like starting Activites, that's not its responsibility

Fragment

*

*grabs a reference to any ViewModels (only certain components like Fragments and Activities can actually "own" them)

*observes any LiveData (or collects Flows if you're doing it that way) on the VM, and updates stuff in the UI in response

*e.g. model.shows.observe(viewLifecycleOwner) { shows -> adapter.setData(shows) }

*handles UI events and calls methods on the VM in response, e.g. click listeners, events from the Adapter
ViewModel

*

*acts as a go-between for the UI (the Fragment) and the data layer (the repository)

*exposes methods for handling events like deleting items, interacts with the data layer as required (e.g. calling the appropriate delete function)

*exposes data state for the UI to observe, so it can react to changes/updates (e.g. a LiveData containing the current list of shows that the data layer has provided)

That's the basic setup - the VM exposes data which the UI layer observes and reacts to, by displaying it. The UI layer also produces events (usually down to user interaction) which are passed to the VM. You can read more about this general approach in this guide about app architecture - it's worth reading because not only is it recommended as a way to build apps, a lot of the components you use in modern Android are designed with this kind of approach in mind (like the reactive model of wiring stuff up).

You could handle the Adapter events like this:
// in your Adapter
var itemDeletedListener: ((Item) -> Unit)? = null

// when the delete event happens for an item
itemDeletedListener?.invoke(item)

// in your Fragment
adapter.itemDeletedListener = { viewModel.deleteItem(it) }

which is easier than implementing an interface, and lets you wire up your Adapter similar to doing setOnClickListener on a button. Notice we're passing the actual Item object here instead of a list index - generally this is easier to work with, you don't need to maintain multiple copies of a list just so you can look up an index given to you by something else. Passing a unique ID can make sense though, especially if you're working with a database! But usually the object itself is more useful and consistent

The data layer is the tricky bit - the ViewModel needs to communicate with that to get the current state. Say you delete an item - you then need to get the current, updated list of shows. You have three approaches:
Call the delete function, immediately after fetch the current data, and set it on the appropriate LiveData
This can work, but it's not very reactive - you're doing one action, then immediately doing another because you know your data is stale. It would be better if the new data just arrived automatically and you could react to that by pushing it out. The other issue is that calling the delete function might not have an immediate effect - if you fetch the current data, nothing might have changed yet. It's better if the data layer is responsible for announcing updates.
This is the simplest approach though, and probably a good start! You could run this task in a coroutine (viewModelScope.launch { // delete and fetch and update LiveData }) so any slowness doesn't block the current thread.
Have the data layer's functions return the current, updated data that results
Similar to above, you're just sort of pushing the fetching into the data layer. This requires all those functions to be written to return the current state, which could take a while! And depending on what data you want, this might be impossible - if you have an active query on some data, how does the function know what specific data to return?
Make the ViewModel observe the data it wants, so when the data layer updates, you get the results automatically
This is the recommended reactive approach - again it's that two-way idea. The VM calling a function on the data layer is completely separate from the VM receiving new data. One thing just happens as a natural consequence of the other, they don't need to be tied together. You just need to wire them up right!

How do you actually do that though? If you're working with something like Room, that's already baked in. Queries can return async data providers like LiveData or Flows - your VM just needs to observe those and expose the results, or just expose them directly. That way, when a table is updated, any queries (like the current shows) push a new value, and the observers receive it and do whatever they need to do, like telling the Adapter to display the data. It all Just Works once it's wired up.
Since you have your own repo, you need to expose your own data sources. You could have a currentShows LiveData or (probably preferably) the flow equivalent, StateFlow. When the repo initialises, and when any data is changed, it updates that currentShows data. Anything observing that (e.g. the VM, the Fragment through a LiveData/Flow that the VM exposes) will automatically get the new values. So broadly:
// Repo

// this setup is exactly the same as your typical LiveData, except you need an initial value
private val _currentShows = MutableStateFlow<List<Show>>(emptyList()) // or whatever default
val currentShows: StateFlow<List<Show>> = _currentShows

fun deleteItem(item: Item) {
    // do the deletion
    // get the updated show list
    _currentShows.value = updatedShowList
}

// ViewModel

// one way of doing things - you have a lot of options! This literally just exposes
// the state from the data layer, and turns it into a LiveData (if you want that)
val currentShows = repo.currentShows.asLiveData()

// Fragment

// wire things up so you handle new data as it arrives
viewModel.currentShows.observe(viewLifecycleOwner) { shows -> adapter.setData(shows) }

That's basically it. I've skimmed over a lot because honestly, there's a lot to learn with this - especially about Flows and coroutines if you're not already familiar with those. But hopefully that gives you an overview of the general idea, and don't be afraid to take shortcuts (like just updating your data in the ViewModel by setting its LiveData values) while you're learning and getting the hang of it. Definitely give that app architecture guide a read, and also the guides for ViewModels and LiveData. It'll start to click when you get the general idea!


text:
Q: Use jsf within jsp (change portion of jsp to use jsf) I need help about converting a portion of jsp page to jsf. My old jsp page is big, and I am trying to change a portion of it (CountryDropdown List) to JSF. So I created a countryDropdown.jsf, I tested to run it directly, it loaded the country-list/works fine.
In my old jsp page (company.jsp), I removed the countryList's portion and try to call/include the new jsf "countryDropdown.jsf" something like this:
<jsp:include page="/web/Test/countryDropDown.jsf" flush="true" />

But I get the errors: java.lang.RuntimeException: Cannot find FacesContext
I am not sure what I was missing, if I directly run the new jsf page http://.../web/Test/countryDropDown.jsf  it works fine.

A: It's not possible to include a JSF page in a regular JSP called directly. If you want to use JSF components, your request must be dispatched by the FacesServlet.
It might be possible to get your setup to work if company.jsp is itself called as a JSF page. But you'll probably keep running into problems; JSF is not really meant to be introduced in bots and pieces into an existing application. At the very least, each page should be either completely JSF or completely classic JSP.


text:
Q: Unable to connect to Oracle DB using ojdbc8 after updating Java from 8u144 - any update after and including 8u171 I've been attempting to upgrade the version of Java (currently 8u144) used in an application connecting to an Oracle 12.2 database using ojdbc8. My latest attempt to update to 8u201 fails with the following error:
Exception in thread "main" java.lang.NullPointerException
at oracle.net.jndi.JndiAttrs.getAttrs(JndiAttrs.java:215)
at oracle.net.resolver.AddrResolution.<init>(AddrResolution.java:237)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:233)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1438)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:518)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:39)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:691)
at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:384)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:273)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:198)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:176)
at Main.main(Main.java:22)

I'm using an LDAP url with the syntax supported and documented similar to the following:
"jdbc:oracle:thin:@ldaps://ldap.example.com:7777/sales,cn=OracleContext,dc=com"

Although my question is similar to the following question, I am not using Hibernate and this question doesn't seem to really answer/address what might be the underlying issue.
Unable to get db connection after Java 8 upgrade
To simplify everything, I have reduced my tests to a simple project using only ojdbc8 and something like the following:
    String url = "jdbc:oracle:thin:@ldaps://....";
    OracleDataSource ods = new OracleDataSource();
    ods.setUser("indiana");
    ods.setPassword("thedoctor");
    ods.setURL(url);

    Connection conn = ods.getConnection();
    PreparedStatement st = conn.prepareStatement("select * from world where temple = 'doom'");

    ResultSet rs = st.executeQuery();
    while(rs.next()) {
        System.out.println(rs.getString("last"));
    }

If I switch Java to 8u144 using the exact same code and configuration, the above works just fine.  I'm at a loss...
UPDATE I've narrowed the issue down some, and discovered that the break occurs at Java 8u171.  I'm looking into the release notes for that version and anything else I can find now.

A: Looks like the SSL handshake is failing while creating the LDAPS connection.
Running the test program with the java net debugging option will help in analysing the issue.
Add this option -Djavax.net.debug=all for running your test program and debug output will contain the SSL debug logs which would be useful in identifying the cause. JDK 8u171 has some security related changes.
(SSL Debug :: https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/ReadDebug.html)


text:
Q: Confused about prediction output for glmnet package cv.glmnet model I am using the glmnet package to perform logistic regression on a dataset.
The x.train and x.test data is a simple dataset of numbers.
y.train and y.test is data with categories "Coffee" and "Tea".
Basically the prediction needs to be either "Coffee" or "Tea"
My first question is that do I need to factor the y datasets? I haven't factored them yet.
Secondly, and mainly, this is the problem:
My code is as follows:
lr.fit<-cv.glmnet(x.train, y.train, type.measure="deviance", family = "binomial")
lr.predicted<-predict(lr.fit, s=c("lambda.1se", "lambda.min"), newx=x.test)

However, when I see the output of the lr.predicted variable, I see a list of numbers. I am asking this question because, I was actually expecting predictions like "Coffee", "Tea", "Coffee", "Coffee", "Tea", ........... and so on.
Kindly guide in the right direction. I am a beginner with R and machine learning, so apologies for being an amateur.

A: You may want to check the reference page for glmnet:

y    response variable. Quantitative for family="gaussian", or
family="poisson" (non-negative counts). For family="binomial" should
be either a factor with two levels, or a two-column matrix of counts
or proportions (the second column is treated as the target class; for
a factor, the last level in alphabetical order is the target class).

For the predict function:

type    Type of prediction required. Type "link" gives the linear predictors (eta scale); Type "response" gives the fitted values (mu
scale). Type "coefficients" computes the coefficients at the requested
values for s. Type "nonzero" returns a list of the indices of the
nonzero coefficients for each value of s.

I believe what you are looking for is type = "class", to get the class with highest probability.
For future references, remember to provide a reproducible example of your issue (both code and data).


text:
Q: WCF OData Service and EF 6 issue - Can't expose entities using Odata Service I am using WCF Data Service (Odata) with .NET framework 4.5.1 and EF 6.1. I have used code first approach to create EF model. When I reference this EF model (AddProjectModel.cs) to WCF OData Service (WcfDataService1.svc), it throws following error:
Error:
The server encountered an error processing the request. The exception message is 'On data context type 'AddProjectModel', there is a top IQueryable property 'Assets' whose element type is not an entity type. Make sure that the IQueryable property is of entity type or specify the IgnoreProperties attribute on the data context type to ignore this property.'. See server logs for more details. The exception stack trace is:
at System.Data.Services.Providers.ReflectionServiceProvider.PopulateMetadata(ProviderMetadataCacheItem metadataCacheItem) at System.Data.Services.Providers.BaseServiceProvider.LoadMetadata(Boolean skipServiceOperations) at System.Data.Services.DataService1.CreateInternalProvider(Object dataSourceInstance) at System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider& metadataProviderInstance, IDataServiceQueryProvider& queryProviderInstance, Object& dataSourceInstance, Boolean& isInternallyCreatedProvider) at System.Data.Services.DataService1.CreateProvider() at System.Data.Services.DataService1.HandleRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
Here is my WCF Data Service:     WcfDataService1.svc
namespace AddProjectService
{
 public class WcfDataService1 : DataService<AddProjectModel>
 {
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        // TODO: set rules to indicate which entity sets and service operations are visible,
         updatable, etc.
        // Examples:
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    }
 }
}

My Code First Model:     AddProjectModel.cs
 public partial class AddProjectModel : DbContext
 {
  public AddProjectModel()
    : base("name=AddProjectModel")
  {
  }

  public virtual DbSet<Asset> Assets { get; set; }
  public virtual DbSet<Project> Projects { get; set; }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Configurations.Add(new AssetMap());
    modelBuilder.Configurations.Add(new ProjectMap());
  }
 }

 public class AssetMap : EntityTypeConfiguration<Asset>
 {
  public AssetMap()
  {
  this.Property(a => a.AssetId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
  this.HasMany(a => a.Projects).WithRequired(p => p.Asset).HasForeignKey(p => p.AssetId);

  //table  & column mappings
  this.ToTable("TBLASSET");
  this.Property(a => a.AssetId).HasColumnName("ASSETID");
  this.Property(a => a.AssetLevelId).HasColumnName("ASSETLEVELID");
  this.Property(a => a.AssetNumber).HasColumnName("ASSETNUMBER");
  this.Property(a => a.Name).HasColumnName("NAME");
  this.Property(a => a.AssetTypeId).HasColumnName("ASSETTYPEID");
 }
}

public class ProjectMap : EntityTypeConfiguration<Project>
{
  public ProjectMap()
  {
   this.Property(p => p.ProjectId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   this.HasMany(p => p.SchedulePhases).WithRequired(sp => sp.Project).HasForeignKey(sp =>
   sp.ProjectId);

  //table & column mappings
  this.ToTable("TBLPROJECT");
  this.Property(p => p.ProjectId).HasColumnName("PROJECTID");
  this.Property(p => p.AssetId).HasColumnName("ASSETID");
  this.Property(p => p.CapitalCategoryId).HasColumnName("CAPITALCATEGORYID");
  this.Property(p => p.Comments).HasColumnName("COMMENTS");
  this.Property(p => p.DesignationId).HasColumnName("DESIGNATIONID");
  this.Property(p => p.DispositionId).HasColumnName("DISPOSITIONID");
  this.Property(p => p.FMSNumber).HasColumnName("FMSNUMBER");
  this.Property(p => p.FundingSourceId).HasColumnName("FUNDINGSOURCEID");
  this.Property(p => p.ImplementerId).HasColumnName("IMPLEMENTERID");
  this.Property(p => p.IsApproved).HasColumnName("ISAPPROVED");
  this.Property(p => p.IsDeferred).HasColumnName("ISDEFERRED");
  this.Property(p => p.IsLongTermLease).HasColumnName("ISLONGTERMLEASE");
  this.Property(p => p.IsRollover).HasColumnName("ISROLLOVER");
  this.Property(p => p.IsSidewalkBridge).HasColumnName("ISSIDEWALKBRIDGE");
  this.Property(p => p.JobDescription).HasColumnName("JOBDESCRIPTION");
  this.Property(p => p.JobType).HasColumnName("JOBTYPE");
  this.Property(p => p.OrganizationId).HasColumnName("ORGANIZATIONID");
  this.Property(p => p.ProgramCategoryId).HasColumnName("PROGRAMCATEGORYID");
  this.Property(p => p.DsfId).HasColumnName("DSFID");
  this.Property(p => p.StatusId).HasColumnName("STATUSID");

  this.Map<DomainObjectModel.ObjectModel.Project.ProjectCIP>(m => m.Requires("PROJECTTYPEID").HasValue(15))
      .Map<DomainObjectModel.ObjectModel.Project.ProjectCapacity>(m => m.Requires("PROJECTTYPEID").HasValue(2));
 }
}

Asset class:
public class Asset
{
 public Asset()
 {
   Projects = new HashSet<Project>();
 }

 [Key]
 public decimal AssetId { get; set; }

 [StringLength(20)]
 public string AssetNumber { get; set; }

 [StringLength(100)]
 public string Name { get; set; }

 public decimal? AssetLevelId { get; set; }

 public decimal? AssetTypeId { get; set; }

 public virtual ICollection<Project> Projects { get; set; }
}

Project class:
public class Project
{
 public Project()
 {
 }

 [Key]
 public decimal ProjectId { get; set; }

 public decimal AssetId { get; set; }

 public decimal CapitalCategoryId { get; set; }

 //public decimal ProjectTypeId { get; set; }

 public decimal ProgramCategoryId { get; set; }

 [StringLength(1024)]
 public string Comments { get; set; }

 public decimal ImplementerId { get; set; }

 public decimal StatusId { get; set; }

 public decimal DsfId { get; set; }

 [StringLength(20)]
 public string FMSNumber { get; set; }

 [StringLength(1024)]
 public string JobDescription { get; set; }

 [StringLength(2)]
 public string JobType { get; set; }

 public decimal OrganizationId { get; set; }

 [Required][StringLength(1)]
 public string IsRollover { get; set; }

 [Required][StringLength(1)]
 public string IsDeferred { get; set; }

 [Required][StringLength(1)]
 public string IsApproved { get; set; }

 [StringLength(1)]
 public string IsSidewalkBridge { get; set; }

 public decimal FundingSourceId { get; set; }

 public decimal? DesignationId { get; set; }

 public decimal? DispositionId { get; set; }

 [Required][StringLength(1)]
 public string IsLongTermLease { get; set; }

 public virtual Asset Asset { get; set; }
}

I don't know how to resolve this issue. Could you please tell me what I am missing here?
I am using oracle database and we have purchased license from devart for dotConnect for oracle recently.
Thanks,

Hi,
I have resolved this error by setting up [DataServiceKey] attribute with primary key on each POCO classes. Please refer this: http://blog.marcgravell.com/2008/12/astoria-and-linq-to-sql-getting-started.html.
Now I can expose entities through Odata service but when I try to access the entity collection by typing URL (ex. .../WcfDataService1.svc/Assets) it throws following error:
Error:
 <?xml version="1.0" encoding="utf-8" ?>
 <m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
   <m:code />
   <m:message xml:lang="en-US">An error occurred while processing this request.</m:message>
   <m:innererror>
     <m:message>Operation could destabilize the runtime.</m:message>
     <m:type>System.Security.VerificationException</m:type>
     <m:stacktrace>at queryable_reader(Object ) at   System.Data.Services.Providers.ReflectionServiceProvider.GetQueryRootForResourceSet(ResourceSet container) at System.Data.Services.Providers.ReflectionDataServiceProvider.GetQueryRootForResourceSet(ResourceSet resourceSet) at System.Data.Services.Providers.DataServiceProviderWrapper.GetQueryRootForResourceSet(ResourceSetWrapper resourceSet) at System.Data.Services.RequestUriProcessor.ComposeExpressionForEntitySet(SegmentInfo segment, IDataService service, Boolean isLastSegment, Boolean checkRights) at System.Data.Services.RequestUriProcessor.ComposeExpressionForSegments(IList`1 segments, IDataService service, Boolean isCrossReferencingUri) at System.Data.Services.RequestUriProcessor.ProcessRequestUri(Uri absoluteRequestUri, IDataService service, Boolean internalQuery) at System.Data.Services.DataService`1.ProcessIncomingRequestUri() at System.Data.Services.DataService`1.HandleRequest()</m:stacktrace>
  </m:innererror>
 </m:error>

How do I resolve this?
Thanks,

A: To use WCF DataService with EF6, there're some extra work to do. Please check the following two blog posts for detail:
Using WCF Data Services 5.6.0 with Entity Framework 6+
WCF Data Services Entity Framework Provider is updated with WCF Data Service 5.6.2
In general, you'll need the following two steps:

*

*Install the latest Nuget package Microsoft.OData.EntityFrameworkProvider following the guide on that page;

*Replace DataService with EntityFrameworkDataService, say in your WcfDataService1.svc:
public class WcfDataService1 : EntityFrameworkDataService


text:
Q: Weird result in setting column values of a numpy array In the script below, I want to apply a rotation matrix to the first two columns of a (Nx3) array.
rotate_mat = lambda theta: np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])

rot_mat = rotate_mat(np.deg2rad(90))

basis1 = np.array([[i+1,j+1,k+1] for k in range(3) for j in range(3) for i in range(3)])
basis2 = basis1.copy()
rot = basis2[:,0:2] @ rot_mat

print('rot','\n',rot[:3],'\n')
print('basis2','\n',basis2[:3],'\n')

basis2[:,0:2] = rot
print('basis2 after','\n',basis2[:3])

after I ran this script, I obtained this output
rot
 [[ 1. -1.]
 [ 1. -2.]
 [ 1. -3.]]

basis2
 [[1 1 1]
 [2 1 1]
 [3 1 1]]

basis2 after
 [[ 1  0  1]
 [ 1 -2  1]
 [ 1 -3  1]]

as you can see by basis2[:,0:2] = rot, the first row of basis2 is [1,0,1], however, the first row of rot is clearly [1,-1], where does this 0 come from?

A: If you take a look at the entries of rot you will see that rot[0,1] is -0.9999999999999999. Furthermore basis2.dtype == dtype('int32'). So during the assignment the new entries get converted to int32 which rounds them towards zero. You can verify that
np.int32(rot[0, 1]) == 0

and
np.int32(rot[0, 1] - 1e-16) == -1

This is due to rounding, as np.cos(np.deg2rad(90)) == 6.123233995736766e-17, when you'd probably expect it to be exactly 0.


text:
Q: XSLT: abbreviation of reocurring xpath in an XSL transformation, I've got a rather lengthy XPath (an union of about 20 different nodes). Because this path is needed frequently, an abbreviation of it would be nice.
The abbreviation must be made in a way that it does evaluate in the current context, so using a global variable or something will not work.
Target version is XSLT 1.0 with EXSLT extensions.
Thanks,
Jost

A: If you can't have a global variable then a function may be the solution.

A: You can use entities to provide an abbreviation of the lengthy XPath.
XSLT is an XML file, so XML entities can be used anywhere within the XSLT.  The entities will be expanded and resolved as the XSLT is parsed.
Something that you can do with entities that you cannot do with a global XSLT variable is to use the entity within XPath and match expressions.
For instance, you could create an entity for your long XPath statement and re-use it in multiple locations like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE stylesheet [
<!ENTITY lengthyXPath "elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20">
]>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:output indent="yes"/>
    <xsl:template match="/">
        <output>
           <xsl:apply-templates select="/*/*"/>
        </output>
    </xsl:template>

    <xsl:template match="foo">
            <xsl:comment>mached foo child elements from: &lengthyXPath;</xsl:comment>
            <xsl:apply-templates select="&lengthyXPath;"/>
    </xsl:template>

    <xsl:template match="bar">
            <xsl:comment>mached bar child elements from: &lengthyXPath;</xsl:comment>
            <xsl:apply-templates select="&lengthyXPath;"/>
    </xsl:template>

    <xsl:template match="baz">
            <xsl:comment>mached baz child elements from: &lengthyXPath;</xsl:comment>
            <xsl:apply-templates select="&lengthyXPath;"/>
    </xsl:template>

    <xsl:template match="&lengthyXPath;">
        <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>

When applied to this XML:
 <doc>
    <foo>
        <elem>no match</elem>
        <elem1>1</elem1>
        <elem>no match</elem>
        <elem3>3</elem3>
        <elem>no match</elem>
        <elem5>5</elem5>
    </foo>
    <bar>
        <elem>no match</elem>
        <elem7>7</elem7>
        <elem>no match</elem>
        <elem9>9</elem9>
        <elem>no match</elem>
        <elem10>10</elem10>
    </bar>
    <baz>
        <elem>no match</elem>
        <elem11>11</elem11>
        <elem>no match</elem>
        <elem13>13</elem13>
        <elem>no match</elem>
        <elem15>15</elem15>
    </baz>
</doc>

Produces the following output:
<?xml version="1.0" encoding="UTF-8"?>
<output><!--mached foo child elements from: elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20--><elem1>1</elem1>
   <elem3>3</elem3>
   <elem5>5</elem5>
   <!--mached bar child elements from: elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20--><elem7>7</elem7>
   <elem9>9</elem9>
   <elem10>10</elem10>
   <!--mached baz child elements from: elem1 | elem2 | elem3 | elem4 | elem5 | elem6 | elem7 | elem8 | elem9 | elem10 | elem11 | elem12 | elem13 | elem14 | elem15 | elem16 | elem17 | elem18 | elem19 | elem20--><elem11>11</elem11>
   <elem13>13</elem13>
   <elem15>15</elem15>
</output>


text:
Q: S3 Bucket referencing old code/api? Angular 5 so I'm hosting my angular 5 site on and S3 bucket with Cloudfront. It has a 'https' secure domain. I used to use a non-secure api from Anguar as the backend, and when I tried to log in from the AWS hosted domain, I got the error:
zone.js:2019 Mixed Content: The page at 'https://app.my_app.io was
loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://my_old_api.com/api/v1/account/auth'. This request has been blocked; the content must be served over HTTPS.

That made sense, so I swapped my Angular app to use a secure api instead, say, ''https://my_new_api.com/api/v1/account/auth''. I rebuilt the app and uploaded the contents to the bucket, but I am still getting essentially the same error in my console when I try to log in, even though the old api is no longer referenced anywhere in my app.
So my question is, does AWS S3 bucket reference a cache, or have some sort of lag, or something that would cause it to be looking at my old code?

A: CloudFront will cache it. The idea of using CloudFront is it would copy/cache the S3 contents into the local zone from where it is requested hence reducing latency for the end user.
You will need to invalidate the contents you want refreshed. If you go into the CloudFront console you should be able to do it.

*

*Go to the CloudFront Console.

*Click the Distribution ID of the CloudFront record.

*Select Invalidations tab

*Create an invalidation - and select what resources you want to invalidate. You can use wildcards here so maybe invalidate everything.

That should make CloudFront refresh all contents.