问:
Bullets not showing in Game view
I am making a simple 2d shooter in unity. I have made a prefab for my weapons and a script to shoot. When I enter the game mode I can see the bullet objects being created, but the bullets don't show on the screen. When I pause it and enter the scene mode they show (most of the time) any idea what could be causing this??
Here is the various settings on my bullet :

Thanks in advance for your help

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    //variable to handle what progectile to spawn
    public GameObject projectile;
    //from where does the bullet coem from
    public Transform shotPoint;
    //How much time should be taken between shots
    public float timeBetweenShots;
    //time to shoot another bullet
    private float shotTime;

    // Update is called once per frame
   private void Update()
    {
        //Callculating the the current mouse position to the current weapon position
        //Input.mouse position returns a screenpoint
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = rotation;

        //if the left mouse button is pressed
        if(Input.GetMouseButton(0)){

            //if the current time in the game is greater than the shot time
            if (Time.time >= shotTime)
            {
                //shoot projectile
                Instantiate(projectile, shotPoint.position, transform.rotation);
                //recalculate shot time current time + time between shots
                shotTime = Time.time + timeBetweenShots;
            }

        }
    }
}

</code>```

答:
Basically you are creating bullets inside of the weapon thats why you are not able to see your bullets. I create simple scene and adding sphere as a bullet then I realized sphere spawning in the gun(for me in the cube). If you will adding force everything will be okay.

Assume the shootPoint is somewhere over the gun barrel,

```<code> Instantiate(projectile, shotPoint.position, transform.rotation);
</code>```

You should give them force,

```<code>GameObject projectile= Instantiate (prefab, position, rotation) as GameObject;
 rb = projectile.GetComponent<Rigidbody>();
 rb.AddForce (direction * speed);
</code>```

Dont forget to add rigidbody to the bullet

Title: Bullets not showing in Game view

Body:
I am making a simple 2d shooter in unity. I have made a prefab for my weapons and a script to shoot. When I enter the game mode I can see the bullet objects being created, but the bullets don't show on the screen. When I pause it and enter the scene mode they show (most of the time) any idea what could be causing this??
Here is the various settings on my bullet :

Thanks in advance for your help

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    //variable to handle what progectile to spawn
    public GameObject projectile;
    //from where does the bullet coem from
    public Transform shotPoint;
    //How much time should be taken between shots
    public float timeBetweenShots;
    //time to shoot another bullet
    private float shotTime;

    // Update is called once per frame
   private void Update()
    {
        //Callculating the the current mouse position to the current weapon position
        //Input.mouse position returns a screenpoint
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = rotation;

        //if the left mouse button is pressed
        if(Input.GetMouseButton(0)){

            //if the current time in the game is greater than the shot time
            if (Time.time >= shotTime)
            {
                //shoot projectile
                Instantiate(projectile, shotPoint.position, transform.rotation);
                //recalculate shot time current time + time between shots
                shotTime = Time.time + timeBetweenShots;
            }

        }
    }
}

Body:
Basically you are creating bullets inside of the weapon thats why you are not able to see your bullets. I create simple scene and adding sphere as a bullet then I realized sphere spawning in the gun(for me in the cube). If you will adding force everything will be okay.

Assume the shootPoint is somewhere over the gun barrel,

 Instantiate(projectile, shotPoint.position, transform.rotation);

You should give them force,

GameObject projectile= Instantiate (prefab, position, rotation) as GameObject;
 rb = projectile.GetComponent<Rigidbody>();
 rb.AddForce (direction * speed);

Dont forget to add rigidbody to the bullet


来源: stackexchange

问:
Configure Eclipse workspace automatically
I have a eclipse workspace which constitutes of 15 different java projects . To configure the eclipse workspace , every time I need to add the java projects manually and add the dependency and refrences in the java build path.
Adding all the  projects and resolving dependency every time becomes a manual and redundant task. I explored on the .classpath inside the every projects which stores the dependency and refrences information.
I would like to automate this redundant process.
Have any one tried doing that , any inputs will be helpful.

I don't need to add same project more than once , but often need to create a new eclipse workspace with new code changes and delivery (I can't take some of the changes in the current work space).In simple terms for e.g if some one need to create eclipse workspace again and again , or multiple people need to create the same workspace for their work . How can we reduce that manual effort?

答:
You don't say whether you're using a build tool other than Eclipse, but if not you should.

Eclipse is able to parse Ant files to discover the source directories and libraries. And Maven and Gradle can both generate Eclipse project files for you to import.

As a longer-term benefit, using a build tool means that you can easily build and deploy your projects without any need for Eclipse. And it will be easier for new team members to work on the projects, as they won't need to figure out all the dependencies.

If you don't already have people with expertise, I would recommend Maven. It's easy to set up a basic Java build script, and its dependency management features are IMO better than the alternatives. It will, however, force you into its way of doing things, particularly wrt source tree layout.

ContentLicense: CC BY-SA 3.0


答:
Check the order layer if you're by mistake not covering your bullets with the background image. Just make your bullet prefab layer higher then background equivalent.

Moreover, move the background node out of the scope of Player (currently you have it in the Player node), it should be equally set as your Main Camera and Player nodes in the tree. Then check the layering order and make sure order value in background is the lowest of all of your sprites.

ContentLicense: CC BY-SA 4.0

Title: Bullets not showing in Game view


问:
Export/Package Vaadin Application
I want to be able to share my application with other people, but can't figure out how to package it / export it so that other people can also use it. I know I can use its jar, but that requires some use of Command Prompt. How would I export properly to make it run as a desktop app/web app?</p>

答:
Web app framework

Vaadin is a framework for building web apps. Applications created with the framework are supposed to be distributed via Internet (accessible via a web browser).

In brief details, the process can be described as:

Once you have developed an application, you should deploy it to a Servlet container, such as Tomcat, Jetty, and so on. Application should be packaged in production mode. This ensures minification and bundling of the front-end resources. You end up with an artifact to deploy, either a WAR file or an EAR file.

Obtain a server on the network or internet. Either:

Buy space from a hosting provider such as a Heroku or DigitalOcean.

Provide your own server hardware.

Install the Tomcat there if there is not one.

For example, look at this article, for a example : How To Install Apache Tomcat 8 on Ubuntu 16.04 and Configuring WAR Deployment with the Heroku CLI)

Once your web container is started, you users will be available to use your application via the IP address your server has. In case you want to have a dedicated name, you can buy a domain name.

Progressive web application (PWA)

Another aspect, is that you can develop your web application as a progressive web application (PWA). Still, the application runs in the browser, but an icon prompt for installing software will be added to your main page(in the browser). A user can click it and the application will be installed. But to do that you have to follow the requirements listed here : Application installation requirement

But, generally, Vaadin is not the right tool, if you want to create applications that are installed locally. I am also wondering, where you have found information that it can be installed? :)

Title: Export/Package Vaadin Application


问:
Convert a List of Object/Strings into substrings separated by comma
Please help on converting a list of objects got from DB into substrings separated by a comma

Take for example I have a sample code below:

```<code>List<string> CategoryNames = new List<string>();
CategoryNames.Add("myName1");
CategoryNames.Add("myName2");
CategoryNames.Add("myName3");
</code>```

I want to convert CategoryNames into a format like this

"myName1","myName2","myName3"

From the above CatgoryNames happen to be retrieved from db.

```<code>var categoryNames = _context.BillingCategory.ToList();
</code>```

How do I convert the categoryNames into substrings as shown above?
Any help will be appreciated.

答:
Use LINQ Select to enclose all names in quotes, then string.Join to merge back into a comma separated string.

```<code>string.Join(',', CategoryNames.Select(n => '"' + n + '"'));
</code>```

Body:
Please help on converting a list of objects got from DB into substrings separated by a comma

Take for example I have a sample code below:

List<string> CategoryNames = new List<string>();
CategoryNames.Add("myName1");
CategoryNames.Add("myName2");
CategoryNames.Add("myName3");

I want to convert CategoryNames into a format like this

"myName1","myName2","myName3"

From the above CatgoryNames happen to be retrieved from db.

var categoryNames = _context.BillingCategory.ToList();

How do I convert the categoryNames into substrings as shown above?
Any help will be appreciated.

Body:
Use LINQ Select to enclose all names in quotes, then string.Join to merge back into a comma separated string.

string.Join(',', CategoryNames.Select(n => '"' + n + '"'));


问:
Measure serialization and deserialization time
In addition to my previous question please, is there a way to measure the time it takes gremlin server to serialize and deserialize a query request from the client? For example, if the client is a java application that sends query request to gremlin server running on a remote server, is there a way to measure the time from the point gremlin server receives the request, deserializes it, before running the query?

Many thanks

答:
No - I can't think of how to do that directly, but when you write your timing requirement like this:

the time from the point gremlin server receives the request, deserializes it, before running the query

it sounds like you only care about measuring the deserialization time in which case I'd suggest that you get Gremlin Server itself out of the way and write performance tests for the deserializer directly. You could write your tests against the driver MessageSerializer implementations which can be found here. Those classes are used by both the driver and the server for all serialization/deserialization activities.

I'm not sure what kind of benchmark you are looking to write, but in the most simple case you could just instantiate the serializer you care about testing, for example, GraphSONMessageSerializerV3d0, construct a RequestMessage as a ByteBuf (the only "hard" part) and time the method call to deserializeRequest(). You can see an example of how all this works in TinkerPop's micro-benchmarks for serialization here which uses the JMH toolkit.


问:
How to Dispose subscriptions in a UserControl if you can change the VisualParent
I have a FooUserControl which subscribes on it's LoadedEvent. This UserControl can be placed else where on your gui (on any Window or inside of any Control). To avoid leaks, I have implemented some kind of disposing.

The problem with this solution:

If you put the FooUserControl on a TabItem of a TabControl  and change the tabs, the OnVisualParentChanged() is called and the subscription is disposed. If I wouldn't add this method, and you close the TabItem the subscription is still alive in background, although the UserControl can be disposed. The same problem will occur with a page

public class FooUserControl : UserControl
{
    private IDisposable _Subscription;
    public FooUserControl()
    {
        Loaded += _OnLoaded;
    }

    private void _OnLoaded(object sender, RoutedEventArgs e)
    {
        // avoid multiple subscribing
        Loaded -= _OnLoaded;

        // add hook to parent window to dispose subscription
        var parentWindow = Window.GetWindow(this);
        if(parentWindow != null)
            parentWindow.Closed += _ParentWindowOnClosed;

        _Subscription = MyObservableInstance.Subscribe(...);
    }

    private void _ParentWindowOnClosed(object? sender, EventArgs e)
    {
        _Dispose();
    }

    // check if the parent visual has been changed
    // can happen if you use the control on a page
    protected override void OnVisualParentChanged(DependencyObject oldParent)
    {
        if (oldParent != null)
        {
            _Dispose();
        }
        base.OnVisualParentChanged(oldParent);
    }

    private void _Dispose()
    {
        _Subscription?.Dispose();
    }
}
```

