text:
Q: how to make part of list item selectable and other not selectable wpf how to make part of list item selectable wpf and other not selectable
I have an list view can select and unselect item in its and want when unselect its by part of the item
Class for Select and unselect items in list view
public static class ListBoxSelectionBehavior
    {
        public static readonly DependencyProperty ClickSelectionProperty =
            DependencyProperty.RegisterAttached("ClickSelection",
                                                typeof(bool),
                                                typeof(ListBoxSelectionBehavior),
                                                new UIPropertyMetadata(false, OnClickSelectionChanged));

        public static bool GetClickSelection(DependencyObject obj)
        {
            return (bool)obj.GetValue(ClickSelectionProperty);
        }

        public static void SetClickSelection(DependencyObject obj, bool value)
        {
            obj.SetValue(ClickSelectionProperty, value);
        }

        private static void OnClickSelectionChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
        {
            ListView listBox = dpo as ListView;
            if (listBox != null)
            {
                if ((bool)e.NewValue == true)
                {
                    listBox.SelectionMode = SelectionMode.Multiple;
                    listBox.SelectionChanged += OnSelectionChanged;
                }
                else
                {
                    listBox.SelectionChanged -= OnSelectionChanged;
                }
            }
        }

        static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                ListView listBox = sender as ListView;
                var valid = e.AddedItems[0];
                foreach (var item in new ArrayList(listBox.SelectedItems))
                {
                    if (item != valid)
                    {
                        listBox.SelectedItems.Remove(item);
                    }
                }
            }
        }
    }

Class for an extention of wrap panel to add discription and every items
    public class WrapPaneEx : WrapPanel
    {
        protected override Size ArrangeOverride(Size finalSize)
        {
            var size = base.ArrangeOverride(finalSize);

            foreach (UIElement fe in this.Children)
            {
                var itemLocation = GetItemLocation(fe);
                if (itemLocation == null)
                {
                    itemLocation = new ItemLocation(this, fe);
                    SetItemLocation(fe, itemLocation);
                }
                itemLocation.OnLocationPropertyChanged();
            }
            return size;
        }

        public static ItemLocation GetItemLocation(DependencyObject obj)
        {
            return (ItemLocation)obj.GetValue(ItemLocationProperty);
        }

        public static void SetItemLocation(DependencyObject obj, ItemLocation value)
        {
            obj.SetValue(ItemLocationProperty, value);
        }

        public static readonly DependencyProperty ItemLocationProperty = DependencyProperty.RegisterAttached("ItemLocation", typeof(ItemLocation), typeof(WrapPaneEx), new PropertyMetadata(null));
    }

    public class ItemLocation : INotifyPropertyChanged
    {
        public ItemLocation(Panel panel, UIElement itemContainer)
        {
            this._Panel = panel;
            this._ItemContainer = itemContainer;
        }

        private UIElement _ItemContainer;
        private Panel _Panel;

        public Point? Location
        {
            get
            {
                if (_Location == null && _Panel != null && _ItemContainer != null)
                {
                    _Location = _ItemContainer.TranslatePoint(default(Point), _Panel);
                }
                return _Location;
            }
        }
        private Point? _Location;

        public Point? LocationN
        {
            get
            {
                if (_LocationN == null && _Location == null && _Panel != null && _ItemContainer != null)
                {
                    Point? np = Location;
                    if (np != null)
                    {
                        _LocationN = new Point(-np.Value.X, -np.Value.Y);
                    }
                }
                return _LocationN;
            }
        }
        private Point? _LocationN;

        public event PropertyChangedEventHandler PropertyChanged;

        internal void OnLocationPropertyChanged()
        {
            _Location = null;
            _LocationN = null;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Location)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LocationN)));
        }
    }

I hop when unselect item on list view to not be not selectable when click on the canvas of the details
<ScrollViewer  x:Name="scollviewer" HorizontalAlignment="Stretch" >
                        <ListView x:Name="listview" Main:ListBoxSelectionBehavior.ClickSelection="True" HorizontalAlignment="Center" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedMovie}" PreviewMouseWheel="List_PreviewMouseWheel">
                                <ListView.Resources>
                                    <ControlTemplate TargetType="{x:Type ListViewItem}" x:Key="withDetailTemplate">
                                        <Grid>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="Auto"/>
                                                <RowDefinition Height="Auto"/>
                                            </Grid.RowDefinitions>
                                            <Border Grid.Row="0" x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="0" SnapsToDevicePixels="true">
                                                <Grid>
                                                    <local:MovieListItemControl/>
                                                    <Border Background="White" Visibility="Collapsed"
                                    Height="2" Grid.RowSpan="2" x:Name="indicator"
                                    VerticalAlignment="Bottom"/>
                                                </Grid>
                                            </Border>
                                            <!-- **************** -->
                                            <Canvas Grid.Row="1" x:Name="detailCanvas"
                                                Width="0" selec
                                                Height="{Binding ElementName=detailGrid,Path=ActualHeight}"
                                                HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Collapsed">
                                                <Grid x:Name="detailGrid" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ScrollViewer},AncestorLevel=2},Path=ActualWidth}"
                                                   Canvas.Left="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListViewItem}},Path=(local:WrapPaneEx.ItemLocation).LocationN.X}">
                                                    <local:MovieDetailsControl/>
                                                </Grid>
                                            </Canvas>
                                            <!-- **************** -->
                                        </Grid>
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsSelected" Value="true">
                                                <Setter Property="Background" TargetName="Bd" Value="Black"/>
                                                <Setter Property="Opacity" TargetName="Bd" Value="0.7"/>
                                                <Setter TargetName="indicator" Property="Visibility" Value="Visible"/>
                                                <Setter TargetName="detailCanvas" Property="Visibility" Value="Visible"/>

                                            </Trigger>
                                            <EventTrigger RoutedEvent="Loaded">
                                                <EventTrigger.Actions>
                                                    <BeginStoryboard>
                                                        <Storyboard>
                                                            <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:1" />
                                                        </Storyboard>
                                                    </BeginStoryboard>
                                                </EventTrigger.Actions>
                                            </EventTrigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </ListView.Resources>
                                <ListView.ItemContainerStyle>
                                    <Style TargetType="{x:Type ListViewItem}">
                                        <Setter Property="Template" Value="{StaticResource withDetailTemplate}" />
                                    </Style>
                                </ListView.ItemContainerStyle>
                                <ListView.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <local:WrapPaneEx  HorizontalAlignment="Center" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ScrollViewer},AncestorLevel=2},Path=ActualWidth}"/>
                                    </ItemsPanelTemplate>
                                </ListView.ItemsPanel>
                            </ListView>
                    </ScrollViewer>

image for expected propgram

A: If you want to make some elements in your ListView be readonly, you should use the IsHitTestVisible="False" Property on the ListViewIitem. To put that into perspective one would create a style for the ListViewIem and then use DataTrigger to switch that off and on.
<Style TargetType="ListViewItem">
    <Style.Triggers>
        <DataTrigger Binding="Property" Value="False">
            <Setter Property="IsHitTestVisible" Value="False"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

Because this is a DependencyProperty you could also directly Bind to that Property:
<Style TargetType="ListViewItem">
    <Setter Property="IsHitTestVisible" Value="{Binding Property}"/>
</Style>

MSDN explanation.
And here is brief explanation:

Gets or sets a value that declares whether this element can possibly be returned as a hit test result from some portion of its rendered content. This is a dependency property.


text:
Q: Relationship between eigenvectors of a covariance matrix and its component covariance matrices I have a covariance matrix $\mathbf{S} = \mathbf{X}^T \mathbf{X}$. I then divide the matrix $\mathbf{X} \in \mathbb{R}^d$ that has $N$ rows into $n$ portions $\mathbf{x_i} \in \mathbb{R}^d$ each having $N_i$ rows such that:
$$
\mathbf{X} =
\begin{bmatrix}
\mathbf{x_1} \\
\mathbf{x_2} \\
\vdots \\
\mathbf{x_n}
\end{bmatrix}
$$
with $N = \sum_{i=1}^{n} N_i$.
I compute covariance matrices on each portion so that in general we have:
$$
\mathbf{S_i} = \mathbf{x_i}^T \mathbf{x_i}
$$
I noticed that:
$$
\mathbf{S} = \mathbf{S_1} + \mathbf{S_2} + \dots + \mathbf{S_n}
$$
since:
$$
s_{ij} = \sum_{k=1}^{N} x_{ik} x_{kj} = \sum_{\substack{k=1\\k \in (1)}}^{N_1} x^{(1)}_{ik} x^{(1)}_{kj} + \sum_{\substack{k=1\\k \in (2)}}^{N_2} x^{(2)}_{ik} x^{(2)}_{kj} + \dots + \sum_{\substack{k=1\\k \in (n)}}^{N_n} x^{(n)}_{ik} x^{(n)}_{kj}
$$
where $x_{ij}$ are elements of $\mathbf{X}$ and $x_{ij}^{(p)}$ are elements of $\mathbf{x_p}$.
I call each $\mathbf{S_i}$ a component covariance matrix.
Suppose I find the eigenvectors of each component covariance matrix $\mathbf{S_i}$. Are there known theorems that can help me find out a relationship between the eigenvectors of all $\mathbf{S_i}$ and the eigenvectors of $\mathbf{S}$?
For the moment, it only seems intuitive to me to think that such relation should exist, since the component matrices are computed on portions of $\mathbf{X}$ and the information about each portion $\mathbf{x_i}$ is as well contained in $\mathbf{X}$. So perhaps eigenvectors of $\mathbf{S}$ would be as well "informed" by the eigenvectors of all $\mathbf{S_i}$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: If $f$ satisfies $|f(z)|\le |f(z^2)|$ then $f$ is constant If $f:\{|z|<1\}\to \mathbb C$ be analytic such that $|f(z)|\le |f(z^2)|$ for all $z$ in $|z|<1$ then prove that $f$ is constant.
We have , $|f(z)|\le |f(z^2)|\le|f(z^4)|\le|f(z^8)|\le\cdots \le |f(z^n)|\to |f(0)|$ , as $n\to \infty$. As , $|z|<1$ so , $z^n\to 0$. From here I can show that $f$ is bounded. But $f$ is NOT entire so that we can say that $f$ is constant. From here how I can proceed ?