答:
I finally found a solution. In the UnLoaded event, I scan the Logical/VisualTree if there is still an instance present or not.

Since there is no real disposing mechanism in wpf, I have adopted this solution. I'm open for a better solution!

FooUserControl

public class FooUserControl : UserControl
{
    private IDisposable _Subscription;
    private Window _ParentWindow;

    public FooUserControl()
    {
        Loaded += _OnLoaded;
        Unloaded += _OnUnloaded;
    }

    private void _OnLoaded(object sender, RoutedEventArgs e)
    {
        // avoid multiple subscribing
        Loaded -= _OnLoaded;

        // add hook to parent window to dispose subscription
        _ParentWindow = Window.GetWindow(this);
        _ParentWindow.Closed += _ParentWindowOnClosed;

        _Subscription = MyObservableInstance.Subscribe(...);
    }

    private void _OnUnloaded(object sender, RoutedEventArgs e)
    {
        // look in logical and visual tree if the control has been removed
        if (_ParentWindow.FindChildByUid<NLogViewer>(Uid) == null)
        {
            _Dispose();
        }
    }

    private void _ParentWindowOnClosed(object? sender, EventArgs e)
    {
        _Dispose();
    }

    private void _Dispose()
    {
        _Subscription?.Dispose();
    }
}
```

<p><strong>DependencyObjectExtensions</strong></p>

<pre class="lang-cs prettyprint-override"><code>public static class DependencyObjectExtensions
{
    /// <summary>
    /// Analyzes both visual and logical tree in order to find all elements of a given
    /// type that are descendants of the <paramref name="source"/> item.
    /// </summary>
    /// <typeparam name="T">The type of the queried items.</typeparam>
    /// <param name="source">The root element that marks the source of the search. If the
    /// source is already of the requested type, it will not be included in the result.</param>
    /// <param name="uid">The UID of the <see cref="UIElement"/></param>
    /// <returns>All descendants of <paramref name="source"/> that match the requested type.</returns>
    public static T FindChildByUid<T>(this DependencyObject source, string uid) where T : UIElement
    {
        if (source != null)
        {
            var childs = GetChildObjects(source);
            foreach (DependencyObject child in childs)
            {
                //analyze if children match the requested type
                if (child != null && child is T dependencyObject && dependencyObject.Uid.Equals(uid))
                {
                    return dependencyObject;
                }

                var descendant = FindChildByUid<T>(child, uid);
                if (descendant != null)
                    return descendant;
            }
        }

        return null;
    }

    /// <summary>
    /// This method is an alternative to WPF's
    /// <see cref="VisualTreeHelper.GetChild"/> method, which also
    /// supports content elements. Keep in mind that for content elements,
    /// this method falls back to the logical tree of the element.
    /// </summary>
    /// <param name="parent">The item to be processed.</param>
    /// <returns>The submitted item's child elements, if available.</returns>
    public static IEnumerable<DependencyObject> GetChildObjects(this DependencyObject parent)
    {
        if (parent == null) yield break;

        if (parent is ContentElement || parent is FrameworkElement)
        {
            //use the logical tree for content / framework elements
            foreach (object obj in LogicalTreeHelper.GetChildren(parent))
            {
                var depObj = obj as DependencyObject;
                if (depObj != null) yield return (DependencyObject) obj;
            }
        }
        else
        {
            //use the visual tree per default
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                yield return VisualTreeHelper.GetChild(parent, i);
            }
        }
    }
}
</code>```

Body:
I finally found a solution. In the UnLoaded event, I scan the Logical/VisualTree if there is still an instance present or not.

Since there is no real disposing mechanism in wpf, I have adopted this solution. I'm open for a better solution!

FooUserControl

public class FooUserControl : UserControl
{
    private IDisposable _Subscription;
    private Window _ParentWindow;

    public FooUserControl()
    {
        Loaded += _OnLoaded;
        Unloaded += _OnUnloaded;
    }

    private void _OnLoaded(object sender, RoutedEventArgs e)
    {
        // avoid multiple subscribing
        Loaded -= _OnLoaded;

        // add hook to parent window to dispose subscription
        _ParentWindow = Window.GetWindow(this);
        _ParentWindow.Closed += _ParentWindowOnClosed;

        _Subscription = MyObservableInstance.Subscribe(...);
    }

    private void _OnUnloaded(object sender, RoutedEventArgs e)
    {
        // look in logical and visual tree if the control has been removed
        if (_ParentWindow.FindChildByUid<NLogViewer>(Uid) == null)
        {
            _Dispose();
        }
    }

    private void _ParentWindowOnClosed(object? sender, EventArgs e)
    {
        _Dispose();
    }

    private void _Dispose()
    {
        _Subscription?.Dispose();
    }
}

DependencyObjectExtensions

public static class DependencyObjectExtensions
{
    /// <summary>
    /// Analyzes both visual and logical tree in order to find all elements of a given
    /// type that are descendants of the <paramref name="source"/> item.
    /// </summary>
    /// <typeparam name="T">The type of the queried items.</typeparam>
    /// <param name="source">The root element that marks the source of the search. If the
    /// source is already of the requested type, it will not be included in the result.</param>
    /// <param name="uid">The UID of the <see cref="UIElement"/></param>
    /// <returns>All descendants of <paramref name="source"/> that match the requested type.</returns>
    public static T FindChildByUid<T>(this DependencyObject source, string uid) where T : UIElement
    {
        if (source != null)
        {
            var childs = GetChildObjects(source);
            foreach (DependencyObject child in childs)
            {
                //analyze if children match the requested type
                if (child != null && child is T dependencyObject && dependencyObject.Uid.Equals(uid))
                {
                    return dependencyObject;
                }

                var descendant = FindChildByUid<T>(child, uid);
                if (descendant != null)
                    return descendant;
            }
        }

        return null;
    }

    /// <summary>
    /// This method is an alternative to WPF's
    /// <see cref="VisualTreeHelper.GetChild"/> method, which also
    /// supports content elements. Keep in mind that for content elements,
    /// this method falls back to the logical tree of the element.
    /// </summary>
    /// <param name="parent">The item to be processed.</param>
    /// <returns>The submitted item's child elements, if available.</returns>
    public static IEnumerable<DependencyObject> GetChildObjects(this DependencyObject parent)
    {
        if (parent == null) yield break;

        if (parent is ContentElement || parent is FrameworkElement)
        {
            //use the logical tree for content / framework elements
            foreach (object obj in LogicalTreeHelper.GetChildren(parent))
            {
                var depObj = obj as DependencyObject;
                if (depObj != null) yield return (DependencyObject) obj;
            }
        }
        else
        {
            //use the visual tree per default
            int count = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < count; i++)
            {
                yield return VisualTreeHelper.GetChild(parent, i);
            }
        }
    }
}


问:
d3 node sub structure/styling based on data attribute
I'd like to create multiple functions which "style" a rectangle differently based on the data (i.e. call different .attr() or .style() functions or even appending other elements based on the data).

I managed to use .call(myDecorator) to dispatch the styling to a separate function, but here I am a little struck. In rectDecorator, I wish to call different sub-selections based on d.type. At the moment (.style('fill'...).style(...).style(...)) shows just one of those possible ways to decorate the rectangle, but ideally, I'd like to "branch" to different chained commands based on d.type. Any idea how I could accomplish that?

    function rectDecorator(selection) {
      // call different selection.xyz functions to style rect differently based on `d.type`
      return selection
        .style('fill', function(d) {
          return d.color;
        })
        .style('fill-opacity', 1)
        .style('stroke-width', 0);
    }

    d3.select('svg')
      .selectAll('g')
      .data(data)
      .join(
        enter => enter
          .append('g')
          .append('rect')
            .attr('x', ...)
            .attr('y', ...)
            .attr('height', 20)
            .attr('width', 40)
            .call(rectDecorator)
        update => update(),
        exit => exit.remove()
```

答:
There are multiple possible solutions to this, although, at some point, you will have to iterate through the selection to check each element's individual type to find the specific decorator. You could set up a Map whereby mapping the types to their corresponding decorators.

```<code>const decorators = new Map([
  ["type1", selection => selection.attr("attr1", "...")],
  ["type2", selection => selection.attr("attr2", "...")]
]);
</code>```

Afterwards, you can easily loop through the selection using .each() and get the suitable decorator from the map based on the datum's type property:

```<code>.each(function(d) {
  d3.select(this).call(decorators.get(d.type));
})
</code>```

For a working demo have a look at the following snippet:

const decorators = new Map([
    ["red", selection => selection.attr("fill", "red")],
    ["green", selection => selection.attr("fill", "none").attr("stroke", "green")]
  ]);

const data = [{ type: "green" }, { type: "red" }];

d3.select('body').append("svg")
  .selectAll('g')
  .data(data)
  .join(
    enter => enter
    .append('g')
    .append('rect')
      .attr('x', (_, i) => i * 50 + 50)
      .attr('y', 50)
      .attr('height', 20)
      .attr('width', 40)
      .each(function(d) {
        d3.select(this).call(decorators.get(d.type));
      })
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.js"></script></code>```

Body:
There are multiple possible solutions to this, although, at some point, you will have to iterate through the selection to check each element's individual type to find the specific decorator. You could set up a Map whereby mapping the types to their corresponding decorators.

const decorators = new Map([
  ["type1", selection => selection.attr("attr1", "...")],
  ["type2", selection => selection.attr("attr2", "...")]
]);

Afterwards, you can easily loop through the selection using .each() and get the suitable decorator from the map based on the datum's type property:

.each(function(d) {
  d3.select(this).call(decorators.get(d.type));
})

For a working demo have a look at the following snippet:

const decorators = new Map([
    ["red", selection => selection.attr("fill", "red")],
    ["green", selection => selection.attr("fill", "none").attr("stroke", "green")]
  ]);

const data = [{ type: "green" }, { type: "red" }];

d3.select('body').append("svg")
  .selectAll('g')
  .data(data)
  .join(
    enter => enter
    .append('g')
    .append('rect')
      .attr('x', (_, i) => i * 50 + 50)
      .attr('y', 50)
      .attr('height', 20)
      .attr('width', 40)
      .each(function(d) {
        d3.select(this).call(decorators.get(d.type));
      })
  );

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.js"></script>


问:
Distinct difference between Azure Databricks and Azure Synapse Analytics
Can someone explain the distinct difference between these two products in all major aspects? As far as I am aware from reading the official documents, both could host database systems and provide data cleaning pipeline? Both are on cloud?</p>

答:
Databricks:

Azure Databricks is an Apache Spark-based analytics platform optimized
  for the Microsoft Azure cloud services platform. Designed with the
  founders of Apache Spark, Databricks is integrated with Azure to
  provide one-click setup, streamlined workflows, and an interactive
  workspace that enables collaboration between data scientists, data
  engineers, and business analysts.

Synapse Analytics:

Azure Synapse is a limitless analytics service that brings together
  enterprise data warehousing and Big Data analytics. It gives you the
  freedom to query data on your terms, using either serverless on-demand
  or provisioned resources—at scale. Azure Synapse brings these two
  worlds together with a unified experience to ingest, prepare, manage,
  and serve data for immediate BI and machine learning needs

they do overlap to some extent, but they are not the same thing. Databricks is pretty much managed Apache Spark, whereas Synapse Analytics is managed SQL Data Warehouse.


问:
Cannot refresh or move back to previous in angular after deployment
I have just integrated my angular 6 project into laravel 5.4.

I followed the normal Laravel templating and here i put my angular index.html code inside welcome.blade.php and it worked fine. I also put the assets in the public folder. I then deployed the entire thing on a shared server.

The problem am having is that after deployment, i cannot refresh or move back to the previous page. I cannot even navigate manually to a url directly in the browser. I need a way to make laravel always load welcome.blade.php everytime i serve a request.

Thank you for any help.

this is my web.php

```<code> <?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
</code>```

then api.php

```<code>    <?php
Route::group([

    'middleware' => 'api'

], function () {

    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

});
</code>```

That's where a directing routes from .

And my welcome.blade.php contains the angular index.html code

答: I managed to solve it. The answer is actually here. Thank you very much.</p>

Body:
I have just integrated my angular 6 project into laravel 5.4.

I followed the normal Laravel templating and here i put my angular index.html code inside welcome.blade.php and it worked fine. I also put the assets in the public folder. I then deployed the entire thing on a shared server.

The problem am having is that after deployment, i cannot refresh or move back to the previous page. I cannot even navigate manually to a url directly in the browser. I need a way to make laravel always load welcome.blade.php everytime i serve a request.

Thank you for any help.

this is my web.php

 <?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

then api.php

    <?php
Route::group([

    'middleware' => 'api'

], function () {

    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

});

That's where a directing routes from .

And my welcome.blade.php contains the angular index.html code


问:
master-datasources.xml content always revert back to initial configuration when I start wso2server 5.9
I am beginner to WSO2, and I'm trying to configure Identity server data-source to PostgreSQL, using the documentation.

JDBC driver used

My latest master-datasources.xml is

```<code><datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">

    <providers>
        <provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
    </providers>

    <datasources>

        <datasource>
            <name>WSO2_CARBON_DB</name>
            <description>The datasource used for registry and user manager</description>
            <jndiConfig>
                <name>jdbc/WSO2CarbonDB</name>
            </jndiConfig>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:postgresql://localhost:5432/wso2_db</url>
                    <username>postgres</username>
                    <password>root</password>
                    <driverClassName>org.postgresql.Driver</driverClassName>
                    <maxActive>50</maxActive>
                    <maxWait>60000</maxWait>
                    <testOnBorrow>true</testOnBorrow>
                    <validationQuery>SELECT 1; COMMIT</validationQuery>
                    <validationInterval>30000</validationInterval>
                    <defaultAutoCommit>true</defaultAutoCommit>
                    <commitOnReturn>true</commitOnReturn>
                </configuration>
            </definition>
        </datasource>
        <datasource>
            <name>WSO2_SHARED_DB</name>
            <description>Shared Database for user and registry data</description>
            <jndiConfig>
                <name>jdbc/SHARED_DB</name>
            </jndiConfig>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:postgresql://localhost:5432/wso2_db</url>
                    <username>postgres</username>
                    <password>root</password>
                    <driverClassName>org.postgresql.Driver</driverClassName>
                    <testOnBorrow>true</testOnBorrow>
                    <maxWait>60000</maxWait>
                    <defaultAutoCommit>true</defaultAutoCommit>
                    <validationInterval>30000</validationInterval>
                    <maxActive>50</maxActive>
                    <jmxEnabled>false</jmxEnabled>
                 </configuration>
            </definition>
        </datasource>

     <datasource>
 <name>WSO2_IDENTITY_DB</name>
 <description>Shared database for identity data</description>
 <jndiConfig>
 <name>jdbc/WSO2IdentityDB</name>
 </jndiConfig>
 <definition type="RDBMS">
 <configuration>
 <url>jdbc:postgresql://localhost:5432/wso2_db</url>
 <username>postgres</username>
 <password>root</password>
 <driverClassName>org.postgresql.Driver</driverClassName>
 </configuration>
 </definition>
 </datasource>
 </datasources>

</datasources-configuration>
</code>```

When I start running WSO2 server , master-datasources.xml revertback to initial H2 configuration.

I modified deployment.toml based on the suggestion from @Piraveena Paralogarajah.

```<code>[server]
hostname = "localhost"
node_ip = "127.0.0.1"
base_path = "https://$ref{server.hostname}:${carbon.management.port}"

[super_admin]
username = "admin"
password = "admin"
create_admin_account = true

[user_store]
type = "read_write_ldap"
connection_url = "ldap://localhost:${Ports.EmbeddedLDAP.LDAPServerPort}"
connection_name = "uid=admin,ou=system"
connection_password = "admin"
base_dn = "dc=wso2,dc=org"      #refers the base dn on which the user and group search bases will be generated

[database.identity_db]
type = "postgre"
hostname = "localhost"
name = "wso2_db"
username = "postgres"
password = "root"
port = "5432"

[database.shared_db]
type = "postgre"
hostname = "localhost"
name = "wso2_db"
username = "postgres"
password = "root"
port = "5432"

[keystore.primary]
name = "wso2carbon.jks"
password = "wso2carbon"
</code>```

executed Query

```<code><IS-HOME>/dbscripts/identity/postgresql.sql
<IS-HOME>/dbscripts/identity/uma/postgresql.sql
<IS-HOME>/dbscripts/consent/postgresql.sql
</code>```

this time master-datasources.xml updated for postgress. But got exception while running server.

```<code>2020-02-19 16:44:35,247] [] ERROR {org.wso2.carbon.user.core.common.DefaultRealm} - nullType class java.lang.reflect.InvocationTargetException org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:397)
        at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:224)
        at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:129)
        at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:264)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:102)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:115)
        at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:72)
        at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:842)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:834)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:791)
        at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:1013)
        at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:365)
        at org.eclipse.osgi.container.Module.doStart(Module.java:598)
        at org.eclipse.osgi.container.Module.start(Module.java:462)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel$1.run(ModuleContainer.java:1820)
        at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor$2$1.execute(EquinoxContainerAdaptor.java:150)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1813)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1770)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1735)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1661)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
        at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234)
        at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:345)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:351)
        ... 25 more
Caused by: org.wso2.carbon.user.core.UserStoreException: Error occurred while checking is existing domain : PRIMARY for tenant : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:860)
        at org.wso2.carbon.user.core.common.AbstractUserStoreManager.persistDomain(AbstractUserStoreManager.java:6190)
        at org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.<init>(ReadOnlyLDAPUserStoreManager.java:240)
        at org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.<init>(ReadWriteLDAPUserStoreManager.java:120)
        ... 30 more
Caused by: org.wso2.carbon.user.core.UserStoreException: DB error occurred while checking is existing domain : PRIMARY & tenant id : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:1009)
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:849)
        ... 33 more
Caused by: org.postgresql.util.PSQLException: ERROR: relation "um_domain" does not exist
  Position: 26
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2510)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2245)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:311)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
        at com.sun.proxy.$Proxy53.executeQuery(Unknown Source)
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:998)
        ... 34 more

[2020-02-19 16:44:35,275] [] ERROR {org.wso2.carbon.user.core.internal.Activator} - Cannot start User Manager Core bundle org.wso2.carbon.user.core.UserStoreException: Cannot initialize the realm.
        at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:274)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:102)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:115)
        at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:72)
        at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:842)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:834)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:791)
        at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:1013)
        at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:365)
        at org.eclipse.osgi.container.Module.doStart(Module.java:598)
        at org.eclipse.osgi.container.Module.start(Module.java:462)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel$1.run(ModuleContainer.java:1820)
        at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor$2$1.execute(EquinoxContainerAdaptor.java:150)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1813)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1770)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1735)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1661)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
        at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234)
        at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:345)
Caused by: org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException
        at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:318)
        at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:129)
        at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:264)
        ... 22 more
Caused by: org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:397)
        at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:224)
        ... 24 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:351)
        ... 25 more
Caused by: org.wso2.carbon.user.core.UserStoreException: Error occurred while checking is existing domain : PRIMARY for tenant : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:860)
        at org.wso2.carbon.user.core.common.AbstractUserStoreManager.persistDomain(AbstractUserStoreManager.java:6190)
        at org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.<init>(ReadOnlyLDAPUserStoreManager.java:240)
        at org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.<init>(ReadWriteLDAPUserStoreManager.java:120)
        ... 30 more
Caused by: org.wso2.carbon.user.core.UserStoreException: DB error occurred while checking is existing domain : PRIMARY & tenant id : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:1009)
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:849)
        ... 33 more
Caused by: org.postgresql.util.PSQLException: ERROR: relation "um_domain" does not exist
  Position: 26
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2510)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2245)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:311)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
        at com.sun.proxy.$Proxy53.executeQuery(Unknown Source)
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:998)
        ... 34 more
</code>```

I tried this but it is not working.

答:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "um_domain" does not exist
    Position: 26

It seems you are missing some tables. Maybe your DB schema is not compliant with wso2 DB schema

To fix that you need to run WSO2 DB scripts on PostgresDB. You can find the scripts inside the product in the following paths {is-home}/dbscripts and {is-home}/dbscripts/identity. Postgres scripts are under the name of "postgres.sql".

Body:
I am beginner to WSO2, and I'm trying to configure Identity server data-source to PostgreSQL, using the documentation.

JDBC driver used

My latest master-datasources.xml is

<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">

    <providers>
        <provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
    </providers>

    <datasources>

        <datasource>
            <name>WSO2_CARBON_DB</name>
            <description>The datasource used for registry and user manager</description>
            <jndiConfig>
                <name>jdbc/WSO2CarbonDB</name>
            </jndiConfig>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:postgresql://localhost:5432/wso2_db</url>
                    <username>postgres</username>
                    <password>root</password>
                    <driverClassName>org.postgresql.Driver</driverClassName>
                    <maxActive>50</maxActive>
                    <maxWait>60000</maxWait>
                    <testOnBorrow>true</testOnBorrow>
                    <validationQuery>SELECT 1; COMMIT</validationQuery>
                    <validationInterval>30000</validationInterval>
                    <defaultAutoCommit>true</defaultAutoCommit>
                    <commitOnReturn>true</commitOnReturn>
                </configuration>
            </definition>
        </datasource>
        <datasource>
            <name>WSO2_SHARED_DB</name>
            <description>Shared Database for user and registry data</description>
            <jndiConfig>
                <name>jdbc/SHARED_DB</name>
            </jndiConfig>
            <definition type="RDBMS">
                <configuration>
                    <url>jdbc:postgresql://localhost:5432/wso2_db</url>
                    <username>postgres</username>
                    <password>root</password>
                    <driverClassName>org.postgresql.Driver</driverClassName>
                    <testOnBorrow>true</testOnBorrow>
                    <maxWait>60000</maxWait>
                    <defaultAutoCommit>true</defaultAutoCommit>
                    <validationInterval>30000</validationInterval>
                    <maxActive>50</maxActive>
                    <jmxEnabled>false</jmxEnabled>
                 </configuration>
            </definition>
        </datasource>

     <datasource>
 <name>WSO2_IDENTITY_DB</name>
 <description>Shared database for identity data</description>
 <jndiConfig>
 <name>jdbc/WSO2IdentityDB</name>
 </jndiConfig>
 <definition type="RDBMS">
 <configuration>
 <url>jdbc:postgresql://localhost:5432/wso2_db</url>
 <username>postgres</username>
 <password>root</password>
 <driverClassName>org.postgresql.Driver</driverClassName>
 </configuration>
 </definition>
 </datasource>
 </datasources>

</datasources-configuration>

When I start running WSO2 server , master-datasources.xml revertback to initial H2 configuration.

I modified deployment.toml based on the suggestion from @Piraveena Paralogarajah.

[server]
hostname = "localhost"
node_ip = "127.0.0.1"
base_path = "https://$ref{server.hostname}:${carbon.management.port}"

[super_admin]
username = "admin"
password = "admin"
create_admin_account = true

[user_store]
type = "read_write_ldap"
connection_url = "ldap://localhost:${Ports.EmbeddedLDAP.LDAPServerPort}"
connection_name = "uid=admin,ou=system"
connection_password = "admin"
base_dn = "dc=wso2,dc=org"      #refers the base dn on which the user and group search bases will be generated

[database.identity_db]
type = "postgre"
hostname = "localhost"
name = "wso2_db"
username = "postgres"
password = "root"
port = "5432"

[database.shared_db]
type = "postgre"
hostname = "localhost"
name = "wso2_db"
username = "postgres"
password = "root"
port = "5432"

[keystore.primary]
name = "wso2carbon.jks"
password = "wso2carbon"

executed Query

<IS-HOME>/dbscripts/identity/postgresql.sql
<IS-HOME>/dbscripts/identity/uma/postgresql.sql
<IS-HOME>/dbscripts/consent/postgresql.sql

this time master-datasources.xml updated for postgress. But got exception while running server.

2020-02-19 16:44:35,247] [] ERROR {org.wso2.carbon.user.core.common.DefaultRealm} - nullType class java.lang.reflect.InvocationTargetException org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:397)
        at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:224)
        at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:129)
        at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:264)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:102)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:115)
        at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:72)
        at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:842)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:834)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:791)
        at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:1013)
        at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:365)
        at org.eclipse.osgi.container.Module.doStart(Module.java:598)
        at org.eclipse.osgi.container.Module.start(Module.java:462)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel$1.run(ModuleContainer.java:1820)
        at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor$2$1.execute(EquinoxContainerAdaptor.java:150)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1813)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1770)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1735)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1661)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
        at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234)
        at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:345)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:351)
        ... 25 more