text:
Q: Override toString() for an Android activity After running Inspect Code from the Analyze menu of the Android Studio (after customizing the inspection profile), I get this warning:
ID: ClassHasNoToStringMethod
Description: Reports classes without toString() method.
Problem synopsis: Class 'MainActivity' does not override 'toString()' method (at line 30)
Note: line 30 holds the declaration of the MainActivity class:
public class MainActivity extends Activity implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {

This is only reported for the Main Activity, that extends Activity. I also have an activity that extends  PreferenceActivity, but no toString warning is reported for it.
1. Does it make sense to override 'toString()' for an activity, as suggested? In what cases would it help? Is it a best practice?
2. How would an Activity toString override implementation look like?
3. Why isn't the warning reported for the PreferenceActivity descendant?


text:
Q: datagridview checkboxcolumn sorting I have this datagridview where i have several checkboxcolumns. The datasource for the datagridview is a datatable. I wish to be able to sort the checkboxcolumn if I click the columnheader, but is it possible? And how is it done?

A: Yes it's possible.  Click on the link on the link below for the answer.  Somebody asked that question before:
C# Datagridview does not sort Checkbox column


text:
Q: jQuery animate() not working in Chrome I have a scroll back to top button that brings the user back to the top of the page with a smooth glide. It is working in Firefox but not Chrome:
$('a#scroll-to-top').click(function() {
    $('html').animate({
        scrollTop: 0
    }, 500);
    return false;
});

Up Top

How to get this to work in Chrome?

A: You would like to use this code:
$('a#scroll-to-top').click(function() {
    $('html, body').animate({
        scrollTop: 0
    }, 500);
    return false;
});

Here is example

A: Just use body instead of html like below:
$('a#scroll-to-top').click(function() {
  $('body').animate({
    scrollTop: 0
 }, 500);
  return false;
});


text:
Q: .htaccess rewrite for SEF URLs that works at 1&1 but not other hosts I've been researching and trying everything i can get my hands on but this strangeness persists.
I have an understandably odd rewrite scenario where a php script that does image resizing and caching is being called without its .php extension to create a SEF url, the odd part is that i'm passing all the 'parameters' as if they were a subdirectory of the script and in this scenario my rewrite fails, ie:
http://10.3.2.218/libraries/imageresize/images/portfolio/200/test.jpg

In the above url, 'imageresize' is in reality 'imageresize.php' and everything after that is captured by my script using $_SERVER['REQUEST_URI'] and processed down to image location and dimensions. the output of the script is a processed image with the needed content type etc.
The exact issue is that my rewrite rules work well under normal conditions and they work well (with above scenario) at 1and1 where my client is, but not on my development centos webserver/vm or my VPS with cpanel. It would seem that anywhere but 1and1 apache is maybe assuming /imageresize/ is a directory and never testing to see if its a script. My rewrite rules are as follows.
Options +FollowSymLinks

RewriteEngine on

RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) $1.php [L]

I guess i'm either looking for a solution related to the server configuration or help with a better rewrite rule or at the very least an explanation why something actually works at 1and1.
Thanks for any help.

A: Sounds like MultiViews in enabled on the servers that don't work.
Change
Options +FollowSymlinks

to
Options +FollowSymlinks -MultiViews


text:
Q: Windows Server Local Account Migration from 2003 to 2008 We have a windows 2003 server with around 2000+ local accounts on it.  Most of these accounts are used simply to authenticate a user accessing a web application on the server (basic authentication in IIS).  They do not use desktop logins.
We are now moving to a new server that runs windows server 2008, and are facing the issue of how to migrate the local account username/password combinations to the new server.
Is this possible with built-in tools?
Could i convert the existing local accounts into active directory accounts, then join the 2008 server into the active directory and sync the accounts that way?
I have seen a product called winzero password copy and winzero server migration tool. Are these reliable tools for the job?  http://www.winzero.ca/
Any other advice on how to approach this welcomed.
UPDATE
We went with the Winzero Server Migrator software and it successfully migrated 2000+ local accounts on a 32 bit windows 2003 server to a 64bit windows 2008 server, passwords intact.

A: I don't think that what you're asking is strictly possible without cracking every local account's password.  It's not possible to just "export" local accounts with their passwords intact.  It may be easier to upgrade the current server (after taking a VERY verified backup) to Server 2008, and attempt to image that onto your new hardware.
Yes, that's painful, but the closest thing to what you're asking for.
If you were to import them to your AD domain, I'd do it to an OU with VERY limited rights.  I'd certainly set the "Logon To" property to a dummy computer account (or maybe the IIS server), and deny "logon locally" and remote desktop for that OU's members.
Another option would be to create a separate domain in your DMZ for these users, but I'd still be pretty restrictive about what they could get to...

A: We went with the Winzero Server Migrator software and it successfully migrated 2000+ local accounts on a 32 bit windows 2003 server to a 64bit windows 2008 server, passwords intact.


text:
Q: withX() does not work in Laravel 4.2 The problem is that withErrors() is working perfectly in this code, but withMessage() isn't.
I also tried with('message', 'Test message!'). In views file, I can retrieve withErrors using $errors variable, but if I want to retrieve withMessage, I have to use Session::get('message'). Why is $message not working?
Controller:
public function registration() {
    $rules = array(...);
    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails()) {
        return Redirect::route('registration')->withErrors($validator);
    }
    else {
        //Some code here...

        return Redirect::route('registration')->withMessage('Test message!');
    }
}

Template:
@extends('default.base')

@section('main')
    @if(!empty($errors->all()))

                @foreach($errors->all() as $error)

{{ $error }}
                @endforeach

    @endif

    @if(isset($message))
    {{ $message }}
    @endif
@stop

A: That is because errors is a special case. When creating a view, Laravel check's if there is a session variable with the name errors. If so it will then pass the contents as $errors to the view.
Illuminate\View\ViewServiceProvider@registerSessionBinder
if ($me->sessionHasErrors($app))
{
    $errors = $app['session.store']->get('errors');

    $app['view']->share('errors', $errors);
}

This means you either use Session::has('message') and Session::get('message') in your view or you add a View Composer that does basically the same that Laravel does with errors:
View::composer('*', function($view){
    if(Session::has('message')){
        $view->with('message', Session::get('message'));
    }
});


text:
Q: Reference for rigorous treatment of the representation theory of the Lorentz group When I studied representation theory for the first time it was only focused on finite groups. It was the second half of a one semester course in group theory, and the book employed was "Representation Theory: A First Course" by Harris and Fulton.
Currently I'm studying Quantum Field Theory, and regarding spinors and quantum fields with spin, I'm interested in the representation theory of the Lorentz group.
I know the description of the fields with various spins is tightly connected to the irreducible representations of the Lorentz group.
Unfortunately, though, most traditional textbooks in QFT take a stand to not do a rigorous treatment of the matter, nor present a mathematicaly pleasant notation or definitions. Most of them speak quite loosely of the subject, that it doesn't even look connected to the representation theory I saw in the course I took.
Considering this, what I'm looking for is a book or lecture notes which presents a mathematicaly rigorous approach to the representation theory of the Lorentz group and also establish in a mathematicaly correct way the connection to quantum fields with spin and the representations of the Lorentz group. Is there such a resource out there?

A: A classical and fairly complete (even if it is considered somewhat outdated by someone) reference is [1]: instead of describing its content, let me report the first sentences of the "Phisics Today" review of the book by J. E. Mansfield

Professor Gel'fand has performed another service to physicists with this study. There are a few place where one can find a treatment of the Lorentz group that is both coherent and complete.

Perhaps, even if it is a quite old reference, it is a nice place to start, even considering that a quite inexpensive Dover paperback reprint has been recently published.
Addendum. In the preface of of [1], the Authors recommend the monograph [2] (see here for a review published in the Journal of the London Mathematical Society) "... to the reader wishing to study the representation of the Lorenz group more thoroughly and at a greater length", in their own exact words ([1] p. xviii).
References
[1] I. M. Gel'fand, R. A. Minlos and Z. Ya. Shapiro, Representations of the rotation and Lorentz groups and their applications. Translated from the Russian by G. Cummins and T. Boddington (English), Oxford-London-New York-Paris: Pergamon Press. xviii, 366 pp. (1963), MR0114876, Zbl 0108.22005.
[2] M. A. Najmark, Linear representations of the Lorentz group. Translated by A.Swinfen and O.J.Marstrand. (English)
International Series of Monographs in Pure and Applied Mathematics. 63. Oxford etc.: Pergamon Press. XIV, 447 p. (1964), MR0170977, Zbl 0116.32904.


text:
Q: Is it possible to replicate a table with flexbox? I'm trying to create a table using flexbox but I'm a little stuck right now.
I can make the whole table align - and make the columns align, but I'm unsure how to get both columns and rows to match up.
Here's what I have so far - the example shows exactly where I'm failing:
https://jsfiddle.net/10Lfd5wp/

Name

ASP.NET_SessionId

visit

Usage

Identifies a session (visit), and allows user specific data to be preserved across pages and page updates.

.flex-table {
  /* 2009 spec */
  display: -webkit-box;
  /* 2012 spec */
  display: -webkit-flexbox;
  display: -ms-flexbox;
  /* Standard spec */
  display: -webkit-flex;
  display: flex;
  border: solid 0.1rem rgba(0, 0, 0, 0.12);
}
.flex-table .item > * {
  padding: 0.8rem;
}
.flex-table .item > *:first-child {
  background-color: #fafafa;
}
.flex-table .item > * ~ * {
  border-top: solid 0.1rem rgba(0, 0, 0, 0.12);
}
.flex-table > .item ~ .item {
  border-left: solid 0.1rem rgba(0, 0, 0, 0.12);
}
.flex-table .item.flex {
  /* 2009 spec - limited */
  -webkit-box-flex: 1;
  /* 2012 onwards */
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
}


text:
Q: How to rotate screenshot image with Phonegap Android Screenshot PlugIn I am using the Phonegap 2.20 Android Screenshot plugin and it works fine. Now I want to save the image rotated by 270° - but I am new to Java/Android and need some help:
I tried to rewrite the EXIF data as follows
...

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String filename = "Screenshot_" + dateFormat + ".png";
File f = new File(folder, filename); // System.currentTimeMillis()

//FileOutputStream fos = openFileOutput(f.getPath(), Context.MODE_PRIVATE);
FileOutputStream fos = new FileOutputStream(f);