Caused by: org.wso2.carbon.user.core.UserStoreException: Error occurred while checking is existing domain : PRIMARY for tenant : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:860)
        at org.wso2.carbon.user.core.common.AbstractUserStoreManager.persistDomain(AbstractUserStoreManager.java:6190)
        at org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.<init>(ReadOnlyLDAPUserStoreManager.java:240)
        at org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.<init>(ReadWriteLDAPUserStoreManager.java:120)
        ... 30 more
Caused by: org.wso2.carbon.user.core.UserStoreException: DB error occurred while checking is existing domain : PRIMARY & tenant id : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:1009)
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:849)
        ... 33 more
Caused by: org.postgresql.util.PSQLException: ERROR: relation "um_domain" does not exist
  Position: 26
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2510)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2245)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:311)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
        at com.sun.proxy.$Proxy53.executeQuery(Unknown Source)
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:998)
        ... 34 more

[2020-02-19 16:44:35,275] [] ERROR {org.wso2.carbon.user.core.internal.Activator} - Cannot start User Manager Core bundle org.wso2.carbon.user.core.UserStoreException: Cannot initialize the realm.
        at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:274)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:102)
        at org.wso2.carbon.user.core.common.DefaultRealmService.<init>(DefaultRealmService.java:115)
        at org.wso2.carbon.user.core.internal.Activator.startDeploy(Activator.java:72)
        at org.wso2.carbon.user.core.internal.BundleCheckActivator.start(BundleCheckActivator.java:61)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:842)
        at org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:834)
        at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:791)
        at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:1013)
        at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:365)
        at org.eclipse.osgi.container.Module.doStart(Module.java:598)
        at org.eclipse.osgi.container.Module.start(Module.java:462)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel$1.run(ModuleContainer.java:1820)
        at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor$2$1.execute(EquinoxContainerAdaptor.java:150)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1813)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1770)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1735)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1661)
        at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
        at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234)
        at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:345)