// change image orientation to landscape
ExifInterface exif = new ExifInterface(filename);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, "8");  // ExifInterface.ORIENTATION_ROTATE_270
exif.saveAttributes();

bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
//fos.close();

//Log.w(TAG, "TAG_ORIENTATION: " + exif.getAttribute(ExifInterface.TAG_ORIENTATION));

that.success(new PluginResult(PluginResult.Status.OK), id);

but it allways throws the error

E/JHEAD(26853): Can't write back - didn't read all

So I think I need to wait until the file is finished writing? Is there any listener or callback or s.l.t.?

A: Well the first problem you will run into is that the ExifInterface can only read jpg data and not png. Second you can set the orientation parameter in the exif header but that doesn't actually rotate the image. It only gives a hint to programs that display images on how to display them properly.


text:
Q: React passing down a function that modifies a third component I have been trying to create a component per function in my app, but I am facing the following issue.
I have the component DisplayAllData that sends the data and an actionable button to DisplayDataWithButton, the issue is that when someone clicks on the Button send in the props, the function modifies the state of the parent component, which is also sent as a parameter to FullScreenDialog, and that throws a Warning: Cannot update a component while rendering a different component.
I designed the components in this particular way because:

*

*DisplayAllData is the only function that has the data to render and the actionable button. (Model)

*DisplayDataWithButton only renders the data and displays the actionable components for that particular data, in this case a button that opens a Dialog in screen. (Viewer)

You can find a running example here: https://codesandbox.io/s/material-demo-forked-8oyef
import React from "react";
import Button from "@material-ui/core/Button";
import DisplayDataWithButton from "./DisplayDataWithButton";
import FullScreenDialog from "./fullscreendialog";

export default function App(props) {
  const [openFullScreen, setopenFullScreen] = React.useState(false);
  var items = ["John", "Melinda"];
  var dataDisplayFunction = (data) => {
    return data.map((item) => {
      return [
        item,
        <Button
          color="success"
          size="small"
          className="px-2"
          variant="contained"
          onClick={setopenFullScreen()}
        >
          Show Dialog
        </Button>
      ];
    });
  };

  return (
    <>
      <DisplayDataWithButton
        shapeDataFunction={dataDisplayFunction}
        data={items}
      />
      <FullScreenDialog open={openFullScreen} />
    </>
  );
}

DisplayDataWithButton.js
export default function DisplayDataWithButton(props) {
  return props.shapeDataFunction(props.data);
}

I suspect that there is another way to implement this model, any suggestion, or ideas on how to fix this one.
Thanks

A: A couple of things: "I have been trying to create a component per function in my app". Forget that - the pattern you have opted for here is called render props but I don't see how it is necessary. Keep it simple. If a big component is simpler to understand than a small component I always opt for the bigger component. Splitting your components will not magically make them easier to understand.
All of the warnings have been dealt with. Most of them were simple mistakes, for example: onClick={setopenFullScreen()} should be onClick={setopenFullScreen}. You can compare your sandbox with my sandbox for all of the changes.
import React from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";
import FullScreenDialog from "./fullscreendialog";

export default function App() {
  const [openFullScreen, setopenFullScreen] = React.useState(false);
  const items = ["John", "Melinda"];
  return (
    <>
      {items.map((item) => [
        item,
        <Button
          key={item}
          color="primary"
          size="small"
          className="px-2"
          variant="contained"
          onClick={() => setopenFullScreen((prev) => !prev)}
        >
          Show Dialog
        </Button>
      ])}
      <FullScreenDialog open={openFullScreen} />
    </>
  );
}

ReactDOM.render(<App />, document.querySelector("#root"));

import React from "react";
import { makeStyles } from "@material-ui/core";
import Button from "@material-ui/core/Button";
import Dialog from "@material-ui/core/Dialog";
import ListItemText from "@material-ui/core/ListItemText";
import ListItem from "@material-ui/core/ListItem";
import List from "@material-ui/core/List";
import Divider from "@material-ui/core/Divider";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import Typography from "@material-ui/core/Typography";
import CloseIcon from "@material-ui/icons/Close";
import Slide from "@material-ui/core/Slide";

const useStyles = makeStyles((theme) => ({
  appBar: {
    position: "relative"
  },
  title: {
    marginLeft: theme.spacing(2),
    flex: 1
  }
}));

const Transition = React.forwardRef(function Transition(props, ref) {
  return <Slide direction="up" ref={ref} {...props} />;
});

export default function FullScreenDialog(props) {
  const classes = useStyles();
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <Dialog
        fullScreen
        open={props.open}
        onClose={handleClose}
        TransitionComponent={Transition}
      >
        <AppBar className={classes.appBar}>
          <Toolbar>
            <IconButton
              edge="start"
              color="inherit"
              onClick={handleClose}
              aria-label="close"
            >
              <CloseIcon />
            </IconButton>
            <Typography variant="h6" className={classes.title}>
              Sound
            </Typography>
            <Button autoFocus color="inherit" onClick={handleClose}>
              save
            </Button>
          </Toolbar>
        </AppBar>
        <List>
          <ListItem button>
            <ListItemText primary="Phone ringtone" secondary="Titania" />
          </ListItem>
          <Divider />
          <ListItem button>
            <ListItemText
              primary="Default notification ringtone"
              secondary="Tethys"
            />
          </ListItem>
        </List>
      </Dialog>
    </div>
  );
}


text:
Q: Where should css go in .html page? I have a index.html page and a style.css file.
I have a style class called .slider and a style class called .logo. Should I put both .slider and .logo inside the style.css page or should i put .slider in index.html and .logo inside .css?
im asking this because i dont know if I should put styles only related to one page inside a global style.css or should i just put it inline in the page it applies to?

A: Typically you embed css that is page specific. Here is how I do my css:
Global css (seperate file(s)):
<link type="text/css" rel="stylesheet" href="css/style.css" media="all" />

NOTE: In today's web world we use a ton of plugins/themes and these plugins/themes tend to roll out newer versions so when you override these plugins/themes make sure you create a css file specific to that theme.
For instance,
Bootstrap 3.1
<link href="/css/bootstrap.3.1.css" rel="stylesheet" type="text/css">

Create this for all your bootstrap overrides so you can use the latest version when it comes out.
<link href="/css/bootstrap.overrides.css" rel="stylesheet" type="text/css">

Page specific css(embedded):

When I am in development stages or the html element does not require css classification.
Simple style format (inline):
Column Header

You may have print specific css as well:
  <link href="/css/print.css" rel="stylesheet" type="text/css">

and inside this file wrap your css as such:
@media print{

}

Keep in mind that you may want to use a css classifcation at a later date when at the time it may seem page specific. Always code for reusability!
Finally:
I like to use css minifier when I put my file(s) into production. I do the same with my javascript files using UglyJs. There is also LESS css that you can use but for now I would stick to these simple conventions or something similar.

A: Styles can go in one of three places.

*

*Inline on the element itself

*In the html page

*In a separate file

I would suggest either putting it in a


text:
Q: qooxdoo: Enhance property to distinguish 0 from -0 Is there a possibility to "override" the equality check of the generated property setters?
I like to have a (integer) property that can distinguish 0 (zero) from -0 (negative zero).
For example this:
qx.Class.define("io.Dummy",
{
  extend : qx.core.Object,
  properties :
  {
    value : {
      check    : "Integer",
      nullable : true,
      init     : null,
      event    : "changeValue"
    }
  }
});

so that following code will fire 3 events (instead of only 1):
  var dummy = new infodesk.Dummy();
  dummy.addListener("changeValue", function (e) {
    this.info("changed!");
  }, this);

  dummy.setValue(-0); // <= changed!
  dummy.setValue(-0);
  dummy.setValue(+0); // <= changed!
  dummy.setValue(+0);
  dummy.setValue(-0); // <= changed!
  dummy.setValue(-0);

When I "patch" the equality-checks in the framework (qx.core.Property's __emitXxx methods) by replacing code like "if (a===b)" with "if(Object.is(a,b))"[1] it works,
...but it would be nice if there's a nicer -more clean- way of doing this.
Maybe this is a feature request?
For a property definition attribute like "compare" (Function) or "altCheck" (Boolean)?
  properties :
  {
    value : {
      check    : "Integer",
      nullable : true,
      init     : null,
      event    : "changeValue",
      altCheck : true // 'alternative check enabled'
      // rsp.:
      compare : function (a, b) { return Object.is(a, b); }
    }
  }

[1] ECMA-Script 6

A: As qooxdoo does not offer the functionality of defining a custom value comparer, please open an issue at the github issue tracker at https://github.com/qooxdoo/qooxdoo/ .
I think the idea of having a compare attribute which allows to define a custom comparer is a good idea. If the compare attribute is omitted, the default comparer should be used.
The best way of getting the functionality you need into qooxdoo is to create a pull request which implements the feature, accompanied by unit tests.

A: I copied the code you mentioned above and found that "changeValue" event happened only once, not 3 times! I use Qooxdoo Playground v5.0.1, Firefox 47.0, Win7.
What's wrong?
You can solve the problem by using the transform key of qooxdoo property, saving the data as string instead of an integer.


text:
Q: ITextSharp Multiple Page PDF from several templates I have a requirement to generate a PDF from multiple different (Unknown page Sized PDF's)

*

*Create a cover sheet from a template and write the text onto it.

*Pull a PDF (Unknown page size) and append to the above 3) Repeat

*until all required PDF's are attached

Step 1 is not a problem and this is working, so I have a a cover sheet PDF generated. I now need a way to append the additional PDF's as above. How can we achieve this using ITextSharp?

A: If you are trying to concatenate multiple PDF files into one you may take a look at the following post.

A: I found a simple way to do this, I found something called PDFCopy in ITextSharp
void MergePdfStreams(List<Stream> Source, Stream Dest)
        {
            var copy = new PdfCopyFields(Dest);

            foreach (Stream source in Source)
            {
                var reader = new PdfReader(source);
                copy.AddDocument(reader);
            }

            copy.Close();
        }

Source : Is there a straight forward way to append one PDF doc to another using iTextSharp?


text:
Q: AWS Serverless Template Configurations with Custom Authorization and Rest API I am a newbie to AWS Lambda Services. I have created a serverless lambda method and successfully deployed it on the AWS cloud.
Next I created a Lambda custom Authorizer and configured the API Gateway for the Lambda method and custom Authorizer.
As, I need to expose many other server less lambda methods therefore I decided to move my lambda method in a serverless .Net API Project. I can deploy this api project to AWS cloud and then manually I can setup the authorizer to use my custom Authorize lambda method.
The struggling part is, I want to configure all these things through serverless.template file.
I am struggling in getting the RESTAPIID for my custom authorizer method and how to set authorizer for my lambda function using the serverless.template file. Below is the configurations I have done.
Also, how to get AuthorizerUri?
I do not want to hard code any thing.
    "Resources" : {
**//How I can create this serverless function to use my custom authorizer?**
    "Create" : {
      "Type" : "AWS::Serverless::Function",
      "Properties": {
        "Handler": "Osn.Ott.Telco.Connector.UI.Web.Controllers.V10::Osn.Ott.Telco.Connector.UI.Web.Controllers.V10.SubscriptionController::Create",
        "Runtime": "dotnetcore2.1",
        "CodeUri": "",
        "MemorySize": 256,
        "Timeout": 30,
        "Role": null,
        "FunctionName" : "CreateCustomer",
        "Policies": [ "AWSLambdaBasicExecutionRole" ],
        "Events": {
          "PutResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/create",
              "Method": "POST"
            }
          }
        }
      }
    },
    "CustomAuthorizer" : {
        "Type" : "AWS::ApiGateway::Authorizer",
        "Properties" : {
            "AuthorizerUri" : {"Fn::GetAtt" : [ "Create", "Arn"]},
            "IdentitySource" : "method.request.header.Authorization,method.request.context.resourcePath, method.request.context.path",
            "Name"           : "CustomAuthorizer",
            "Type"           : "REQUEST",
**//How I can get this id?**
            "RestApiId" : {"Fn::GetAtt" : [ "ServerlessRespApi", ""]}
        }
    }
}

A: AWS announced support for AWS Serverless Application Model Supports Amazon API Gateway Authorizers last week (it could be done previously as well but then one had to use inline Swagger in the SAM template).
There are a few GitHub examples linked from the page the above, and I guess that the Lambda Request Authorizer is closest to your problem. The code below is copied from the template.yaml. Please also see the API Auth Object part of the AWS SAM specification.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: API Gateway with Lambda Token Authorizer
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: MyLambdaRequestAuthorizer
        Authorizers:
          MyLambdaRequestAuthorizer:
            FunctionPayloadType: REQUEST
            FunctionArn: !GetAtt MyAuthFunction.Arn
            # FunctionInvokeRole: !Ref MyRole
            Identity:
              QueryStrings:
                - auth
              # NOTE: Additional options:
              # Headers:
              #   - Authorization
              # StageVariables:
              #   - AUTHORIZATION
              # Context:
              #   - authorization
              # ReauthorizeEvery: 100 # seconds

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: index.handler
      Runtime: nodejs8.10
      Events:
        GetRoot:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get
            Auth:
              Authorizer: NONE
        GetUsers:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /users
            Method: get

  MyAuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: authorizer.handler
      Runtime: nodejs8.10

Outputs:
  ApiURL:
    Description: "API URL"
    Value: !Sub 'https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/'


text:
Q: MYSQLI - Script keeps inserting empty data I am having trouble with my insert script. I can't seem to get my script to stop inserting empty data into mysql. I tried using !empty function. But yet it still submits it into the database. Here's my code:
<?php

  // Connect to MySQL
  $mysqli = new mysqli( 'localhost', 'xxx', 'xxx', 'xxx' );

  if ( $mysqli->connect_error ) {
    die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
  }

if (!empty($_POST)) {

  // Insert into posts
  $sql = "INSERT INTO posts (title, postdata ) VALUES ( '{$mysqli->real_escape_string($_POST['title'])}', '{$mysqli->real_escape_string($_POST['data'])}' )";
  $insert = $mysqli->query($sql);

  // Print response from MySQL
  if ( $insert ) {
    echo "Success! Row ID: {$mysqli->insert_id}";
  } else {
    die("Error: {$mysqli->errno} : {$mysqli->error}");
  }

  // Close our connection
  $mysqli->close();
}
?>

<form action="" method="POST">

Title:

<input type="text" name="title">

Post:

<textarea name="data" id="data"></textarea>

<input type="submit" name="submit">
</form>

A: Your code will automatically insert into the database when the page loads.
As a workaround, you should add if(isset($_POST['submit'])) { which will only insert into the database when the form is submitted.
The code will also check if $_POST['title'] is empty and displays an error if so.
if(isset($_POST['submit'])) {
   if(empty($_POST['title'])) {
      echo 'Please fill in the field.';
   }else{
      $sql = "INSERT INTO posts (title, postdata ) VALUES ( '{$mysqli-real_escape_string($_POST['title'])}', '{$mysqli-real_escape_string($_POST['data'])}' )";
      $insert = $mysqli->query($sql);
   }
}

As you failed to supply your form, I'm guessing that the name of the submit button is submit.


text:
Q: tensorflow run time stable on CPU, but goes up on GPU I have a problem where I'm timing how long each batch takes to run. When it's run on CPU, the time takes to run iteration is 10X the GPU initially but it's consistent, but when I run on GPU, the time keeps going up. Here is a sample code:
def feedward_model(graph, input_x_placeholder):
    with graph.as_default():
       # nn_layer takes input nodes and output y
       y = nn_layer(input_x_placeholder)
       return y
def train_model(graph, y_true_placeholder, predicted_y):
    with graph.as_default():
        cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_true_placeholder, logits=predicted_y)
        train_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
        return train_step, cross_entropy

def timeit(f):
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        delta = te-ts
        print('func:%r took: %2.4f sec' %(f.__name__, delta))
        return result
    return wrap

g = tf.Graph()

with g.as_default():
   # placeholder block
   train_x = tf.placeholder(tf.float32)
   train_y = tf.placeholder(tf.int32)

def feed_dict():
   # data batching block, x and y will be generated in batches:
    x = np.array()
    y = np.array()
    return {train_x: x, train_y: y}

with tf.Session(graph=g, config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as sess:
    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
    run_metadata = tf.RunMetadata()

    with graph.as_default():
        pred_y = feedforward_model(graph, train_x)
        train_step, cross_entropy = train_model(graph, train_y, pred_y)

    @timeit
    def train_run():
       _, loss = session.run([train_step, cross_entropy], feed_dict=feed_dict(), options=run_options, run_metadata=run_metadata)

    for i in range(1000):
        train_run()

In the stdout i get the time takes to run each iteration
I removed all possible stage where it has to communicate back to CPU, i.e. logging, tf.summary. I cannot think of any reason the same graph works consistent with CPU, but run time starts going up ~200 iterations on GPU..
[UPDATE]
I figured out the problem .. The final logging I didn't remove is
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()

Now that I removed these two from session.run, the time to run each iteration on GPU has stabled. I suppose every time the session.run is called, the FULL_TRACE gets longer, thus time goes up linearly. But why would the GPU run time only start going up around 200? and why it didn't affect runs on CPU?


text:
Q: SSRS how to render HTML escaped character I am trying to render a column which has lots of HTML escaped characters, such as &#0945 for alpha, &#0946 for beta. I use SSRS 2012's placeholder property to render it as HTML markup type. This feature looks like only works with HMTL tags, not escaped characters.
Any feedback appreciated.

A: Right-click on the non-design surface of your report and click Report Properties.... Click the References option, click Add in Add or remove assemblies and add System.Web from the .NET options.
Click the Code option and add the following code:
Function Decode(ByVal EncodedString AS String) AS String
  Return System.Web.HttpUtility.HTMLDecode(EncodedString)
End Function

For your field value, use the expression:
=Code.Decode(Fields!MyField.Value)


text:
Q: T-SQL Loop in a stored proc how do I loop through a comma separated variable using tsql in a stored proc
So for instance my list would look like this
"1,2,3,4,5,6,7,8,9,10"

and I would loop thought this list and made some necessary table
insert based on this list

A: You could do it a couple ways, but if this would be a list of ID's it could be done like this as well. It would change your list format a bit.
UPDATE table
SET column = value
WHERE ID in ('1','2','3','4','5','6','7','8','9','10')

You could do a loop as well
DECLARE @List CHAR(100)
DECLARE @ListItem int
DECLARE @Pos int
SET @List = '1,2,3,4,5,6,7,8,9,10'
WHILE LEN(@List) > 0
BEGIN
    --Pull Item Frim List
    SET @Pos = CHARINDEX(',', @List)
    IF @Pos = 0
        BEGIN
            SET @ListItem = @List
        END
    ELSE
        BEGIN
            SET @ListItem = SUBSTRING(@List, 1, @Pos - 1)
        END

    UPDATE table
    SET column = value
    WHERE ID = @ListItem

    --Remove Item Frim List
    IF @Pos = 0
        BEGIN
               SET @List = ''
        END
    ELSE
        BEGIN
                SET @List = SUBSTRING(@List, @Pos + 1, LEN(@List) - @Pos)
        END
END

A: I'd try to avoid looping and insert the rows directly from your comma list.
Use a table values parameter (new in SQl Server 2008).  Set it up by creating the actual table parameter type:
CREATE TYPE IntTableType AS TABLE (ID INTEGER PRIMARY KEY)

Your procedure would then be:
Create Procedure up_TEST
    @Ids IntTableType READONLY
AS

SELECT *
    FROM ATable a
    WHERE a.Id IN (SELECT ID FROM @Ids)

RETURN 0
GO

if you can't use table value parameters, see: "Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog, then there are many ways to split string in SQL Server.  This article covers the PROs and CONs of just about every method.  in general, you need to create a split function.  This is how a split function can be used to insert rows:
INSERT INTO YourTableA (colA)
    SELECT
        b.col1
        FROM dbo.yourSplitFunction(@Parameter) b

I prefer the number table approach to split a string in TSQL but there are numerous ways to split strings in SQL Server, see the previous link, which explains the PROs and CONs of each.
For the Numbers Table method to work, you need to do this one time table setup, which will create a table Numbers that contains rows from 1 to 10,000:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO Numbers
    FROM sys.objects s1
    CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)

Once the Numbers table is set up, create this split function:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
     @SplitOn  char(1)      --REQUIRED, the character to split the @List string on
    ,@List     varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN
(

    ----------------
    --SINGLE QUERY-- --this will not return empty rows
    ----------------
    SELECT
        ListValue
        FROM (SELECT
                  LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT @SplitOn + @List + @SplitOn AS List2
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = @SplitOn
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''

);
GO

You can now easily split a CSV string into a table and join on it:
Create Procedure up_TEST
@Ids VARCHAR(MAX)
AS
SELECT * FROM ATable a
WHERE a.Id IN (SELECT ListValue FROM dbo.FN_ListToTable(',',@Ids))
GO

or insert rows from it:
Create Procedure up_TEST
@Ids VARCHAR(MAX)
,@OtherValue varchar(5)
AS
INSERT INTO YourTableA
        (colA, colB, colC)
    SELECT
        ListValue, @OtherValue, GETDATE()
        FROM dbo.FN_ListToTable(',',@Ids)
GO

A: Using CTE (Common Table Expression) is the most elegant solution I think check this question on stackoverflow,
T-SQL: Opposite to string concatenation - how to split string into multiple records


text:
Q: How to automatically redirect to custom admin menu after plugin activation? I need a function to redirect user to the plugin settings page, right after plugin activation.
I use this function to create a custom menu settings page:
// add option page menu link
function axl_ads_add_admin_menu() {
    $icon = 'dashicons-align-left"';
      add_menu_page( 'AXL Ads', 'AXL Ads', 'manage_options', 'axl_ads',  array($this, 'axl_ads_options_page'), $icon, '3' );
  }

And my settings page url is: wp-admin/admin.php?page=axl_ads
Any help with this, please?

A: You can use register_activation_hook(). Add this to your plugin, tested and works.
register_activation_hook(__FILE__, 'redirect_after_activation');

function redirect_after_activation() {
    add_option('redirect_after_activation_option', true);
}

add_action('admin_init', 'activation_redirect');

function activation_redirect() {
    if (get_option('redirect_after_activation_option', false)) {
        delete_option('redirect_after_activation_option');
        exit(wp_redirect(admin_url( 'wp-admin/admin.php?page=axl_ads' )));
    }
}

A: There is a hook named register_activation_hook that usually works at the time of the plugin activation. This function should be called within the plugins_loaded hook. So,
Firstly, call the activation hook -
function fn_name(){
register_activation_hook(__FILE__,'activation_fn');
}
add_action('plugins_loaded','fn_name');

Now, you need to call the function -
function activation_fn(){
 wp_redirect($target_url);
}

here, wp_redirect($url) is used that redirect you to a specific location. So, simply add your target URL inside the wp_redirect() function.
As a result, when your plugin will be activated, it will automatically redirect to you to the specific location.


text:
Q: git undo merge to master, but keep the changes locally I had a feature branch and a master branch. I did some work on the feature, merged into master, pushed the changes, and then deleted the feature branch, both remotely and locally. So far, so good.
After merging, I realized there was a problem with my feature changes. I'd like to undo the merge on master, but still keep the feature changes so I can work on them again. How can I do this?
What I had originally:
A---B---C---D   [master]
     \
      E----F    [feature]

What I have now:
A---B---C---D---EF (squashed) [master]

What I want:
A---B---C---D      [master]
             \
              EF   [feature]

How do I accomplish this?

A: There are many command sequences that can do it.  Here is one short one.

*

*Make sure everything is committed (git status), so that step 3 can't wreck anything.  This is always a useful base step. :-)

*Run git branch feature.

*Run git reset --hard HEAD^ or git reset --hard HEAD~ (either spelling is fine, use whatever you prefer to type in).

Explanation:

*

*Step 1 should be obvious.

*Step 2 creates the new name feature, identifying the same squashed EF commit that master identifies.  This gives you:
A--B--C--D--EF   <-- master (HEAD), feature

The (HEAD) annotation shows which branch name is the current branch name, and therefore which commit is the current commit as well (in this case EF).

*Step 3 moves the current branch name to point to the selected commit.  The current branch name is, as we see in the diagram, master.  The selected commit is one first-parent hop back from commit EF: EF^ means "first parent of commit EF" and EF~ means "starting from EF, step back one first parent".
The result is:
A--B--C--D   <-- master (HEAD)
          \
           EF   <-- feature

which is what you wanted.
Note that EF~2 would start at EF and count back twice, to D then to C, so that master (still HEAD) would point to commit C instead of commit D.  The --hard to git reset tells Git to replace the index content with that from the chosen commit, and to update your work-tree to match.

A: You need to reset --sort master branch to the commit before merge D this will make you master head on D commit and the EF commit will be local on your machine, make sure from this then force push the master to remove unneeded EF commit then create new feature branch and commit the local changes to it again
Steps:

*

*git reset --soft YOUR_COMMIT_HASH

*git status // to make sure that your files not gone

*git stash // to make your is head clean

*git push -f origin master

*git checkout -b feature

*git stash pop // to retrieve the removed commit changes
reference: https://git-scm.com/docs/git-reset#Documentation/git-reset.txt---soft

A: This could be accomplished in 3 steps with:
On master branch:
$ git reset --hard <Hash of D>    # D is now the tip of master branch
$ git switch -c feature   # Creates a new feature branch based on D and move to it

Now on the newly created feature branch:
$ git cherry-pick <Hash of EF> # Restores the EF commit

This is all that is required.
When a branch is deleted, any lost commits can be found in the reflog for a given period of time (30 days by default), so the EF commit hash could be found there just in case:
$ git reflog

Note:
The switch -c command is available from git 2.23.0+ and does the same as checkout -b.


text:
Q: Silencing "An unhandled exception of type 'System.ExecutionEngineException' occurred in Unknown Module" error I'm getting this error while debugging two background tasks that access an Entity Framework DB. Running just one background task does not seem to trigger the error message. I can't really tell what the issue is because everything is working fine except for the breaking error message that pops up during debug.
It would be great if I can find out why this is happening (the other questions related to this message are unsolved), but the more important thing is turning the error notification off. I am not sure why I am getting the error in the first place because  I do not have anything checked in my exception settings. Does anyone know how?

A: @Tyress, you cannot turn off notifications for unhandled exceptions while debugging. Since unhandled exceptions typically result in application crashes, the debugger will always break when they are encountered.


text:
Q: concatenate numbers to string getting from different number pickers and showing them in a textView I have a text view, by clicking TextView I have a dialog with 3 NumberPickers. I want to concatenate values to string which will looks like '99 9 99' or '99999'[selected integers from NumberPickers] from all 3 different NumberPickers shown in dialog, and set the string to the textView.
public void pricePTola() {

    //int price;
    //TextView;
    //double RPT;
    NumberPicker np1, np2, np3;
    final int npThousand, npHundrd, npTen;
    //final String[] price = new String[1];
    String price;

    TextView textView = (TextView)findViewById(R.id.RPT);
    Dialog dialog = new Dialog(HomeActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dialog.setContentView(R.layout.number_picker);
    dialog.setTitle("RATE PER TOLA");
    //dialog.set

    //String strPrice = String.valueOf(price);
    //TextView RPT=(TextView)findViewById(R.id.RPT);

    np1=(NumberPicker)dialog.findViewById(R.id.np1);
    np1.setMaxValue(99);
    np1.setMinValue(00);
    np1.setWrapSelectorWheel(true);
    npThousand=np1.getValue();
    //npThousand=np1.toString();

    np2=(NumberPicker)dialog.findViewById(R.id.np2);
    np2.setMaxValue(9);
    np2.setMinValue(0);
    np1.setWrapSelectorWheel(true);
    npHundrd=np2.getValue();
    //npHundrd=np2.toString();

    np3=(NumberPicker)dialog.findViewById(R.id.np3);
    np3.setMaxValue(99);
    np3.setMinValue(00);
    np1.setWrapSelectorWheel(true);
    npTen=np3.getValue();
    np3.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            picker.setValue((newVal < oldVal)?oldVal-5:oldVal+5);
            /*price[0] = npThousand + "" + npHundrd + "" + npTen;
            TextView RPT = (TextView) findViewById(R.id.RPT);
            RPT.setText(price[0]);*/
        }
    });
    /*np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            picker.setValue((newVal < oldVal)?oldVal-5:oldVal+5);
            price[0] = npThousand + "" + npHundrd + "" + npTen;
            TextView RPT = (TextView) findViewById(R.id.RPT);
            RPT.setText(price[0]);
        }
    });
    np1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {

            picker.setValue((newVal < oldVal)?oldVal-5:oldVal+5);
            price[0] = npThousand + "" + npHundrd + "" + npTen;
            TextView RPT = (TextView) findViewById(R.id.RPT);
            RPT.setText(price[0]);
        }
    });
    dialog.show();

    //price = valueOf(valueOf(np1) + valueOf(np2) + valueOf(np3));
    price = npThousand+""+ npHundrd+""+npTen;
    TextView RPT=(TextView)findViewById(R.id.RPT);
    RPT.setText(price);

}

MainActivity.Java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    final TextView TV1=(TextView)findViewById(RPT);
    TV1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pricePTola();

        }
    });

A: 1- I saw that you should make function   pricePTola  return string and you shouldn't declare TextView on it.
2 - in function pricePTola on every onvalueChange function you must put  npThousand=np1.getValue(); for np1 and do the same for two other pickers.
3- the end of function  String result = String.valueOf(npThousand)+String.valueOf(npHundrd)+String.valueOf(npTen);
return result;
4 - finally on oncreate
TV1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String final = pricePTola();
        TV1.setText(final);

    }
});

i hope this helped


text:
Q: How to store Qfile in Qhash I want to write the data to many different files randomly, So I store the QFile * to Qhash, But it seams not work. and there is a report

QObject::connect: No such signal QObject::aboutToClose() in ....\include\QtCore\5.3.2\QtCore/private/../../../../../src/corelib/io/qtextstream_p.h:75

Could you help me to solve this problem?
Here is a test code to realize my idea.
#include <QHash>
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
QHash <qint32,QFile *> fileHandHash;
for(qint32 i=0; i<1000; i++){
qint32 id = i % 10;
qDebug() << i << "\t" << id;

if( ! fileHandHash.contains(id) ){
QString filename = id + ".out.txt";
QFile MYFILE(filename);
MYFILE.open(QIODevice::WriteOnly);
fileHandHash.insert(id,&MYFILE);
}

QTextStream OUT(fileHandHash.value(id));
OUT << i << "\n";
}
return 1;
}

A: As said in the comment, you can't store pointers to local variables. However this may be more or less what you're looking for:
#include <QHash>
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QFile>
#include <QDebug>

int main(int argc, char* argv[])
{
   QHash <qint32, QFile*> fileHandHash;

   for (qint32 i = 0; i < 1000; i++) {
      qint32 id = i%10;
      qDebug() << i << "\t" << id;

      if(!fileHandHash.contains(id)) {
         QString filename = QString("%1.out.txt").arg(id);
         QFile* myfile = new QFile(filename);
         myfile->open(QIODevice::WriteOnly);
         fileHandHash.insert(id, myfile);
      }

      QTextStream out(fileHandHash.value(id));
      out << i << "\n";
   }

   qDeleteAll(fileHandHash);
   fileHandHash.clear();

   return 1;
}

Pay attention to the number of file descriptors. Doing this each file will have an open descriptor while in the hash.


text:
Q: how to resolve this "mysqli extension is missing" error after update php7 to 8 in windows apache24?
I am using apache24 on windows.
phpmyadmin working well on PHP version 7.4.26, after I changed PHP version 8.1.4 following error occurred (screenshot). I am also tried with PHP version 8.0.17 but the same error
I am enabled required extensions also such as "mysqli, mbstring, pdo_mysql" but not working with same error
this is my apche24 httpd.conf
PHPIniDir "C:/php8"
AddHandler application/x-httpd-php .php
LoadModule php_module 'C:/php8/php8apache2_4.dll'

A: This message says your php engine don't have the mysqli extension enabled...
So, you can try, on your php.ini:
extension=mysqli # (or the path to the extension module, like: C:/php8/ext/php_mysqli.dll, assuming the path on your post....

Remember to restart apache if you're running php as an module, or the php wrapper, if is an cgi-like)
And make sure your environment configuration is pointing to the correct php.ini for the environment you are running as you have more than one version installed...path precedence can be an issue.


text:
Q: SQL count function workings When you run a query like select count(*) from myTable where (myVariable =1) you get a number returned that fits that criteria.  If you replace the asterisk with any number, you get the same answer.  What's going on with SQL here?

A: Its equivalent.
You are asking how many rows are in the table the number n will refer to the nth column in the table. Even if you don't have n columns this will work.
But it gets better you don't even need to put in anything relating to the table
SELECT ('X') from Table is valid
There is a school of thought that SELECT(1) is better for performance but MSSQL at least the query optimzer looks after this by choosing the correct plan

A: Count checks for non null values, so you can pass any value that has non null value e.g. *, field name, static value.
COUNT(*) will count every row. COUNT(yourColumn) won't include rows where yourColumn is NULL
Refer many ways to use Count function

A:
Since the COUNT function will return the same results regardless of
  what NOT NULL field(s) you include as the COUNT function parameters
  (ie: within the brackets), you can change the syntax of the COUNT
  function to COUNT(1) to get better performance as the database engine
  will not have to fetch back the data fields.

Source: SQL: COUNT Function

A: Little known feature is that you can query select count(distinct someColumn) from SomeTable to get the unique count of a certain column. Then it does matter wich column you pick obviously.
Else the other answers already explain it.

A: count(expression) counts rows where  expression is not null.
If you try count(1), then you'll get all the rows, as 1 is never null.
If you try count(column_name), then you'll count rows where column_name is not null.
http://docs.oracle.com/cd/B10500_01/server.920/a96540/functions26a.htm#82699


text:
Q: Github Webhook on Local Jenkins Server I would like to know is it possible to set a Github Webhook on Local Jenkins Server? Is there any Jenkins plugin to solve this kind of problem? Thanks.

A: Yes, it is possible, however you'll need to connect your local Jenkins server to the internet, using a tool like ngrok.

A: I have searched a lot to configure my local jenkins server with Github Webhookand finally with the help of serveo.net make it work by following below steps -

*

*Open terminal and paste command: ssh -R 80:<localhost_with_port_number> serveo.net

e.g. ssh -R 80:127.0.0.1:8080 serveo.net

*It will give you an accessible url -

*Your local jenkins server will be accessible on given url -

*Use this url in your webhook configuration -

Now your local jenkins server is ready to test any CICD activity...

Note: Each time it may generate a different url and in that case you have to update webhook configuration.

Happy learning!

A: In your Jenkins server, Go to "Manage Jenkins" -> "Manage Plugins" as shown below:

Search for GitHub plugin in the available list of plugins and install it, as shown below.

Next go to your GitHub project's settings, click the webhooks tab on the left as shown below and add the Jenkins GitHub plugin's webhook URL there.

Everytime, a Git pull or Git push event happens, GitHub will send a HTTP Post notification to your Jenkins server via the GitHub plugin.
You need a service like SocketXP to interconnect online GitHub or GitLab or Bitbucket project with your Jenkins server running in your local network or in your private cloud.


text:
Q: Keep track of the maximum memory use in java profiler I am trying to detect memeory leak in my java codes with java profilers VisualVM. I want to report the maximum memory usage before and after I fix a memory leak. While running VisualVM or other java profilers, is there anyway to find out the peak of the memeory usage? Thanks!

A: You can do this with VisualVM. First, install the VisualVM-MBeans plugin, and restart VisualVM. After that on the new MBeans tab choose java.lang.Memory.HeapMemoryUsage. The max value will give you the maximal allocated memory.
Update:
I double-checked it, and HeapMemoryUsage.max isn't the peak heap usage indeed. Fortunately, there are per-generation peak usage statistics in java.lang.MemoryPool.<Generation>.PeakUsage.used. To verify it, I wrote a small program that allocates some memory, and PeakUsage.max for Eden Space plus Old Gen plus Survivor Space gives the desired peak heap usage.
So here's what you can do:

*

*You can use these per-generation statistics. You can also write some small tool that computes and prints the sum of the peak use of each generation for a given process via JMX.

*If you only need some approximation, you can check the Monitor tab in VisualVM, the purple area on the Heap chart is Used Heap, so you can get some idea about the peak usage as well.

*If you need this to eliminate a memory leak, what you really need is the long-time memory allocation pattern, and again, that is available on the Heap chart in VisualVM. This is a good start.

A: You can call Runtime.maxMemory() for how much memory the VM had allocated (this usually doesn't shrink). If you do this in a shutdown hook, then the value should be pretty accurate.

A: Use jmap or -XX:+HeapDumpOnCtrlBreak to accurately measure the memory used in your application at any given time.  Both of these mechanisms trigger a GC when the memory snapshot is taken, so its more accurately reflects the contents and size of the heap.  You can use jhat to open the heap dump.


text:
Q: C++ REST SDK: asynchronous tasks vs. C++11 multithreading This is a conceptual question on the asynchronous task feature of the C++ REST SDK (and maybe also a bit of a noob question).
In a basic application, I have a client and perform several requests, e.g. like
http_client client(U("whatever"));

for(int i=0; i<100; ++i)
{
    http_request request;
    //fill the request
    client.request(request).then([](http_response response) { /* do something*/});
}