Caused by: org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException
        at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:318)
        at org.wso2.carbon.user.core.common.DefaultRealm.init(DefaultRealm.java:129)
        at org.wso2.carbon.user.core.common.DefaultRealmService.initializeRealm(DefaultRealmService.java:264)
        ... 22 more
Caused by: org.wso2.carbon.user.core.UserStoreException: nullType class java.lang.reflect.InvocationTargetException
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:397)
        at org.wso2.carbon.user.core.common.DefaultRealm.initializeObjects(DefaultRealm.java:224)
        ... 24 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.wso2.carbon.user.core.common.DefaultRealm.createObjectWithOptions(DefaultRealm.java:351)
        ... 25 more
Caused by: org.wso2.carbon.user.core.UserStoreException: Error occurred while checking is existing domain : PRIMARY for tenant : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:860)
        at org.wso2.carbon.user.core.common.AbstractUserStoreManager.persistDomain(AbstractUserStoreManager.java:6190)
        at org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.<init>(ReadOnlyLDAPUserStoreManager.java:240)
        at org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.<init>(ReadWriteLDAPUserStoreManager.java:120)
        ... 30 more
Caused by: org.wso2.carbon.user.core.UserStoreException: DB error occurred while checking is existing domain : PRIMARY & tenant id : -1234
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:1009)
        at org.wso2.carbon.user.core.util.UserCoreUtil.persistDomain(UserCoreUtil.java:849)
        ... 33 more
Caused by: org.postgresql.util.PSQLException: ERROR: relation "um_domain" does not exist
  Position: 26
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2510)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2245)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:311)
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368)
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
        at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:109)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
        at com.sun.proxy.$Proxy53.executeQuery(Unknown Source)
        at org.wso2.carbon.user.core.util.UserCoreUtil.isExistingDomain(UserCoreUtil.java:998)
        ... 34 more

I tried this but it is not working.


问:
Java stream Collectors.groupingBy() with list of String
I have following class :

```<code>Class Foo{
  private String cassette;
  private List<String> organs; //["Lung","Liver"]
  //getter setter
}
</code>```

I'm collecting data into List<Foo> and I want to group them by organ as Map<String,List<Foo>>

So far I have tried following solution:

```<code>Map<Object, List<Foo>> collect = fooList
                                   .stream()
                                   .collect(Collectors.groupingBy(x -> x.getOrgan()));
</code>```

It returns Map<Object, List<Foo>> instead of Map<String,List<Foo>> as follow:

{[Lung, Liver]=[Foo [cassette=1A, organ=[Lung, Liver]]], [Liver]=[Foo
  [cassette=2A, organ=[Liver]]]}

Also, how can I make a generic method which will return Map<String,List<Foo>> when I pass only key for grouping of Type<T> for Collectors.groupingBy(T) and it will group by a specified key

答:
You are grouping by a List<String>, not by a String. To group by a String you have to pre-process the Stream to first obtain all the pairs of (String,Foo):

```<code>Map<String,List<Foo>> collect =
    fooList.stream()
           .flatMap(f -> f.getOrgan().stream().map(o -> new SimpleEntry<>(o,f)))
           .collect(Collectors.groupingBy(Map.Entry::getKey,
                                          Collectors.mapping(Map.Entry::getValue,
                                                             Collectors.toList())));
</code>```

Body:
I have following class :

Class Foo{
  private String cassette;
  private List<String> organs; //["Lung","Liver"]
  //getter setter
}

I'm collecting data into List<Foo> and I want to group them by organ as Map<String,List<Foo>>

So far I have tried following solution:

Map<Object, List<Foo>> collect = fooList
                                   .stream()
                                   .collect(Collectors.groupingBy(x -> x.getOrgan()));

It returns Map<Object, List<Foo>> instead of Map<String,List<Foo>> as follow:

{[Lung, Liver]=[Foo [cassette=1A, organ=[Lung, Liver]]], [Liver]=[Foo
  [cassette=2A, organ=[Liver]]]}

Also, how can I make a generic method which will return Map<String,List<Foo>> when I pass only key for grouping of Type<T> for Collectors.groupingBy(T) and it will group by a specified key

Body:
You are grouping by a List<String>, not by a String. To group by a String you have to pre-process the Stream to first obtain all the pairs of (String,Foo):

Map<String,List<Foo>> collect =
    fooList.stream()
           .flatMap(f -> f.getOrgan().stream().map(o -> new SimpleEntry<>(o,f)))
           .collect(Collectors.groupingBy(Map.Entry::getKey,
                                          Collectors.mapping(Map.Entry::getValue,
                                                             Collectors.toList())));


问:
Detect process exit on OSX
I want to be notified right before a process exits on OSX so that I can gather statistics about the process before it dies.  (Example specifics: I want to aggregate CPU usage for processes that have many child processes that spawn and die quickly, but use large amounts of CPU.  When sampling CPU usage via things like proc_pidinfo, processes that are born and die at rates similar to my sampling rate do not get adequately captured in my aggregate statistics.  I would like to be notified when processes die so that I can sum up their total user and system time.

So far, the approach that has seemed like it will work the best has been to use libdtrace, but I can't figure out how to set a probe for process exit using the dtrace command, much less set up libdtrace from a C program.  Any tips on setting such a dtrace probe as well as tutorials on how to use libdtrace would be greatly appreciated.

EDIT:

Alright, following the advice of a few commenters, I have managed to create a program that uses libdtrace and reliably triggers off of a process' exit.  This is great, but unfortunately I can't seem to get the PID of the process that is exiting.  It seems that calling printf() in my D program and trying to format integers is badly broken.  Specifically, if I run this program which is supposed to print out the name and PID of a process right as it's exiting, it fails miserably.  It prints some other integer, and indeed that integer is printed no matter what I try to output.  If I change the D program from

```<code>syscall::*exit*:entry {
    printf(\"%s %d\\n\", execname, curpsinfo->pr_pid);
};
</code>```

To just

```<code>syscall::*exit*:entry {
    printf(\"%d\\n\", 100);
};
</code>```

It just prints out the first three digits of the mystery integer.  Note that the process names are correct, it's just the integer -> string conversion that is failing, I believe.  Running the main dtrace program with the above D programs works properly, but I want to integrate this into a C program that I have already written a lot into, and piping subcommand outputs into that program isn't really the way I want to move forward.

Help on how to get either the buffered output from libdtrace to work properly, or alternatively to get the PID as an integer rather than a string would be great.

答:
The following example takes a UNIX process ID as argument, and watches up to 20 seconds, and reports if the process terminates in that time

```<code>// cc test.c -framework CoreFoundation -O
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
#include <sys/event.h>
static void noteProcDeath(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) {
    struct kevent kev;
    int fd = CFFileDescriptorGetNativeDescriptor(fdref);
    kevent(fd, NULL, 0, &kev, 1, NULL);
    // take action on death of process here
    printf("process with pid '%u' died\n", (unsigned int)kev.ident);
    CFFileDescriptorInvalidate(fdref);
    CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example
}
// one argument, an integer pid to watch, required
int main(int argc, char *argv[]) {
    if (argc < 2) exit(1);
    int fd = kqueue();
    struct kevent kev;
    EV_SET(&kev, atoi(argv[1]), EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
    kevent(fd, &kev, 1, NULL, 0, NULL);
    CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, noteProcDeath, NULL);
    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
    CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);
    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
    CFRelease(source);
    // run the run loop for 20 seconds
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, 20.0, false);
    return 0;
}
</code>```

For those who barely know C:

build: cc test.c -framework CoreFoundation -O

run: ./a.out 57168

57168 is the pid of the process being monitored. Kill it to test!

Surely you can increase the 20 seconds to make it last as long as you want.

Title: Detect process exit on OSX

Body:
I want to be notified right before a process exits on OSX so that I can gather statistics about the process before it dies.  (Example specifics: I want to aggregate CPU usage for processes that have many child processes that spawn and die quickly, but use large amounts of CPU.  When sampling CPU usage via things like proc_pidinfo, processes that are born and die at rates similar to my sampling rate do not get adequately captured in my aggregate statistics.  I would like to be notified when processes die so that I can sum up their total user and system time.

So far, the approach that has seemed like it will work the best has been to use libdtrace, but I can't figure out how to set a probe for process exit using the dtrace command, much less set up libdtrace from a C program.  Any tips on setting such a dtrace probe as well as tutorials on how to use libdtrace would be greatly appreciated.

EDIT:

Alright, following the advice of a few commenters, I have managed to create a program that uses libdtrace and reliably triggers off of a process' exit.  This is great, but unfortunately I can't seem to get the PID of the process that is exiting.  It seems that calling printf() in my D program and trying to format integers is badly broken.  Specifically, if I run this program which is supposed to print out the name and PID of a process right as it's exiting, it fails miserably.  It prints some other integer, and indeed that integer is printed no matter what I try to output.  If I change the D program from

syscall::*exit*:entry {
    printf(\"%s %d\\n\", execname, curpsinfo->pr_pid);
};

To just

syscall::*exit*:entry {
    printf(\"%d\\n\", 100);
};

It just prints out the first three digits of the mystery integer.  Note that the process names are correct, it's just the integer -> string conversion that is failing, I believe.  Running the main dtrace program with the above D programs works properly, but I want to integrate this into a C program that I have already written a lot into, and piping subcommand outputs into that program isn't really the way I want to move forward.

Help on how to get either the buffered output from libdtrace to work properly, or alternatively to get the PID as an integer rather than a string would be great.

Body:
The following example takes a UNIX process ID as argument, and watches up to 20 seconds, and reports if the process terminates in that time

// cc test.c -framework CoreFoundation -O
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
#include <sys/event.h>
static void noteProcDeath(CFFileDescriptorRef fdref, CFOptionFlags callBackTypes, void *info) {
    struct kevent kev;
    int fd = CFFileDescriptorGetNativeDescriptor(fdref);
    kevent(fd, NULL, 0, &kev, 1, NULL);
    // take action on death of process here
    printf("process with pid '%u' died\n", (unsigned int)kev.ident);
    CFFileDescriptorInvalidate(fdref);
    CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example
}
// one argument, an integer pid to watch, required
int main(int argc, char *argv[]) {
    if (argc < 2) exit(1);
    int fd = kqueue();
    struct kevent kev;
    EV_SET(&kev, atoi(argv[1]), EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
    kevent(fd, &kev, 1, NULL, 0, NULL);
    CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, noteProcDeath, NULL);
    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);
    CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);
    CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
    CFRelease(source);
    // run the run loop for 20 seconds
    CFRunLoopRunInMode(kCFRunLoopDefaultMode, 20.0, false);
    return 0;
}

For those who barely know C:

build: cc test.c -framework CoreFoundation -O

run: ./a.out 57168

57168 is the pid of the process being monitored. Kill it to test!

Surely you can increase the 20 seconds to make it last as long as you want.


答:
You can use string.Join() and concat with the double quotes character :

```<code>var serialized = $@"""{ string.Join(@""",""", CategoryNames) }"""; // "myName1","myName2","myName3"
</code>```

Try it yourself

Title: Convert a List of Object/Strings into substrings separated by comma

Body:
You can use string.Join() and concat with the double quotes character :

var serialized = $@"""{ string.Join(@""",""", CategoryNames) }"""; // "myName1","myName2","myName3"

Try it yourself


问:
(Laravel Eloquent) Get posts of category and all nested subcategories
I would like to retrieve all posts of chosen category and all nested subcategories. I mean sth like this:

```<code>[id= 1]-Category 1
[id= 7]--Category 1.1
[id=12]---Category 1.1.1
[id=13]---Category 1.1.2
[id= 9]--Category 1.2
[id= 3]-Category 2
</code>```

At first I tried to get recursively all IDs of chosen category and all nested subcategories and then retrieve posts with those categories IDs.

I wrote method getSubcategoriesIds($category) in controller which actually give me what I want but it returns array with duplicated ids. For instans, category 1 I get:

```<code>array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]
</code>```

How can I improve the method to return IDs without duplicates?
Or maybe there is better way to revive those posts?

Here are my files:

Model Category.php:

```<code>class Category extends Model {

    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function subcategories() {
        return $this->children()->with('subcategories');
    }

    public function parents() {
        return $this->parent()->with('parents');
    }

    public function posts(){
        return $this->hasMany('App\Post');
    }
}
</code>```

PostController.php:

```<code>public function show($id)
{
    $ids =$this->getSubcategoriesIds(Category::with('subcategories')->where('id', $id)->first()));
    $posts = Post::whereIn('category_id', $ids)->get();
    return view('post.index', compact('posts'));
}

public function getSubcategoriesIds($category) {
    $array = [$category->id];
    if(count($category->subcategories) == 0) {
        return $array;
    }
    else  {
        foreach ($category->subcategories as $subcategory) {
            array_push($array, $subcategory->id);
            if(count($subcategory->subcategories)){
                $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
            }
        }
        return $array;
    }
}

public function getChildren($subcategories, $array) {
    foreach ($subcategories as $subcategory)  {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories)){
            return $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
        }
        return $array;
    }
}
</code>```

答:
Your question: How can I improve the method to return IDs without duplicates? Or maybe there is better way to revive those posts?

```<code>$subcategoriesIds = array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]
</code>```

My answer: collect($subcategoriesIds)->unique()->all()

Check out Laravel Collection Unique Docs

Body:
I would like to retrieve all posts of chosen category and all nested subcategories. I mean sth like this:

[id= 1]-Category 1
[id= 7]--Category 1.1
[id=12]---Category 1.1.1
[id=13]---Category 1.1.2
[id= 9]--Category 1.2
[id= 3]-Category 2

At first I tried to get recursively all IDs of chosen category and all nested subcategories and then retrieve posts with those categories IDs.

I wrote method getSubcategoriesIds($category) in controller which actually give me what I want but it returns array with duplicated ids. For instans, category 1 I get:

array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]

How can I improve the method to return IDs without duplicates?
Or maybe there is better way to revive those posts?

Here are my files:

Model Category.php:

class Category extends Model {

    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function subcategories() {
        return $this->children()->with('subcategories');
    }

    public function parents() {
        return $this->parent()->with('parents');
    }

    public function posts(){
        return $this->hasMany('App\Post');
    }
}

PostController.php:

public function show($id)
{
    $ids =$this->getSubcategoriesIds(Category::with('subcategories')->where('id', $id)->first()));
    $posts = Post::whereIn('category_id', $ids)->get();
    return view('post.index', compact('posts'));
}