(The foor-loop is just to indicate that the request is sent often, I don't really use it in my code).
Questions:

*

*As far I understand, the asynchronous task library then handles those incoming requests in a parallel way -- meaning that not the main thread handles all tasks in an event-like fashion, but rather the library assigns the tasks to an underlying thread pool in some (--to me intransparent--) way. Did I get that correct?

*If the previous view is correct, then is there any reason to combine the REST SDK with the multithreading capabilities of C++. For example, taking again the above loop, start 10 threads and in each one process 10 loop iterations. Does this makes sense or is it unnecessary?

*Moreover, in general, are there any common patterns where one should combine the ppl-capabilities by the C++11 multithreading feature? Or is it safe to rely that the REST SDK and ppl under the hood get the job done better?
(Info: I've asked this question also on the cpprest discussion page. However, this forum seems to be not maintained anymore.)

A:
As far I understand, the asynchronous task library then handles those
  incoming requests in a parallel way -- meaning that not the main
  thread handles all tasks in an event-like fashion, but rather the
  library assigns the tasks to an underlying thread pool in some (--to
  me intransparent--) way. Did I get that correct?

Yes, in the REST SDK, they use a threadpool to launch the task continuation. on windows, they use the Windows API ThreadPool functions (CreateThreadPool, TrySubmitThreadpoolCallback etc.) . on Linux, they use the Boost one.

If the previous view is correct, then is there any reason to combine the REST SDK with the multithreading capabilities of C++. For
  example, taking again the above loop, start 10 threads and in each one
  process 10 loop iterations. Does this makes sense or is it
  unnecessary?

Completly unnecessery, the platform has its own thread pool.

Moreover, in general, are there any common patterns where one should
  combine the ppl-capabilities by the C++11 multithreading feature? Or
  is it safe to rely that the REST SDK and ppl under the hood get the
  job done better?

well, the whole idea of a task is to abstract away the use of threads. threads don't scale well when dealling with many parallel tasks. the conventional approach is to use a thread pool to not spawn a new thread for each new task.
ppl tasks gives you the possibility to handle asynchronous IO in more elegant way. you encapsulate the CPU bound tasks in ppl::task, in these tasks, you can spawn another async IO operations, and use ppl::task::then to continue doing CPU bound tasks when the async IO is finished.
the mechanism is a chain of task-> aync IO -> continuation task-> async IO ->task and so one. when the task launches an IO operation, the underlying thread pool moves on to the next task. when the async IO is finished, it queues the continuation task on the end of the thread pool tasks queue.
So no, you should not directly create any std::thread on you own. you do however, want to use syncrhonization objects like std::mutex if you task accesses any shread resource.
------------------------------------
A good bonus: on VC++ with visual studio 2015 RTM and above, you can use await on tasks and get rid of the then:
http_client client(U("whatever"));

for(int i=0; i<100; ++i)
{
    http_request request;
    //fill the request
   auto response = await client.request(request);
   //do something with the response
}

---------------------------------------------------
A bad bonus: with my experience with REST SDK, its performance is extremly poor, not something you'd expect from a C++ platform.


text:
Q: How to show different content? I have created two Android app's (soundboards). One version is normal, other one is censored. Now I want to squeeze them to only one app. Now, how to make an options in settings menu, to show, or not to show censored content?

A: You can add a PreferenceActivity with a CheckBoxPreference to your Application (don't forget to use the Manifest to declare them).
There is a nice sample of that in the API Demos.
After doing that you can easily check a boolean value from the SharedPreferences - here's how: Data Storage Guide.


text:
Q: scheme for object-oriented programmers I'm thoroughly intrigued by Scheme, and have started with some toy programming examples, and am reading through Paul Graham's On Lisp.
One thing I haven't been able to find is a book or website intended to teach Scheme to "OO people", i.e. people like myself who've done 99 % of their coding in c++/Java/Python.
I see that closures are sort of object-y, in the sense that they have local state, and offer one or more functions that have access to that state. But I don't want to learn Scheme only to port my existing habits on to it. This is why I'm learning Scheme rather than Common Lisp at the moment; I fear that CLOS might just serve as a crutch to my existing OO habits.
What would be ideal is a book or website that offers case studies of problems solved in both an OO language, and also in Scheme in a Schemey way. I suppose I would most appreciate scientific computing and/or computer graphics problems, but anything would do.
Any pedagogical leads would be much appreciated.

A: Congrat you, my friend ! Love cs, love functional programming.
If you are python developer it takes 3-4 days to think in scheme
Here is the best simple tutorial I have ever met http://www.shido.info/lisp/idx_scm_e.html
I found this course http://cs.gettysburg.edu/~tneller/cs341/scheme-intro/index.html and it may be useful for you

A: One beginner's resource that is very helpful and geared very much toward the casual reader is "The Adventures of a Pythonista in Schemeland". It's written (obviously) from the point of view of a Python programmer taking first steps with Scheme. One especially nice thing about it is that it includes an overview of the current implementations and compatibility issues between each scheme implementation, which, unfortunately, can cause some headaches when you're just starting out.
With regards to object systems, these two documents (linked from here) give nice examples of very simple toy implementations using closures that I found helpful in understanding their use in capturing state.

A: If you are starting off with Scheme, have a look at How to Design Programs. This book presents the "Schemey" approach to problem solving. I don't think there is a book that compares OO and functional solutions to the same programming problems. But there is a nice presentation that shows how dynamic languages like Scheme could provide simple solutions to problems that demand complex design patterns in statically typed OOP languages.

A: I doubt CLOS would serve as a crutch for old habits, I found it to be pretty different from the OO style in C++/Java/Python, and very interesting. I don't understand all the details, but I would recommend Peter Seibel's Practical Common Lisp. If you are reading On Lisp without much trouble, you should be able to dive into the chapters introducing CLOS in PCL. Also, I'd recommend his Google Tech Talk comparing Java and Common Lisp.
Here's a few more recommendations to make this a more full-fledged answer:
The classic text Structure and Interpretation of Computer Programs covers quite a few examples in chapter 3 of building modular systems using closures (and addresses issues with introducing state and mutability). Chapter 2 includes some generic and data/type-directed programming which could be helpful for motivating study of CLOS. This book really needs no introduction though, it's a towering work, and I've only been reading it slowly since the spring. Highly recommended if you are interested in Scheme.
While SICP is a great book, it's not without its flaws: A really interesting look at these is the essay "The Structure and Interpretation of the Computer Science Curriculum" which elaborates on a few criticism of SICP, and is written by the authors of How to Design Programs (I haven't read HTDP but I hear it's very good). While this essay won't teach you specifically what you are looking for - comparing functional and OO programming - it is really interesting anyway. Their freshman undergraduate course starts with a first semester introduction to functional programming using Scheme (I think, PLT/Racket) and is followed by a semester of OO programming with C++ or Java... at least that's the course they describe in the essay.
These slides from Peter Norvig address some of the design patterns common in OO programming and show why they are missing or unnecessary in dynamic, functional languages like Scheme and Lisp: http://norvig.com/design-patterns/
I cautiously recommend the book by the same authors as the Little Schemer books: A Little Java, A Few Patterns. I can't say for sure if this is a really a good book or not, it was incredibly strange and there are some really bad typesetting decisions (italic, serif, variable-width, superscript doesn't belong in a text on programming), but it might be interesting to take a look at. You can probably find it cheap, anyway. Don't take this recommendation that seriously. I think it would be better to stick to the Scheme texts.
p.s. I have to disagree with one comment stating that functional programming is not as complicated at OO programming, I think that's grossly misstating it. Functional programming in all its breadth is truly mind-boggling. When you go beyond map/filter/reduce and first-class functions, and take a look at other things in the functional realm like lazy evaluation, avoiding side effects and mutation, and the strong, static-typed languages, it gets pretty interesting, and is certainly just as complicated as traditional OO programming. I've only just scratched the surface myself but have discovered a great deal of new ideas. Programming is complicated business, whether OO or functional.


text: Q: how to insert javascript code into powershell? I want to assign 3000 lines of javascript code to $variable but I am getting the following error. Even though I put the @ signs at the beginning and the end, it doesn't work and gives an error like the one below. How should I do?


text:
Q: How to display 365 day Calendar in WPF I have to show all 365 days on an events diary (it has to be 365 days, I have no choice).
The app was originally in winforms, it had 12 DataGridView's, one for each month, with one small text line for each day upto 31 lines. We (just) Managed to get it all on screen ( it was done on two rows i.e. Jan-June top 6 DGV's, July-Dec Bottom 6 DGV's).
I need to get the project over to WPF.
My question is regarding speed, the winforms ver wasn't too fast, im wondering whats the best approach for the layout & DB for this app, i.e  more info -

*

*It uses T-SQL as the diary DB

*Not All days have anything to display (ie no direct binding for text day-> db day enrty)

*DB entries have a date an event description (description is what I need to display)

*A typical Diary has approx 150 entries to display

Any Help Appreciated

A: Can't really help you much on the layout side, however I was required to implement something very similar in silverlight and this is the solution I used which worked pretty well.
1: Implement isolated storage on the application side, this is used as the diary cache
2: On the database side you should store the data as an XML data type
3: When the user logs in immeadiatly display the contents of the diary cache so there's no waiting
4: Next immeadiatly kick off a background worker which communicates back to the database and gets the latest up to date diary information
5: Once the background worker completes, check if any day's data from the db is different from that stored in local cache, if so update the GUI and local cache
6: Run the background worker every 5 minutes following steps 4 & 5 as required


text:
Q: rdfproc took forever to parse a 8.33 MB file? I'm trying to combine all my ttl files into one data dump, but when I try to do
rdfproc test_big parse vm_base.ttl turtle

It's taking forever, still waiting..., making me suspect it has stuck somewhere.
Is there a better alternative which can do this faster?
Other than I manually open all files in Protégé, which is what I have been doing, and find it time-consuming.
The file, if you need to test:
https://github.com/miranda-zhang/cloud-computing-schema/blob/master/example/sparql-generate/result/azure/v1.0.1/2019-03-07/vm_base.ttl

Edit
I did a test with riot merging 2 files, but why does it give duplicated @prefix declarations?
@prefix schema:  <https://schema.org/> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .
@prefix rdfs:  <http://www.w3.org/2000/01/rdf-schema#> .
@prefix cocoon:  <https://w3id.org/cocoon/v1.0.1#> .

<https://w3id.org/cocoon/data/v1.0.1/Device/150.203.213.249/lat=-35.271475/long=149.121434>
        <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>  cocoon:Device ;
        rdfs:comment  "The computer used to conduct the tests, belongs to Australian National University College of Engineering & Computer Science."@en ;
        rdfs:label    "CECS-030929"@en .

_:b0    <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>  schema:Place .

_:b1    <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>  schema:GeoCoordinates ;
        schema:address    "Hanna Neumann Building #145, Science Road, Canberra ACT 2601" ;
        schema:latitude   "-35.271475" ;
        schema:longitude  "149.121434" .

_:b0    schema:geo  _:b1 .

<https://w3id.org/cocoon/data/v1.0.1/Device/150.203.213.249/lat=-35.271475/long=149.121434>
        cocoon:inPhisicalLocation  _:b0 ;
        cocoon:ipv4                "150.203.213.249" .
@prefix schema:  <https://schema.org/> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .
@prefix cocoon:  <https://w3id.org/cocoon/v1.0.1#> .

<1-KB>  <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>  schema:TypeAndQuantityNode ;
        schema:amountOfThisGood  "1"^^xsd:interger ;
        schema:unitText          "KB" ;
        schema:unitCode          "2P" .

I tested with files

*

*https://github.com/miranda-zhang/cloud-computing-schema/blob/master/example/sparql-generate/result/device.ttl

*https://github.com/miranda-zhang/cloud-computing-schema/blob/master/example/sparql-generate/result/qos_property.ttl


text:
Q: GetElementByClassName isn't working I'm developing a website, that apply content editable feature to some pages, so I wanted to store it in local storage, but it only works for one element! I tried to use GetElementByClassName() and querySelectorAll(), but with no luck. Here is the code and any feedback is highly appreciated!

Trip Name

 Country Name

    Save

Trip Foucs

Thanks,
Maryam


text:
Q: SQL - select distinct I used the select disctinct statement with 2 fields from my sql database table. Here is my code.
myCommand = New SqlCommand("SELECT DISTINCT Author FROM tblBook UNION SELECT DISTINCT BookCode FROM tblBook",myConnection)
 myAdapter = New SqlDataAdapter(myCommand)
 myAdapter.Fill(myDataSet, "tblBook")
 cboAuthor.DataSource = myDataSet.Tables(0)
 cboAuthor.DisplayMember = "Author"
 cboAuthor.DisplayValue = "BookCode"

and it generates error : cannot bind to the new member. Parameter name:value. Please help

A: you have selected only one column in your sql statement, Author.
BookCode isn't present so it won't be in the dataset either.
Include the BookCode in the Sql Statement and it will be fixed

A: Maybe you are looking for
SELECT DISTINCT Author, Bookcode FROM tblBook

Union is used to merge rows not columns..
So your query returns a single column where you have all the autors (distinct) followed in the same column by rows of all the bookcodes (distinct as well).

A: A UNION operation does not work in this way.
You want a recordset containing two columns - Authors and BookCodes so you are going to need a query something like:
 SELECT DISTINCT Author, BookCode FROM tblBook

A: You make a query of two distinct things.
You either want to...

*

*Get the author of each book. In that case have to make a query joining the tables, so union is not an option

*You indeed need the result as one column, in that case give the column an alias and bind the alias
SELECT DISTINCT Author AS mycolumn FROM tblBook
UNION
SELECT DISTINCT BookCode AS mycolumn FROM tblBook


text:
Q: Finding within-groups specific sequences I am working on a data set including the results of repeated tests (results expressed as positive(1)/negative(0)) on individuals over time; the number of tests per individual is not necessarily the same.
below is a df reproducing how my dataset looks like:
id<-c(rep("a", time=5), rep("b", time=5), rep("c",time=7))
date<-as.Date(c("2018-03-01","2018-04-01","2018-06-01","2018-08-01","2018-10-01","2017-03-01","2017-04-01","2018-02-01","2018-11-01","2018-12-01","2016-05-11","2017-10-01","2018-03-01","2018-03-21","2018-4-01","2018-07-01","2018-08-01"))
test<-c(1,1,0,1,0,0,1,0,1,1,0,0,1,0,0,1,0)
df<-data.frame(id, test, date)
df
id test       date
a    1 2018-03-01
a    1 2018-04-01
a    0 2018-06-01
a    1 2018-08-01
a    0 2018-10-01
b    0 2017-03-01
b    1 2017-04-01
b    0 2018-02-01
b    1 2018-11-01
b    1 2018-12-01
c    0 2016-05-11
c    0 2017-10-01
c    1 2018-03-01
c    0 2018-03-21
c    0 2018-04-01
c    1 2018-07-01
c    0 2018-08-01

what I am trying to do is to create a new column 'Var' indicating whether any of the following set of results:
match1<-c(1,1,1,1)
match2<-c(1,1,1,0)
match3<-c(0,1,1,1)
match4<-c(1,0,1,1)
match5<-c(1,1,0,1)

is observed in the result set of each individual. ideally this would result in:
id test       date      Var
a    1 2018-03-01     case
a    1 2018-04-01     case
a    0 2018-06-01     case
a    1 2018-08-01     case
a    0 2018-10-01     case
b    0 2017-03-01     case
b    1 2017-04-01     case
b    0 2018-02-01     case
b    1 2018-11-01     case
b    1 2018-12-01     case
c    0 2016-05-11 non-case
c    0 2017-10-01 non-case
c    1 2018-03-01 non-case
c    0 2018-03-21 non-case
c    0 2018-04-01 non-case
c    1 2018-07-01 non-case
c    0 2018-08-01 non-case

because the sequence (1,1,0,1) is observed within the result set of 'a', (1,0,1,1) in 'b' while none of the target sequences is observed in 'c'.
Apologize for not posting any attempt but I am really stuck with this!
best regards,
Matteo


text:
Q: How to check if webhook posted data is in some table and if not select some data from another table I am trying to update ms sql server table's specific field data using webhook posted xml data
the below is php $tsql script
$tsql = "UPDATE Item SET Quantity = (Quantity - '$qty')
         WHERE ItemLookupCode = '$sku'";
'$sku' is from xml data field which is webhook posted but the problem is for example i got 4 '$sku' from xml and 2 of '$sku' is matching with ItemLookupCode in 'Item' Table so i can update but the other 2'$sku' i have to find from another table using different field in another table - Item2(another table's name for example) so after i got 2 '$sku''s specific field in Item2 table i come bact to 'Item' table and i can update Quantity in Item table using different field using the data i got from Item2 table
i am sorry if i made u confused...
so basically what i am trying to do is if "$sku' from xml matches with ItemLookupCode in Item table then i update the quantity but if "$sku" from xml doen't matches or don't have in another word in Item table's ItemLookupCode then i how do i try to find some data from another table using those '$sku'
(ex) if some item's sku is not in ItemLookupCode column in Item table then use that "$sku" to select some column's specific values in Item2 table to update Item table's Quantity
Thank you so much guys!

A: UPDATE Item  SET Quantity = (Quantity - '$qty')
From OtherTable o
WHERE Item.Name=o.Name and o.ItemLookupCode = '$sku'


text:
Q: How to code fortran to read a data file and print certain rows? I have created a code that reads in a data file and print out the 20 lines of it. I want to develop this by making the code read all the lines within the data file, and only printing out certain lines that comply with an if statement. There are 4 values per data row, and I want it to look at the 3rd value and see if this changes, and if it does then to print that row of values. Can anyone help?
  program datafile

  implicit none
  real*8 um,nm,pN,s
  integer*8 au
  integer*8 i
  real, dimension(1:4)
  real, dimension(4) :: file

  WRITE(*,*)"test"
  OPEN(UNIT=1, FILE="file.dat",STATUS="old",ACTION="read")
  WRITE(*,*)"file opened"

  do i=1,20
     read(1,*) file

     write(*,*)file
  enddo

  close(unit=1)
  end program datafile

~


text:
Q: Почему не работает регулярное выражение в JS, когда оно работает в PHP? Почему не работает регулярное выражение в JS, когда оно работает в PHP?
var re = /^[a-z0-9-.]{1,39}+$/;

из-за знака + происходит ошибка синтаксиса:
Uncaught SyntaxError: Invalid regular expression: /^[a-z0-9-.]{1,39}+$/: Nothing to repeat

Но почему? Регулярное выражение правильное же!

A: В книгах такое поведение назывется "сверхжадным" квантификатором, которое не поддерживается движком JavaScript, но поддерживается в PHP.
Это такое поведение квантификатора, когда ни один захваченный литерал не буден откачен назад при несовпадении. Может произойти откат только всей конструкции в целом.
Проще всего прийти к пониманию вопроса прочитав про "атомарную группировку".
Выражение
[a-z0-9-.]{1,39}+

Эквивалентно
(?>[a-z0-9-.]{1,39})

Вот еще небольшой список "сверхжадных" квантификаторов PCRE:
++
*+
?+
{m,n}+

их все отличает наличие + после самого квантификатора.

Смотрим примеры поведения:
https://regex101.com/r/nO7rE6/6
a++a

Нет совпадения, потому что сверхжадная квантификация не вернет ни одного захваченного литерала несмотря на то, что из-за этого все выражение не совпадет.
https://regex101.com/r/nO7rE6/5
a+a

Квантификация вернет один литерал, потому что это нужно для общего совпадения.
https://regex101.com/r/nO7rE6/4
a+?a

а тут идет попытка захватить минимальное число литералов для общего совпадения.

A: Дело в том, что диалект регулярных выражений JavaScript не поддерживает данного поведения регулярных выражений PHP.


text:
Q: Ambiguous use of 'init(contentsOfURL:)' in swift 4.1 I use Swift 4.1 and XCode 9.3
var upsList = [Any]()

func loadUpsValues () {
    print("loadUpsValues")
    let upsFileAsURL = URL(string: "Upslist.txt")
    //    Original Objective C Call was: NSMutableArray *ListUpsArray = [NSMutableArray arrayWithContentsOfURL:upsFile];
    //
    let upsList = NSArray(contentsOfURL:upsFileAsURL! )
}

I get an error: Ambiguous use of 'init(contentsOfURL:)'
and it seems that the source for NSArray comes from the same foundation definition:
I have twice:

1 Found this candidate (Foundation.NSArray)
2 Found this candidate (Foundation.NSArray)

Thanks for your help

A: This error is because [NS(Mutable)Array arrayWithContentsOfURL:]; does not exists in Swift.
For swift the NSArray initialiser has been changed to be more 'swifty' so it became:
NSArray(contentsOf:)

As seen here.

So changing your last line, the code should run as expected, i.e:
let upsList = NSArray(contentsOf: upsFileAsURL!)

Edit:
Going with the comment from @nayem. Assuming your text file is a collection of lines, you could change your code to work without relying on NS based objects like so:
func loadUpsValues () {
    do {
        guard let url = Bundle.main.url(forResource: "Upslist", withExtension: "txt") else { return }

        let data = try String(contentsOf: url)
        let upsList = data.components(separatedBy: NSCharacterSet.newlines)

        ...
    } catch {
        /* handle error */
    }
}

A: Look at this solution:
You have declared once the upsList, why do you declare it again as a let
This solution works.
    var upsList = NSArray()

func loadUpsValues () {
    print("loadUpsValues")
    let upsFileAsURL = URL(string: "Upslist.txt")
    //    Original Objective C Call was: NSMutableArray *ListUpsArray = [NSMutableArray arrayWithContentsOfURL:upsFile];
    //
    upsList = NSArray(contentsOf: upsFileAsURL! ) ?? NSArray()
}


text:
Q: How can I ensure repeatability while parallelizing a randomly seeded experiment? I'm using Mydia to extract random frames from videos. Because I have a lot of videos, I want to parallelize this workflow while maintaining repeatability. mydia.Videos accepts a random seed, which is important for ensuring repeatability. Now I need to work on the parallelization piece.
Given n videos and a random seed, r, how can I ensure that the extracted frames for each video is the same regardless of the number of workers? I'm particularly interested in the algorithmic component, not necessarily the code.
My initial thought was to use multiprocessing.Pool. However, there will be a race condition in sampling the frames if the processes' completion times are non-determinstic; i.e., if proc 1 takes longer than proc 0, the sampled frames from the Videos class will be different than if proc 0 takes longer than proc 1.

A: My solution is a bit unorthodox because it's library-specific. Mydia allows to pass the frames to extract in lieu of forcing the Videos client to sample directly. This affords me the opportunity to  precalculate the frames to sample in the parent process. By doing this, I can "mock" the randomness in the subprocesses by instantiating a new Videos with those frames. For instance:
class MySampler:
   def __init__(self, input_directory: Path, total_frames: int, num_frames: int, fps: int):
       self.input_directory = Path(input_directory)

       self.frames_per_video = [
            self.__get_frame_numbers_for_each_video(total_frames, num_frames, fps)
            for _ in self.input_directory.glob("*.mp4")
        ]

    @staticmethod
    def get_reader(num_frames: int, frames: List[int]):
        # ignores the inputs and returns samples the frames that its constructed with
        return Videos(target_size=(512, 512), num_frames=num_frames, mode=lambda *_: frames)

and then I can simply parallelize this:
   def sample_frames(self, number_of_workers: int):
        pool = Pool(processes=number_of_workers)
        videos = list(self.input_directory.glob("*.mp4"))

        pool.starmap_async(self.read_video, zip(self.frames_per_video, videos))

        pool.close()
        pool.join()

where read_video is the method that calls get_reader and does the reading.