public function getSubcategoriesIds($category) {
    $array = [$category->id];
    if(count($category->subcategories) == 0) {
        return $array;
    }
    else  {
        foreach ($category->subcategories as $subcategory) {
            array_push($array, $subcategory->id);
            if(count($subcategory->subcategories)){
                $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
            }
        }
        return $array;
    }
}

public function getChildren($subcategories, $array) {
    foreach ($subcategories as $subcategory)  {
        array_push($array, $subcategory->id);
        if(count($subcategory->subcategories)){
            return $array = array_merge($array, $this->getChildren($subcategory->subcategories, $array));
        }
        return $array;
    }
}

Body:
Your question: How can I improve the method to return IDs without duplicates? Or maybe there is better way to revive those posts?

$subcategoriesIds = array:10 [
    0 => 1
    1 => 7
    2 => 1
    3 => 7
    4 => 12
    5 => 1
    6 => 7
    7 => 12
    8 => 13
    9 => 9
]

My answer: collect($subcategoriesIds)->unique()->all()

Check out Laravel Collection Unique Docs


问:
How I can get current active Live streams list and filter them by description and location
JAVA/YouTube API v3

I tried to do this through the developer's console
and the JSON responce is:

```<code>{
 "error": {
  "errors": [
   {
    "domain": "youtube.liveBroadcast",
    "reason": "liveStreamingNotEnabled",
    "message": "The user is not enabled for live streaming.",
    "extendedHelp": "https://www.youtube.com/features"
   }
  ],
  "code": 403,
  "message": "The user is not enabled for live streaming."
 }
}

</code>```

And PopUp that sais:

This error may be due to using an insufficient credential type. Try using OAuth 2.0.

Same response from my code run:

```<code>GoogleJsonResponseException code: 403 : The user is not enabled for live streaming.
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "youtube.liveBroadcast",
    "message" : "The user is not enabled for live streaming.",
    "reason" : "liveStreamingNotEnabled",
    "extendedHelp" : "https://www.youtube.com/features"
  } ],
  "message" : "The user is not enabled for live streaming."
}

</code>```

Ok. Thanks a lot to DaImTo!
I just don't need to use "youtube-livestreaming-api" for that!

答:
as per the documentation errors#liveBroadcasts_youtube.liveBroadcasts.transition

from comments actual usage of this api.

The user that authorized the request is not enabled to stream live video on YouTube. The user needs to enable it find more information at youtube.com/features.

The YouTube Live Streaming API lets you create, update, and manage live events on YouTube.

Body:
JAVA/YouTube API v3

I tried to do this through the developer's console
and the JSON responce is:

{
 "error": {
  "errors": [
   {
    "domain": "youtube.liveBroadcast",
    "reason": "liveStreamingNotEnabled",
    "message": "The user is not enabled for live streaming.",
    "extendedHelp": "https://www.youtube.com/features"
   }
  ],
  "code": 403,
  "message": "The user is not enabled for live streaming."
 }
}

And PopUp that sais:

This error may be due to using an insufficient credential type. Try using OAuth 2.0.

Same response from my code run:

GoogleJsonResponseException code: 403 : The user is not enabled for live streaming.
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "youtube.liveBroadcast",
    "message" : "The user is not enabled for live streaming.",
    "reason" : "liveStreamingNotEnabled",
    "extendedHelp" : "https://www.youtube.com/features"
  } ],
  "message" : "The user is not enabled for live streaming."
}

Ok. Thanks a lot to DaImTo!
I just don't need to use "youtube-livestreaming-api" for that!


问:
Hive Exists condition not working on multiple condition
I'm running the following query

```<code>select * from Data t1
where not exists (select 1 from data2 t2 where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t2.dx and
t1.diagonosiscode4 = t2.dx and
t1.diagonosiscode5 = t2.dx and
t1.diagonosiscode6 = t2.dx and
t1.diagonosiscode7 = t2.dx and
t1.diagonosiscode8 = t2.dx and
t1.diagonosiscode9 = t2.dx and
t1.diagonosiscode10 = t2.dx and
t1.diagonosiscode11 = t2.dx and
t1.diagonosiscode12 = t2.dx and
t1.diagonosiscode13 = t2.dx and
t1.diagonosiscode14 = t2.dx and
t1.diagonosiscode15 = t2.dx and
t1.diagonosiscode16 = t2.dx and
t1.diagonosiscode17 = t2.dx and
t1.diagonosiscode18 = t2.dx and
t1.diagonosiscode19 = t2.dx and
t1.diagonosiscode20 = t2.dx and
t1.diagonosiscode21 = t2.dx and
t1.diagonosiscode22 = t2.dx and
t1.diagonosiscode23 = t2.dx and
t1.diagonosiscode24 = t2.dx and
t1.diagonosiscode25 = t2.dx )
</code>```

the above query throws the following error.

org.apache.hive.service.cli.HiveSQLException: Error while compiling
  statement: FAILED: SemanticException [Error 10250]: Line 2:33 Invalid
  SubQuery expression 'dx': For Exists/Not Exists operator SubQuery must
  be Correlated.

but the same query executes when I write for a single condition

```<code>select * from Data t1
where not exists (select 1 from  Data2 t2
                  where t1.diagnosiscode3 = t2.dx)
</code>```

whether hive supports only one exists condition.

I can't able to perform multiple in condition also since hive doesn't support.

How to resolve the issue.

答:
Try using left join:

```<code>select t1.*
from Data t1 left join
     data2 t2
     on t1.diagonosiscode2 = t2.dx and
        t1.diagonosiscode3 = t2.dx and
        . . .
where t2.dx is null;
</code>```

I notice you are comparing all the codes to dx.  So you could also do:

```<code>select t1.*
from Data t1
where t1.diagonosiscode2 = t1.diagonosiscode3 and
      t1.diagonosiscode2 = t1.diagonosiscode4 and
      . . .
     not exists (select 1
                 from data2 t2
                 where t1.diagonosiscode4 = t2.dx
                );
</code>```

Body:
I'm running the following query

select * from Data t1
where not exists (select 1 from data2 t2 where
t1.diagonosiscode2 = t2.dx and
t1.diagonosiscode3 = t2.dx and
t1.diagonosiscode4 = t2.dx and
t1.diagonosiscode5 = t2.dx and
t1.diagonosiscode6 = t2.dx and
t1.diagonosiscode7 = t2.dx and
t1.diagonosiscode8 = t2.dx and
t1.diagonosiscode9 = t2.dx and
t1.diagonosiscode10 = t2.dx and
t1.diagonosiscode11 = t2.dx and
t1.diagonosiscode12 = t2.dx and
t1.diagonosiscode13 = t2.dx and
t1.diagonosiscode14 = t2.dx and
t1.diagonosiscode15 = t2.dx and
t1.diagonosiscode16 = t2.dx and
t1.diagonosiscode17 = t2.dx and
t1.diagonosiscode18 = t2.dx and
t1.diagonosiscode19 = t2.dx and
t1.diagonosiscode20 = t2.dx and
t1.diagonosiscode21 = t2.dx and
t1.diagonosiscode22 = t2.dx and
t1.diagonosiscode23 = t2.dx and
t1.diagonosiscode24 = t2.dx and
t1.diagonosiscode25 = t2.dx )

the above query throws the following error.

org.apache.hive.service.cli.HiveSQLException: Error while compiling
  statement: FAILED: SemanticException [Error 10250]: Line 2:33 Invalid
  SubQuery expression 'dx': For Exists/Not Exists operator SubQuery must
  be Correlated.

but the same query executes when I write for a single condition

select * from Data t1
where not exists (select 1 from  Data2 t2
                  where t1.diagnosiscode3 = t2.dx)

whether hive supports only one exists condition.

I can't able to perform multiple in condition also since hive doesn't support.

How to resolve the issue.

Body:
Try using left join:

select t1.*
from Data t1 left join
     data2 t2
     on t1.diagonosiscode2 = t2.dx and
        t1.diagonosiscode3 = t2.dx and
        . . .
where t2.dx is null;

I notice you are comparing all the codes to dx.  So you could also do:

select t1.*
from Data t1
where t1.diagonosiscode2 = t1.diagonosiscode3 and
      t1.diagonosiscode2 = t1.diagonosiscode4 and
      . . .
     not exists (select 1
                 from data2 t2
                 where t1.diagonosiscode4 = t2.dx
                );


问:
What can I do to fix a 504 gateway timeout error?
I have been using jquery to try and pull data from an API. However I am getting a 504 error. Even when I am using postman to test the data this happens. Can anyone suggest what I need to do to get around this?</p>

答:
One way to fix this is, Changing proxy settings to "NO PROXY" in the browser

It works in Firefox browser, Others I don't know.

Follow the steps:
1. Go to preferences (top right corner 3 lines, search in drop down)

Search for proxy (Ctrl+F)

Go inside the settings

select "NO PROXY" in the choice buttons, below "Configure Proxy Access to the Internet"

refresh web page.


问:
Doing pandas join with multiple values on the left and one on the right
I'm looking for help joining two datasets in pandas.

My first dataset is a contacts dataset, including name and an ID. The second is a deals dataset which amongst other fields includes one column with a number of comma separated contact IDs. I would like to left join the deals dataset to the contacts dataset where the contact ID matches one of the IDs in the 'associated contacts' field.

contacts_df = pd.DataFrame(
  {'name': ['John Smith', 'Jane Doe', 'James Bond'],
  'id': [1,2,3]}

deals_df = pd.DataFrame(
  {'deal_name': ['McDonalds', 'KFC'],
  'associated_contacts':['1,3','2']}```
</div>
</div>
</p>

<p>I have split the contacts in the deals dataframe into four different columns: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>deals_df[['Contact ID 1','Contact ID 2','Contact ID 3', 'Contact ID 4']] = deals_df['associated_contacts'].str.split(',',expand=True)</code>```

And tried to join this to the contacts dataset:

```<code>merged = contacts_df.merge(deals_df, how='left', left_on='id',
                    right_on=['Contact ID 1','Contact ID 2','Contact ID 3','Contact ID 4'])
</code>```

But that returned a ValueError:

```<code>ValueError: len(right_on) must equal len(left_on)
</code>```

Can anyone help me join these two datasets please? I think in my dataset each contact will only be associated with one deal. But a deal could have multiple contacts and I'd like to see the deal associated with each one.

答:
Use DataFrame.explode (pandas 0.25+) for repeat values of associated_contacts splitted by ,, laso is necessary convert column id to integers:

```<code>deals_df = (deals_df.assign(id = deals_df.pop('associated_contacts').str.split(','))
                    .explode('id')
                    .assign(id = lambda x: x['id'].astype(int)))
print (deals_df)
   deal_name  id
0  McDonalds   1
0  McDonalds   3
1        KFC   2
</code>```

Your solution should be changed with DataFrame.stack and DataFrame.join to original:

```<code>deals_df = (deals_df.join(deals_df.pop('associated_contacts')
                                  .str.split(',', expand=True)
                                  .stack()
                                  .astype(int)
                                  .reset_index(level=1, drop=True)
                                  .rename('id')))
print (deals_df)
0  McDonalds   1
0  McDonalds   3
1        KFC   2
</code>```

And then use merge with parameter on only:

```<code>merged = contacts_df.merge(deals_df, how='left', on='id')
print (merged)
         name  id  deal_name
0  John Smith   1  McDonalds
1    Jane Doe   2        KFC
2  James Bond   3  McDonalds
</code>```

Body:
I'm looking for help joining two datasets in pandas.

My first dataset is a contacts dataset, including name and an ID. The second is a deals dataset which amongst other fields includes one column with a number of comma separated contact IDs. I would like to left join the deals dataset to the contacts dataset where the contact ID matches one of the IDs in the 'associated contacts' field.

contacts_df = pd.DataFrame(
  {'name': ['John Smith', 'Jane Doe', 'James Bond'],
  'id': [1,2,3]}

deals_df = pd.DataFrame(
  {'deal_name': ['McDonalds', 'KFC'],
  'associated_contacts':['1,3','2']}

I have split the contacts in the deals dataframe into four different columns:

deals_df[['Contact ID 1','Contact ID 2','Contact ID 3', 'Contact ID 4']] = deals_df['associated_contacts'].str.split(',',expand=True)

And tried to join this to the contacts dataset:

merged = contacts_df.merge(deals_df, how='left', left_on='id',
                    right_on=['Contact ID 1','Contact ID 2','Contact ID 3','Contact ID 4'])

But that returned a ValueError:

ValueError: len(right_on) must equal len(left_on)

Can anyone help me join these two datasets please? I think in my dataset each contact will only be associated with one deal. But a deal could have multiple contacts and I'd like to see the deal associated with each one.

Body:
Use DataFrame.explode (pandas 0.25+) for repeat values of associated_contacts splitted by ,, laso is necessary convert column id to integers:

deals_df = (deals_df.assign(id = deals_df.pop('associated_contacts').str.split(','))
                    .explode('id')
                    .assign(id = lambda x: x['id'].astype(int)))
print (deals_df)
   deal_name  id
0  McDonalds   1
0  McDonalds   3
1        KFC   2

Your solution should be changed with DataFrame.stack and DataFrame.join to original:

deals_df = (deals_df.join(deals_df.pop('associated_contacts')
                                  .str.split(',', expand=True)
                                  .stack()
                                  .astype(int)
                                  .reset_index(level=1, drop=True)
                                  .rename('id')))
print (deals_df)
0  McDonalds   1
0  McDonalds   3
1        KFC   2

And then use merge with parameter on only:

merged = contacts_df.merge(deals_df, how='left', on='id')
print (merged)
         name  id  deal_name
0  John Smith   1  McDonalds
1    Jane Doe   2        KFC
2  James Bond   3  McDonalds


问:
C# How to Use button click Function from code and not only users click
Lets assume I have this code

```<code> private void Exitbtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
</code>```

And I want to call this function from another part of my code and not only from the click of the user

```<code>code...
{
    ...do something...
    Exitbtn_Click()
}
</code>```

I have tried Exitbtn.Click +=new EventHandler(Exitbtn_Click); but it doesn't work i believe it is because of the word new but I am not sure, I am new to C#

答:
As john said in the comments:</p>

```<code>  Exitbtn_Click(null, EventArgs.Empty);
</code>```

Body:
Lets assume I have this code

 private void Exitbtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

And I want to call this function from another part of my code and not only from the click of the user

code...
{
    ...do something...
    Exitbtn_Click()
}

I have tried Exitbtn.Click +=new EventHandler(Exitbtn_Click); but it doesn't work i believe it is because of the word new but I am not sure, I am new to C#

Body:
As john said in the comments:

  Exitbtn_Click(null, EventArgs.Empty);


问:
Sorting a dictionary by its sub value
I currently have a dictionary in Python3 that looks like this

```<code>{'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }
</code>```

Is there a way that I can arrange the nested dictionary that it becomes

```<code>{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}
}
</code>```

答:
here you go.</p>

```<code>  data = {'parentkey1': {'value1': 3, 'value2': 0},
  'parentkey2': {'value1': 2, 'value2': 5},
  'parentkey3': {'value1': 6, 'value2': 9},
  'parentkey4': {'value1': 8, 'value2': 3}
  }

  for key, value in data.items():
    print(value)

  print("\n")

  for key, value in data.items():
    new = {}
    if value["value1"] >=  value["value2"]:
      new["value2"] = value["value2"]
      new["value1"] = value["value1"]
    else:
      new["value1"] = value["value1"]
      new["value2"] = value["value2"]
    data[key] = new

  for key, value in data.items():
    print(value)
</code>```

Title: Sorting a dictionary by its sub value

Body:
I currently have a dictionary in Python3 that looks like this

{'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }

Is there a way that I can arrange the nested dictionary that it becomes

{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}
}

Body:
here you go.

  data = {'parentkey1': {'value1': 3, 'value2': 0},
  'parentkey2': {'value1': 2, 'value2': 5},
  'parentkey3': {'value1': 6, 'value2': 9},
  'parentkey4': {'value1': 8, 'value2': 3}
  }

  for key, value in data.items():
    print(value)

  print("\n")

  for key, value in data.items():
    new = {}
    if value["value1"] >=  value["value2"]:
      new["value2"] = value["value2"]
      new["value1"] = value["value1"]
    else:
      new["value1"] = value["value1"]
      new["value2"] = value["value2"]
    data[key] = new

  for key, value in data.items():
    print(value)