问:
CSS and JS not loading in laravel
My css and js files are not loading when i launch my project i already included the link of my files in the stylesheet of my code where it is located. I already trided several methods but it is not working

The components is directly in my public folders directory

public folder contains:

bower_components

build

css

dist

documentation

pages

plugins

my head.blade.php

```<code><head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>BET ADMIN | Dashboard</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.7 -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/bootstrap/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/font-awesome/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/Ionicons/css/ionicons.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/dist/css/AdminLTE.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/dist/css/skins/_all-skins.min.css'">
    <!-- Morris chart -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/morris .js/morris.css">
    <!-- jvectormap -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/jvectormap/jquery-jvectormap.css">
    <!-- Date Picker -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css">
    <!-- Daterange picker -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/bootstrap-daterangepicker/daterangepicker.css">
    <!-- bootstrap wysihtml5 - text editor -->
    <link rel="stylesheet" href="{{URL::to('/')}}/public/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- Google Font -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
  </head>

</code>```

my footer-scripts.blade.php

```<code><!-- jQuery 3 -->
<script src="{{URL::to('/')}}/public/bower_components/jquery/dist/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="{{URL::to('/')}}/public/bower_components/jquery-ui/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
  $.widget.bridge('uibutton', $.ui.button);
</script>
<!-- Bootstrap 3.3.7 -->
<script src="{{URL::to('/')}}/public/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="{{URL::to('/')}}/public/bower_components/raphael/raphael.min.js"></script>
<script src="{{URL::to('/')}}/public/bower_components/morris.js/morris.min.js"></script>
<!-- Sparkline -->
<script src="{{URL::to('/')}}/public/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="{{URL::to('/')}}/public/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="{{URL::to('/')}}/public/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="{{URL::to('/')}}/public/bower_components/jquery-knob/dist/jquery.knob.min.js"></script>
<!-- daterangepicker -->
<script src="{{URL::to('/')}}/public/bower_components/moment/min/moment.min.js"></script>
<script src="{{URL::to('/')}}/public/bower_components/bootstrap-daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="{{URL::to('/')}}/public/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="{{URL::to('/')}}/public/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="{{URL::to('/')}}/public/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="{{URL::to('/')}}/public/bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="{{URL::to('/')}}/public/dist/js/adminlte.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="{{URL::to('/')}}/public/dist/js/pages/dashboard.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="{{URL::to('/')}}/public/dist/js/demo.js"></script>

</code>```

demo.blade.php

```<code>
@extends('layouts.mainlayout')

@section('content')

<div>
    HELLO
</div>

@endsection

</code>```

web.php /routes

```<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('/demo', function () {
    return view('demo');
});

Auth::routes();

//Route::get('/demo', 'HomeController@index')->name('demo');

Route::get('demo', 'HomeController@index');

</code>```

HomeController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('demo');
    }
}

</code>```

答: check your chrome console through inspect element, probably the system cant find the file path..</p>

Title: CSS and JS not loading in laravel

Body:
My css and js files are not loading when i launch my project i already included the link of my files in the stylesheet of my code where it is located. I already trided several methods but it is not working

The components is directly in my public folders directory

public folder contains:

bower_components

build

css

dist

documentation

pages

plugins

my head.blade.php

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>BET ADMIN | Dashboard</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/bootstrap/dist/css/bootstrap.min.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/font-awesome/css/font-awesome.min.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/Ionicons/css/ionicons.min.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/dist/css/AdminLTE.min.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/dist/css/skins/_all-skins.min.css'">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/morris .js/morris.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/jvectormap/jquery-jvectormap.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/bower_components/bootstrap-daterangepicker/daterangepicker.css">

    <link rel="stylesheet" href="{{URL::to('/')}}/public/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">

my footer-scripts.blade.php

demo.blade.php

@extends('layouts.mainlayout')

@section('content')

    HELLO

@endsection

web.php /routes

<?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('/demo', function () {
    return view('demo');
});

Auth::routes();

//Route::get('/demo', 'HomeController@index')->name('demo');

Route::get('demo', 'HomeController@index');

HomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('demo');
    }
}


来源: stackexchange

问:
Is single threaded process contains only one thread?
Can someone give more explain for single-threaded and multi-threaded processes

Is single threaded process contains only one thread? or it means that that process can contain multiple threads and can run only one thread at a time, then context-switch between them?

If i run a java program on a single core processor is the second one would be true?

Can someone explain it further?

答:
Single threaded does not mean single-core, single process.
Single threaded processes contain the execution of instructions in a single sequence. In other words, one command is processes at a time</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Name 'Actor' is not defined
I have a problem with python programming, when I'm trying to write a game (introduced by the book: Coding Games Python DK 3), it says:
name 'Actor' is not defined.

here's my code:

```<code>import pgzrun

from random import randint

WIDTH = 400
HEIGHT = 400

dots = []
lines = []

next_dot = 0

for dot in range(0, 10):
    actor = Actor("dot")
    actor.pos = randint(20, WIDTH -20), randint (20, HEIGHT - 20)
    dots.append(actor)

def draw():
    screen.fill("black")
    number = 1
    for dot in dots:
        screen.draw.text(str(number), (dot.pos[0], dot.pos[1] + 12))
    dot.draw()
    number = number + 1

for line in lines:
    screen.draw.line(line[0], line[1], (100, 0, 0))

pgzrun.go()
</code>```

答:
This page on the Pygame site will help you run it from your IDE: https://pygame-zero.readthedocs.io/en/stable/ide-mode.html

Essentially, you have to have these two lines of code:

```<code>import pgzrun
...
...
pgzrun.go()
</code>```

But during coding, the IDE will still complain that objects and functions like screen and Actor are undefined. Pretty annoying. As far as I know, there's no way to fix it, you just have to ignore the complaints and hit Debug > Run. Provided you have no mistakes, the program will compile and run.

With regards to

```<code>import pgzrun
actor = pgzrun.Actor("dot")
</code>```

Or

```<code>from pgzrun import *
dot=Actor("dot")
</code>```

Neither of these help integrated development environments like Spyder or Visual Studio recognise objects and functions like screen and Actor

pgzrun doesn't seem to behave like a normal python library.
Pygame relies on using pgzrun to run your python script from the command line:

```<code>pgzrun mygame.py
</code>```

Title: Name 'Actor' is not defined

Body:
I have a problem with python programming, when I'm trying to write a game (introduced by the book: Coding Games Python DK 3), it says:
name 'Actor' is not defined.

here's my code:

import pgzrun

from random import randint

WIDTH = 400
HEIGHT = 400

dots = []
lines = []

next_dot = 0

for dot in range(0, 10):
    actor = Actor("dot")
    actor.pos = randint(20, WIDTH -20), randint (20, HEIGHT - 20)
    dots.append(actor)

def draw():
    screen.fill("black")
    number = 1
    for dot in dots:
        screen.draw.text(str(number), (dot.pos[0], dot.pos[1] + 12))
    dot.draw()
    number = number + 1

for line in lines:
    screen.draw.line(line[0], line[1], (100, 0, 0))

pgzrun.go()

Body:
This page on the Pygame site will help you run it from your IDE: https://pygame-zero.readthedocs.io/en/stable/ide-mode.html

Essentially, you have to have these two lines of code:

import pgzrun
...
...
pgzrun.go()

But during coding, the IDE will still complain that objects and functions like screen and Actor are undefined. Pretty annoying. As far as I know, there's no way to fix it, you just have to ignore the complaints and hit Debug > Run. Provided you have no mistakes, the program will compile and run.

With regards to

import pgzrun
actor = pgzrun.Actor("dot")

Or

from pgzrun import *
dot=Actor("dot")

Neither of these help integrated development environments like Spyder or Visual Studio recognise objects and functions like screen and Actor

pgzrun doesn't seem to behave like a normal python library.
Pygame relies on using pgzrun to run your python script from the command line:

pgzrun mygame.py


问:
JavaFX 2 BorderPane Use Full Space
I´m just facing a little issue that I can´t solve by myself.
I try to place a vBox including a TextField and a HTML-Editor in my BorderPane, but
the full space is not used. Another problem is that if I shrink the window, the html-editor
overlaps with my left option window.

```<code>private void initEditor()
{
editor = new HTMLEditor();
editor.setId("editor");
editor.lookup(".top-toolbar").setDisable(true);
editor.lookup(".top-toolbar").setManaged(false);
((ToolBar) editor.lookup(".bottom-toolbar")).getItems().addAll(FXCollections.observableArrayList(((ToolBar)editor.lookup(".top-toolbar")).getItems()));

editorBox = new VBox();
TextField field = new TextField();
field.setPrefHeight(36);
field.setId("editor-title");
editorBox.setFillWidth(true);
editorBox.getChildren().addAll(field, editor);
    root.setCenter(editorBox);
}
</code>```

答:
I was also facing the same kind of issue. My anchorPane inside borderPane was not filling up. Setting a large number for prefSize worked for me. So when border pane grows, it tries to provide as much size as possible to its child</p>

```<code>anchorPane.setMinSize(25, 25);
anchorPane.setPrefSize(25000, 25000);
</code>```

Title: JavaFX 2 BorderPane Use Full Space

Body:
I´m just facing a little issue that I can´t solve by myself.
I try to place a vBox including a TextField and a HTML-Editor in my BorderPane, but
the full space is not used. Another problem is that if I shrink the window, the html-editor
overlaps with my left option window.

private void initEditor()
{
editor = new HTMLEditor();
editor.setId("editor");
editor.lookup(".top-toolbar").setDisable(true);
editor.lookup(".top-toolbar").setManaged(false);
((ToolBar) editor.lookup(".bottom-toolbar")).getItems().addAll(FXCollections.observableArrayList(((ToolBar)editor.lookup(".top-toolbar")).getItems()));

editorBox = new VBox();
TextField field = new TextField();
field.setPrefHeight(36);
field.setId("editor-title");
editorBox.setFillWidth(true);
editorBox.getChildren().addAll(field, editor);
    root.setCenter(editorBox);
}

Body:
I was also facing the same kind of issue. My anchorPane inside borderPane was not filling up. Setting a large number for prefSize worked for me. So when border pane grows, it tries to provide as much size as possible to its child

anchorPane.setMinSize(25, 25);
anchorPane.setPrefSize(25000, 25000);


问:
SlidingUpPanelLayout and ScrollView
I have a SlidingUpPanelLayout that holds a image as a top view, and a view pager that needs to slide.
The viewpager has 3 fragments and two of them are list views. So I want to be able to expand the view pager on pulling up, and once the view pager is up I want to be able to scroll the scrollviews inside the fragments. But when pulling  down on the scrollview in case there is no more to scroll, I want to start collapsing the viewpager.
So please suggest how to make the SlidingUpPanelLayout collapse on pulling the scrollview  in case there is no more contents to scroll?

Here I post some of my code:
I have tried capture the touch events and overwrite the SlidingUpPanel onInterceptTouchEvent function in the following way:

```<code>@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (isHandled) {
        Log.i("interceptToch", "HEREEE");
        return onTouchEvent(ev);
    }
    return false;
}
</code>```

So when the SlidingUpPanelLayout is expanded I set isHandled = false. So when the  slidingUpPanelLayout expands, all touch events are passed to its child views.

And I also put onTouchEvent in the scrollView, in-order to unblock the SlidingUpPanelLayout.onInterceptTouchEvent:

```<code>public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    if (action == MotionEvent.ACTION_DOWN) {
        scroll = 0;
        y = event.getY();
    } else if (action == MotionEvent.ACTION_MOVE) {
        if (scroll_view_summary.getScrollY() == 0 && event.getY() > y) {
            scroll = scroll + 1;
            if (scroll > 2) {
                // the user has pulled the list and the slidingUpPanelLauout
                // should be able to handle the toch events again
                SlidingUpPanelLayoutCustom las =
                    ((SaleDetailsActivity) getActivity()).getLayout();
                las.setHandle(true);
                scroll = 0;
                return false;
            }
        }
    }
    return false;
}
</code>```

But this is not working. The problem is that once the scrollview.onTouch event is in MotionEvent.ACTION_MOVE  SlidingUpPanelLayout.onInterceptTouchEvent is not called. SlidingUpPanelLayout.onInterceptTouchEvent is called after MotionEvent.ACTION_CANCEL. This means that the event can't be passed to the  SlidingUpPanelLayout and the panel can't collapse.

答:
Would like to add to PAD's answer.

create a new NestedScrollableViewHelper class which will extends ScrollableViewHelper
as directed in https://github.com/umano/AndroidSlidingUpPanel#scrollable-sliding-views

and then set it in your mainActivity:

slidingUpPanelLayout = findViewById(R.id.slidingpanel);
slidingUpPanelLayout.setScrollableViewHelper(new NestedScrollableViewHelper());

without this, SlidingUpPanel is not intercepting the touch while scrolling down in
 inner nestedscrollview or scrollview and is scrolling the SlidingUpPanel itself down.

scrolling up is working fine.

Title: SlidingUpPanelLayout and ScrollView

Body:
I have a SlidingUpPanelLayout that holds a image as a top view, and a view pager that needs to slide.
The viewpager has 3 fragments and two of them are list views. So I want to be able to expand the view pager on pulling up, and once the view pager is up I want to be able to scroll the scrollviews inside the fragments. But when pulling  down on the scrollview in case there is no more to scroll, I want to start collapsing the viewpager.
So please suggest how to make the SlidingUpPanelLayout collapse on pulling the scrollview  in case there is no more contents to scroll?

Here I post some of my code:
I have tried capture the touch events and overwrite the SlidingUpPanel onInterceptTouchEvent function in the following way:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (isHandled) {
        Log.i("interceptToch", "HEREEE");
        return onTouchEvent(ev);
    }
    return false;
}

So when the SlidingUpPanelLayout is expanded I set isHandled = false. So when the  slidingUpPanelLayout expands, all touch events are passed to its child views.

And I also put onTouchEvent in the scrollView, in-order to unblock the SlidingUpPanelLayout.onInterceptTouchEvent:

public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    if (action == MotionEvent.ACTION_DOWN) {
        scroll = 0;
        y = event.getY();
    } else if (action == MotionEvent.ACTION_MOVE) {
        if (scroll_view_summary.getScrollY() == 0 && event.getY() > y) {
            scroll = scroll + 1;
            if (scroll > 2) {
                // the user has pulled the list and the slidingUpPanelLauout
                // should be able to handle the toch events again
                SlidingUpPanelLayoutCustom las =
                    ((SaleDetailsActivity) getActivity()).getLayout();
                las.setHandle(true);
                scroll = 0;
                return false;
            }
        }
    }
    return false;
}

But this is not working. The problem is that once the scrollview.onTouch event is in MotionEvent.ACTION_MOVE  SlidingUpPanelLayout.onInterceptTouchEvent is not called. SlidingUpPanelLayout.onInterceptTouchEvent is called after MotionEvent.ACTION_CANCEL. This means that the event can't be passed to the  SlidingUpPanelLayout and the panel can't collapse.


问:
Invalid shorthand property initializer in Chrome Console
I do not know why I got Uncaught SyntaxError for this code</p>

```<code>const relationship2 = {
    name = 'zero',
    friends: ['nero', 'hero', 'xero'],
        logFriends() {
            this.friends.forEach(friend => {
                console.log(this.name, frined);
            });
        },
};
</code>```

答:
Object needs key/value pair which are seprated by :not =

change this

```<code>name = 'zero',
</code>```

to this

```<code>name : 'zero',
</code>```

Body:
I do not know why I got Uncaught SyntaxError for this code

const relationship2 = {
    name = 'zero',
    friends: ['nero', 'hero', 'xero'],
        logFriends() {
            this.friends.forEach(friend => {
                console.log(this.name, frined);
            });
        },
};

Body:
Object needs key/value pair which are seprated by :not =

change this

name = 'zero',

to this

name : 'zero',


问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

答:
This was just asked a couple of days ago (but I cannot find it):

```<code>>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]
</code>```

It might be better to use sets from the beginning, depending on the context. Then you can use set operations like other answers show.

However, converting lists to sets and back only for these operations is slower than list comprehension.

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
This was just asked a couple of days ago (but I cannot find it):

>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]

It might be better to use sets from the beginning, depending on the context. Then you can use set operations like other answers show.

However, converting lists to sets and back only for these operations is slower than list comprehension.


问:
A better way of visualizing extreme oscillation curve in matlibplot?
Here are three curve

All the curve contains so many spikes and noises. I'm interesting to see which curve has less chaos

One way is to use np.convolve to smooth the curve. Unfortunately, it lost so much information and defeat my original purposes.

I'm wondering if there different way of visualization ? (Not necessarily plotting the curve but use some math theorem to visualize the chaos in a different way)

答: Maybe Flatten out your plot by specifying the width, height for you plot.</p>


问:
How to save data that I fetched from API, using SharedPreferences in Kotlin Android Studio
I have used Retrofit to make an API call. Now I want to save the data using SharedPreferences and to check Previous Promotional Data Method.. Promotional is keyword used by me.

I have created a retrofit instance, declared API services and created a required function in viewmodel class.
Now I have created a method in getpromotinalDetails in FragmentHome which will be used to save data.
In onViewCreated method, doInitialSetup() method has been created and in that I will check Previous Promotional Data Method.

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    doInitialSetup()
    getPromotionalDetails()
}

private fun getPromotionalDetails() {
    mUserViewModel?.getPromotionalDetails()?.observe(this, Observer { promotionBanner ->
        if (promotionBanner.apiStatus == ApiStatusTypes.SUCCESS) {
            //todo: save data
        } else {
            //Log.d("response", "failed")
        }
    })
}
</code>```

答:
For Andorid

//these code is for saving json data received from api*

```<code>try
{
String dataReceived=jsonObject.setString("data");
SharedPreferences sharedpreferences = getSharedPreferences("mydata", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("saveddata",dataReceived);
editor.commit();
}
catch(Exception e)
{}
</code>```

//these code is for fetching  data stored in shared preference*

```<code> SharedPreferences sharedpreferences = getSharedPreferences("mydata",
                Context.MODE_PRIVATE);
if (sharedpreferences.contains("saveddata")) {
            String datafetched=sharedpreferences.getString("saveddata", ""));
        }
</code>```

Body:
I have used Retrofit to make an API call. Now I want to save the data using SharedPreferences and to check Previous Promotional Data Method.. Promotional is keyword used by me.

I have created a retrofit instance, declared API services and created a required function in viewmodel class.
Now I have created a method in getpromotinalDetails in FragmentHome which will be used to save data.
In onViewCreated method, doInitialSetup() method has been created and in that I will check Previous Promotional Data Method.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    doInitialSetup()
    getPromotionalDetails()
}

private fun getPromotionalDetails() {
    mUserViewModel?.getPromotionalDetails()?.observe(this, Observer { promotionBanner ->
        if (promotionBanner.apiStatus == ApiStatusTypes.SUCCESS) {
            //todo: save data
        } else {
            //Log.d("response", "failed")
        }
    })
}

Body:
For Andorid

//these code is for saving json data received from api*

try
{
String dataReceived=jsonObject.setString("data");
SharedPreferences sharedpreferences = getSharedPreferences("mydata", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("saveddata",dataReceived);
editor.commit();
}
catch(Exception e)
{}

//these code is for fetching  data stored in shared preference*

 SharedPreferences sharedpreferences = getSharedPreferences("mydata",
                Context.MODE_PRIVATE);
if (sharedpreferences.contains("saveddata")) {
            String datafetched=sharedpreferences.getString("saveddata", ""));
        }


问:
How to use intersect in a query?
I have 2 tables. I want to check the very last data inserted in the tables.
So, I want to retrieve the last data from both tables and then check if that last data from both tables are same or not.

```<code>$q1 =   "SELECT * ".
        "FROM `admin`, `student` ".
        "ORDER BY `admin`.`id` DESC  LIMIT 1 ".
        "INTERSECT".
        "SELECT *".
        "FROM `admin`, `student`".
        "WHERE `admin`.`pcode` = `student`.`code` AND
`admin`.`puser_name` = `student`.`puser_name`";
</code>```

I cannot use intersect operator so I am getting difficulty in changing in other form.

答:
Try this query:

```<code>$q1 =   "SELECT * FROM admin, student ORDER BY admin.id DESC  LIMIT 1
        INTERSECT
        SELECT * FROM admin, student
        WHERE admin.pcode = student.code AND admin.puser_name = student.puser_name
        ";
</code>```

Hope will help

Title: How to use intersect in a query?

Body:
I have 2 tables. I want to check the very last data inserted in the tables.
So, I want to retrieve the last data from both tables and then check if that last data from both tables are same or not.

$q1 =   "SELECT * ".
        "FROM `admin`, `student` ".
        "ORDER BY `admin`.`id` DESC  LIMIT 1 ".
        "INTERSECT".
        "SELECT *".
        "FROM `admin`, `student`".
        "WHERE `admin`.`pcode` = `student`.`code` AND
`admin`.`puser_name` = `student`.`puser_name`";

I cannot use intersect operator so I am getting difficulty in changing in other form.

Body:
Try this query:

$q1 =   "SELECT * FROM admin, student ORDER BY admin.id DESC  LIMIT 1
        INTERSECT
        SELECT * FROM admin, student
        WHERE admin.pcode = student.code AND admin.puser_name = student.puser_name
        ";

Hope will help


问:
F#: How to "await" a function in a handler so that exception still bubble up to the handler?
I want to offload the handler used for a subscription for RabbitMQ with EasyNetQ, in C# I get what I want cause the handler itself is tagged as async and hence inside I can then await the offloading, in other words:

var subscription = bus.PubSub.Subscribe<Message>("subscriptionId", async message =>
{
    // Await Offloading
    await Task.Run(() =>
    {
        // If it throws something here, it still bubble up to the handler
    });
});
```

<p>However, in F# I am completely puzzled, does the C# code can be properly translated to F#?</p>

<p>I started to draft something, but this is clearly not the solution</p>

<pre class="lang-ml prettyprint-override"><code>let handle (message: Message) = async{
    printfn "%A" message
}

let subscription = bus.PubSub.Subscribe<Message>("subscriptionId", fun message ->
    handle message
    |> Async.Start
    )
</code>```

This F# snippet does not properly address my question, it's two-folded:

handle is not awaited

exceptions that can occur in handle do not bubble up to the fun handler

Another improper way to tackle the problem is:

let handle (message: Message) = async{
    printfn "%A" message
}

let subscription = bus.PubSub.Subscribe<Message>("subscriptionId", fun message ->
    handle message
    |> Async.RunSynchronously
    )
```

But although this is awaited (unlike the snippet above), this one runs on the same thread and does not offload the work onto a threadpool thread.

答:
A close approximation of what you're looking for would be something like this:

```<code>bus.PubSub.SubscribeAsync<Message>("subscriptionId", fun message ->
        async {
            do! handle message
        }
        |> Async.StartAsTask :> Task)
</code>```

async-await constructs in C# only provide syntax sugar for composing Tasks - all the .***Async methods that are now ubiquitous in .NET apis are entirely usable from F#, though sometimes the necessary plumbing code can get unwieldy. The situation there might be improving in the future though.

Body:
I want to offload the handler used for a subscription for RabbitMQ with EasyNetQ, in C# I get what I want cause the handler itself is tagged as async and hence inside I can then await the offloading, in other words:

var subscription = bus.PubSub.Subscribe<Message>("subscriptionId", async message =>
{
    // Await Offloading
    await Task.Run(() =>
    {
        // If it throws something here, it still bubble up to the handler
    });
});

However, in F# I am completely puzzled, does the C# code can be properly translated to F#?

I started to draft something, but this is clearly not the solution

let handle (message: Message) = async{
    printfn "%A" message
}

let subscription = bus.PubSub.Subscribe<Message>("subscriptionId", fun message ->
    handle message
    |> Async.Start
    )

This F# snippet does not properly address my question, it's two-folded:

handle is not awaited

exceptions that can occur in handle do not bubble up to the fun handler

Another improper way to tackle the problem is:

let handle (message: Message) = async{
    printfn "%A" message
}

let subscription = bus.PubSub.Subscribe<Message>("subscriptionId", fun message ->
    handle message
    |> Async.RunSynchronously
    )

But although this is awaited (unlike the snippet above), this one runs on the same thread and does not offload the work onto a threadpool thread.

Body:
A close approximation of what you're looking for would be something like this:

bus.PubSub.SubscribeAsync<Message>("subscriptionId", fun message ->
        async {
            do! handle message
        }
        |> Async.StartAsTask :> Task)

async-await constructs in C# only provide syntax sugar for composing Tasks - all the .***Async methods that are now ubiquitous in .NET apis are entirely usable from F#, though sometimes the necessary plumbing code can get unwieldy. The situation there might be improving in the future though.


问:
Sqlite order by rows order
I am using this query

```<code>"select * from SomeTable group by SomeColumn"
</code>```

It is returns list with accenting order, but i need to same order like in database.

For example the order in database is:

```<code>p

a

s
</code>```

But result is:

```<code>a

i

p
</code>```

Sample

The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul

答:
In your statement, add this line to sort the results:</p>

```<code>order by min(rowid)
</code>```

Title: Sqlite order by rows order

Body:
I am using this query

"select * from SomeTable group by SomeColumn"

It is returns list with accenting order, but i need to same order like in database.

For example the order in database is:

p

a

s

But result is:

a

i

p

Sample

The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul

Body:
In your statement, add this line to sort the results:

order by min(rowid)


问:
Dynamic-height UICollectionView inside a dynamic-height UITableViewCell
I have a horizontal UICollectionView pinned to all edges of a UITableViewCell. Items in the collection view are dynamically sized, and I want to make the table view's height equal to that of the tallest collection view cell.

The views are structured as follows:

UITableView

UITableViewCell

UICollectionView

UICollectionViewCell

UICollectionViewCell

UICollectionViewCell

```<code>class TableViewCell: UITableViewCell {

    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout)
        return collectionView
    }()

    var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.estimatedItemSize = CGSize(width: 350, height: 20)
        layout.scrollDirection = .horizontal
        return layout
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let nib = UINib(nibName: String(describing: CollectionViewCell.self), bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: CollectionViewCellModel.identifier)

        addSubview(collectionView)

        // (using SnapKit)
        collectionView.snp.makeConstraints { (make) in
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        collectionView.layoutIfNeeded()
        collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width , height: 1)

        return layout.collectionViewContentSize
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let spacing: CGFloat = 50
        layout.sectionInset = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: spacing)
        layout.minimumLineSpacing = spacing
    }
}

class OptionsCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        contentView.translatesAutoresizingMaskIntoConstraints = false

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
    }
}

class CollectionViewFlowLayout: UICollectionViewFlowLayout {

    private var contentHeight: CGFloat = 500
    private var contentWidth: CGFloat = 200

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        if let attrs = super.layoutAttributesForElements(in: rect) {
           // perform some logic
           contentHeight = /* something */
           contentWidth = /* something */
           return attrs
        }
        return nil
    }

    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: contentHeight)
    }
}
</code>```

In my UIViewController, I have tableView.estimatedRowHeight = 500 and tableView.rowHeight = UITableView.automaticDimension.

I'm trying to make the table view cell's size in systemLayoutSizeFitting equal to the collectionViewContentSize, but it's called before the layout has had a chance to set collectionViewContentSize to the correct value. Here's the order in which these methods are called:

```<code>cellForRowAt
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
**OptionsTableViewCell systemLayoutSizeFitting (200.0, 500.0) << incorrect/original value**
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
willDisplay cell
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
TableViewCell layoutSubviews() collectionViewContentSize.height:  500.0 << incorrect/original value
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height
</code>```

How can I make my table view cell's height equal to my collection view's tallest item, represented by the layout's collectionViewContentSize?

答:
There are some steps to achieve this:

Defining selfsizing UICollectionViewCell

Defining selfsizing UICollectionView

Defining selfsizing UITableViewCell

Calculate all cell sizes and find the tallest (Could be expensive)

Reload higher order view of any child's bounds changed

- Defining selfsizing UICollectionViewCell

You have two options here:
- use autolayout with selfsizing UI elements (like UIImageView or UILabel or etc.)
- calculate and provide it's size your self

-
Use autolayout with selfsizing UI elements:

if you set the estimatedItemsSize to be automatic and layout cell subviews correctly with selfsizing UI elements, it would be automatically sizing on the fly. BUT be aware of expensive layout time and lags because of complex layouts. Specially on older devices.

-
Calculate and provide it's size your self:

One of the best places that you can setup the cell size is intrinsicContentSize. Although there are other places to do this (eg. in flowLayout class or etc), this is were you can guarantee that cell will not conflict with other selfsizing UI elements:

```<code>override open var intrinsicContentSize: CGSize { return /*CGSize you prefered*/ }
</code>```

- Defining selfsizing UICollectionView

Any UIScrollView subclass can be selfsizing duo to it's contentSize. Since collectionView and tableView content sizes are constantly changing, you should inform the layouter (not known as layouter anywhere officially):

```<code>protocol CollectionViewSelfSizingDelegate: class {
    func collectionView(_ collectionView: UICollectionView, didChageContentSizeFrom oldSize: CGSize, to newSize: CGSize)
}

class SelfSizingCollectionView: UICollectionView {

    weak var selfSizingDelegate: CollectionViewSelfSizingDelegate?

    override open var intrinsicContentSize: CGSize {
        return contentSize
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        if let floawLayout = collectionViewLayout as? UICollectionViewFlowLayout {
            floawLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        } else {
            assertionFailure("Collection view layout is not flow layout. SelfSizing may not work")
        }
    }

    override open var contentSize: CGSize {
        didSet {
            guard bounds.size.height != contentSize.height else { return }
            frame.size.height = contentSize.height
            invalidateIntrinsicContentSize()

            selfSizingDelegate?.collectionView(self, didChageContentSizeFrom: oldValue, to: contentSize)
        }
    }
}
</code>```

So after overriding intrinsicContentSize we observe for changes of contentSize and inform the selfSizingDelegate that will need to know about this.

- Defining selfsizing UITableViewCell

This cells can be selfsizing by implementing this in their tableView:

```<code>override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}
</code>```

We will put a selfSizingCollectionView in this cell and implement this:

```<code>class SelfSizingTableViewCell: UITableViewCell {

    @IBOutlet weak var collectionView: SelfSizingCollectionView!

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        return collectionView.frame.size
    }

    override func awakeFromNib() {
        ...
        collectionView.selfSizingDelegate = self
    }
}
</code>```

So we conform the delegate and implement the function to update cell.

```<code>extension SelfSizingTableViewCell: CollectionViewSelfSizingDelegate {

    func collectionView(_ collectionView: UICollectionView, didChageContentSizeFrom oldSize: CGSize, to newSize: CGSize) {
        if let indexPath = indexPath {
            tableView?.reloadRows(at: [indexPath], with: .none)
        } else {
            tableView?.reloadData()
        }
    }
}
</code>```

Note that I wrote some helper extensions for UIView and UITableViewCell to access parent table view:

```<code>extension UIView {

    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

extension UITableViewCell {

    var tableView: UITableView? {
        return (next as? UITableView) ?? (parentViewController as? UITableViewController)?.tableView
    }

    var indexPath: IndexPath? {
        return tableView?.indexPath(for: self)
    }
}
</code>```

To this point, your collection view will have exactly needed height (if it is vertical) but you should remember to limit all cell widths in order to not goes beyond screen width.

```<code>extension SelfSizingTableViewCell: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: frame.width, height: heights[indexPath.row])
    }
}
</code>```

Notice heights ? this is where you should cache (manual/automatic) calculated height of all cells in order to not getting laggy. (I generate all of them randomly for testing purposes)

- Last two steps:

Last two steps are already covered but you should consider some important things about the case you seek:

1 - Autolayout could be epic performance killer if you ask it to calculate all cellsizes for you, but it's reliable.

2 - You must cache all sizes and get the tallest and return it in tableView(:,heightForRowAt:) (No more need for selfsizing tableViewCell)

3 - Consider the tallest one could be taller than entire tableView and 2D scrolling would be strange.

4 - If you reuse a cell containing a collectionView or tableView, the scroll offset, inset and many other attributes behave strange the way you're not expecting.

This is one of the most complex layouts of all you could meet, but once you get used to it, it become simple.

Body:
I have a horizontal UICollectionView pinned to all edges of a UITableViewCell. Items in the collection view are dynamically sized, and I want to make the table view's height equal to that of the tallest collection view cell.

The views are structured as follows:

UITableView

UITableViewCell

UICollectionView

UICollectionViewCell

UICollectionViewCell

UICollectionViewCell

class TableViewCell: UITableViewCell {

    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout)
        return collectionView
    }()

    var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.estimatedItemSize = CGSize(width: 350, height: 20)
        layout.scrollDirection = .horizontal
        return layout
    }()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let nib = UINib(nibName: String(describing: CollectionViewCell.self), bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier: CollectionViewCellModel.identifier)

        addSubview(collectionView)

        // (using SnapKit)
        collectionView.snp.makeConstraints { (make) in
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        collectionView.layoutIfNeeded()
        collectionView.frame = CGRect(x: 0, y: 0, width: targetSize.width , height: 1)

        return layout.collectionViewContentSize
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        let spacing: CGFloat = 50
        layout.sectionInset = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: spacing)
        layout.minimumLineSpacing = spacing
    }
}

class OptionsCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        contentView.translatesAutoresizingMaskIntoConstraints = false

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
    }
}

class CollectionViewFlowLayout: UICollectionViewFlowLayout {

    private var contentHeight: CGFloat = 500
    private var contentWidth: CGFloat = 200

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        if let attrs = super.layoutAttributesForElements(in: rect) {
           // perform some logic
           contentHeight = /* something */
           contentWidth = /* something */
           return attrs
        }
        return nil
    }

    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: contentHeight)
    }
}

In my UIViewController, I have tableView.estimatedRowHeight = 500 and tableView.rowHeight = UITableView.automaticDimension.

I'm trying to make the table view cell's size in systemLayoutSizeFitting equal to the collectionViewContentSize, but it's called before the layout has had a chance to set collectionViewContentSize to the correct value. Here's the order in which these methods are called:

cellForRowAt
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
**OptionsTableViewCell systemLayoutSizeFitting (200.0, 500.0) << incorrect/original value**
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
willDisplay cell
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
TableViewCell layoutSubviews() collectionViewContentSize.height:  500.0 << incorrect/original value
CollectionViewFlowLayout collectionViewContentSize:  (200.0, 500.0) << incorrect/original value
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewCell systemLayoutSizeFitting
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 20.0)
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height
CollectionViewFlowLayout layoutAttributesForElements
CollectionViewFlowLayout collectionViewContentSize:  (450.0, 301.0) << correct size
TableViewCell layoutSubviews() collectionViewContentSize.height:  301.0 << correct height

How can I make my table view cell's height equal to my collection view's tallest item, represented by the layout's collectionViewContentSize?

Body:
There are some steps to achieve this:

Defining selfsizing UICollectionViewCell

Defining selfsizing UICollectionView

Defining selfsizing UITableViewCell

Calculate all cell sizes and find the tallest (Could be expensive)

Reload higher order view of any child's bounds changed

- Defining selfsizing UICollectionViewCell

You have two options here:
- use autolayout with selfsizing UI elements (like UIImageView or UILabel or etc.)
- calculate and provide it's size your self

-
Use autolayout with selfsizing UI elements:

if you set the estimatedItemsSize to be automatic and layout cell subviews correctly with selfsizing UI elements, it would be automatically sizing on the fly. BUT be aware of expensive layout time and lags because of complex layouts. Specially on older devices.

-
Calculate and provide it's size your self:

One of the best places that you can setup the cell size is intrinsicContentSize. Although there are other places to do this (eg. in flowLayout class or etc), this is were you can guarantee that cell will not conflict with other selfsizing UI elements:

override open var intrinsicContentSize: CGSize { return /*CGSize you prefered*/ }

- Defining selfsizing UICollectionView

Any UIScrollView subclass can be selfsizing duo to it's contentSize. Since collectionView and tableView content sizes are constantly changing, you should inform the layouter (not known as layouter anywhere officially):

protocol CollectionViewSelfSizingDelegate: class {
    func collectionView(_ collectionView: UICollectionView, didChageContentSizeFrom oldSize: CGSize, to newSize: CGSize)
}

class SelfSizingCollectionView: UICollectionView {

    weak var selfSizingDelegate: CollectionViewSelfSizingDelegate?

    override open var intrinsicContentSize: CGSize {
        return contentSize
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        if let floawLayout = collectionViewLayout as? UICollectionViewFlowLayout {
            floawLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        } else {
            assertionFailure("Collection view layout is not flow layout. SelfSizing may not work")
        }
    }

    override open var contentSize: CGSize {
        didSet {
            guard bounds.size.height != contentSize.height else { return }
            frame.size.height = contentSize.height
            invalidateIntrinsicContentSize()

            selfSizingDelegate?.collectionView(self, didChageContentSizeFrom: oldValue, to: contentSize)
        }
    }
}

So after overriding intrinsicContentSize we observe for changes of contentSize and inform the selfSizingDelegate that will need to know about this.

- Defining selfsizing UITableViewCell

This cells can be selfsizing by implementing this in their tableView:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

We will put a selfSizingCollectionView in this cell and implement this:

class SelfSizingTableViewCell: UITableViewCell {

    @IBOutlet weak var collectionView: SelfSizingCollectionView!

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        return collectionView.frame.size
    }

    override func awakeFromNib() {
        ...
        collectionView.selfSizingDelegate = self
    }
}

So we conform the delegate and implement the function to update cell.

extension SelfSizingTableViewCell: CollectionViewSelfSizingDelegate {

    func collectionView(_ collectionView: UICollectionView, didChageContentSizeFrom oldSize: CGSize, to newSize: CGSize) {
        if let indexPath = indexPath {
            tableView?.reloadRows(at: [indexPath], with: .none)
        } else {
            tableView?.reloadData()
        }
    }
}

Note that I wrote some helper extensions for UIView and UITableViewCell to access parent table view:

extension UIView {

    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

extension UITableViewCell {

    var tableView: UITableView? {
        return (next as? UITableView) ?? (parentViewController as? UITableViewController)?.tableView
    }

    var indexPath: IndexPath? {
        return tableView?.indexPath(for: self)
    }
}

To this point, your collection view will have exactly needed height (if it is vertical) but you should remember to limit all cell widths in order to not goes beyond screen width.

extension SelfSizingTableViewCell: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: frame.width, height: heights[indexPath.row])
    }
}

Notice heights ? this is where you should cache (manual/automatic) calculated height of all cells in order to not getting laggy. (I generate all of them randomly for testing purposes)

- Last two steps:

Last two steps are already covered but you should consider some important things about the case you seek:

1 - Autolayout could be epic performance killer if you ask it to calculate all cellsizes for you, but it's reliable.

2 - You must cache all sizes and get the tallest and return it in tableView(:,heightForRowAt:) (No more need for selfsizing tableViewCell)

3 - Consider the tallest one could be taller than entire tableView and 2D scrolling would be strange.

4 - If you reuse a cell containing a collectionView or tableView, the scroll offset, inset and many other attributes behave strange the way you're not expecting.

This is one of the most complex layouts of all you could meet, but once you get used to it, it become simple.


答:
In Sqlite, each row of a table has a unique rowid, which you can use for sorting.</p>

```<code>select * from SomeTable group by SomeColumn order by rowid;
</code>```

Title: Sqlite order by rows order

Body:
In Sqlite, each row of a table has a unique rowid, which you can use for sorting.

select * from SomeTable group by SomeColumn order by rowid;


问:
Parsing & converting nested xml in python
I have below xml data.

```<code><transaction>
        <date>20190415</date>
        <ticket>303434037</ticket>
        <value>15</value>
        <notenders>01</notenders>
        <tenderdetail>
            <tendertype>00</tendertype>
            <tenderamt>15</tenderamt>
        </tenderdetail>
        <item>
            <receipeno>00001096</receipeno>
            <price>7</price>
            <qty>0001</qty>
            <items>
                <item>
                    <receipeno>00000786</receipeno>
                    <price>8</price>
                    <qty>0001</qty>
                    <items>
                        <item>
                            <receipeno>00000599</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000605</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000608</receipeno>
                            <price>0</price>
                            <qty>0004</qty>
                        </item>
                    </items>
                </item>
                <item>
                    <receipeno>10000043</receipeno>
                    <price>0</price>
                    <qty>0001</qty>
                </item>
                <item>
                    <receipeno>00000381</receipeno>
                    <price>7</price>
                    <qty>0001</qty>
                    <items>
                    <item>
                            <receipeno>00000607</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                    </items>
                </item>
            </items>
        </item>
   </transaction>
</code>```

I need to convert this to a table format. the issues is there are many nested branches inside each tag. eg many <item> & <items> tags. irrespective of the nested-ness. I need to list down the data one below he other.

my desired output is as follows

```<code> +----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
|   date   | ticket | value | notenders | tendertype | tenderamt | receipeno | price | qty |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
| 20190101 |  12345 |    15 |         1 |          0 |        15 |      1096 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       786 |     8 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       599 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       605 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       608 |     0 |   4 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       143 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       381 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       607 |     0 |   1 |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
</code>```

I'm new to python & XML parsing. Hence, kindly, direct me to solve this.
...

答:
Start from necessary imports:

```<code>import pandas as pd
import xml.etree.ElementTree as et
import re
</code>```

Then, to remove leading zeroes from tags to be read, define the following function:

```<code>def stripLZ(src):
    return re.sub(r'^0+(?=\d)', '', src)
</code>```

To read the source file and its root element, execute:

```<code>tree = et.parse('transaction.xml')
root = tree.getroot()
</code>```

To read tags from the root level (other than read from items), execute:

```<code>dt = root.find('date').text
tck = root.find('ticket').text
val = root.find('value').text
notend = stripLZ(root.find('notenders').text)
</code>```

Two remaining tags are one level down, so start from reading their parent tag:

```<code>tdet = root.find('tenderdetail')
</code>```

and read these tags from it:

```<code>tendtyp = stripLZ(tdet.find('tendertype').text)
tendamt = tdet.find('tenderamt').text
</code>```

Note that I used stripLZ function here (it will be used
a few times more).

Now there is time to create the result DataFrame:

```<code>df_cols = ['date', 'ticket', 'value', 'notenders',
    'tendertype', 'tenderamt', 'receipeno', 'price', 'qty']
df = pd.DataFrame(columns = df_cols)
</code>```

And the loading loop can be performed using iter method:

```<code>for it in root.iter('item'):
    rcp = it.find('receipeno').text
    prc = it.find('price').text
    qty = stripLZ(it.find('qty').text)
    df = df.append(pd.Series([dt, tck, val, notend,
        tendtyp, tendamt, rcp, prc, qty],
        index = df_cols), ignore_index=True)
</code>```

This loop:

Iterates over all item tags, regardless if their depth.

Reads 3 tags from the current item.

Appends a row to the result DataFrame.

Body:
I have below xml data.

<transaction>
        <date>20190415</date>
        <ticket>303434037</ticket>
        <value>15</value>
        <notenders>01</notenders>
        <tenderdetail>
            <tendertype>00</tendertype>
            <tenderamt>15</tenderamt>
        </tenderdetail>
        <item>
            <receipeno>00001096</receipeno>
            <price>7</price>
            <qty>0001</qty>
            <items>
                <item>
                    <receipeno>00000786</receipeno>
                    <price>8</price>
                    <qty>0001</qty>
                    <items>
                        <item>
                            <receipeno>00000599</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000605</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                        <item>
                            <receipeno>00000608</receipeno>
                            <price>0</price>
                            <qty>0004</qty>
                        </item>
                    </items>
                </item>
                <item>
                    <receipeno>10000043</receipeno>
                    <price>0</price>
                    <qty>0001</qty>
                </item>
                <item>
                    <receipeno>00000381</receipeno>
                    <price>7</price>
                    <qty>0001</qty>
                    <items>
                    <item>
                            <receipeno>00000607</receipeno>
                            <price>0</price>
                            <qty>1</qty>
                        </item>
                    </items>
                </item>
            </items>
        </item>
   </transaction>

I need to convert this to a table format. the issues is there are many nested branches inside each tag. eg many <item> & <items> tags. irrespective of the nested-ness. I need to list down the data one below he other.

my desired output is as follows

 +----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
|   date   | ticket | value | notenders | tendertype | tenderamt | receipeno | price | qty |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+
| 20190101 |  12345 |    15 |         1 |          0 |        15 |      1096 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       786 |     8 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       599 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       605 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       608 |     0 |   4 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       143 |     0 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       381 |     7 |   1 |
| 20190101 |  12345 |    15 |         1 |          0 |        15 |       607 |     0 |   1 |
+----------+--------+-------+-----------+------------+-----------+-----------+-------+-----+

I'm new to python & XML parsing. Hence, kindly, direct me to solve this.
...

Body:
Start from necessary imports:

import pandas as pd
import xml.etree.ElementTree as et
import re

Then, to remove leading zeroes from tags to be read, define the following function:

def stripLZ(src):
    return re.sub(r'^0+(?=\d)', '', src)

To read the source file and its root element, execute:

tree = et.parse('transaction.xml')
root = tree.getroot()

To read tags from the root level (other than read from items), execute:

dt = root.find('date').text
tck = root.find('ticket').text
val = root.find('value').text
notend = stripLZ(root.find('notenders').text)

Two remaining tags are one level down, so start from reading their parent tag:

tdet = root.find('tenderdetail')

and read these tags from it:

tendtyp = stripLZ(tdet.find('tendertype').text)
tendamt = tdet.find('tenderamt').text

Note that I used stripLZ function here (it will be used
a few times more).

Now there is time to create the result DataFrame:

df_cols = ['date', 'ticket', 'value', 'notenders',
    'tendertype', 'tenderamt', 'receipeno', 'price', 'qty']
df = pd.DataFrame(columns = df_cols)

And the loading loop can be performed using iter method:

for it in root.iter('item'):
    rcp = it.find('receipeno').text
    prc = it.find('price').text
    qty = stripLZ(it.find('qty').text)
    df = df.append(pd.Series([dt, tck, val, notend,
        tendtyp, tendamt, rcp, prc, qty],
        index = df_cols), ignore_index=True)

This loop:

Iterates over all item tags, regardless if their depth.

Reads 3 tags from the current item.

Appends a row to the result DataFrame.


问:
Array from firebase database call logs correct data but length shows 0
I am making a call to the database and grabbing each of the map items from an array and storing them in an array that I am returning. The array shows the correct data if I log to the console but the array seems to be empty when I try to reference any of the data and the length of the array is also zero.

```<code>$(document).ready(function(){
    //This ('click','li') binds all dynamically added shit to respond to click.
    $('ul.hiddentext').on('click','li', function(e){
        $(this).siblings().css('font-weight','normal');
        $(this).css('font-weight','bolder');
        let text = $(this).text();
        currentWorkoutSelected = text;
        var exercises = pullWorkoutTableData(text)
        console.log(exercises.length);
        var workout = new workoutTemplate(text, user, exercises);
        workout.populateTable();

        //Populate the title of the workout based on if its already there or not.
        if($('h4#workoutTitle').length == 0){
            $("table.exerciseList").prepend('<h4 id="workoutTitle">'+ text+ '</h4>');
        }
        else{
            $('h4#workoutTitle').replaceWith('<h4 id="workoutTitle">'+ text+ '</h4>');
        };
    });
});

//Taking the data needed for the workout table from the database.
function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
    });
    console.log(exerciseList);
    this.setState({exerciseList});
    return exerciseList;
};
</code>```

Expecting to be able to call the populateTable function but the object isnt created correctly because the array is empty.

答:
Problem is db.collection returns a promise, and the data is not yet available when you log it.

you can try a couple of things here:

Move your set state into the listener, if you only care about the React state

```<code>function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
        this.setState({exerciseList}); // <---- HERE
    });

    return exerciseList;
};
</code>```

Another thing you can do is to use an async/await function, but probably to update the state is enough for your case :)

If you browser support it.

```<code>function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    return db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
        return Promise.resolve({ exerciseList })
    });
};
$(document).ready(async function(){
    //This ('click','li') binds all dynamically added shit to respond to click.
    $('ul.hiddentext').on('click','li', function(e){
        $(this).siblings().css('font-weight','normal');
        $(this).css('font-weight','bolder');
        let text = $(this).text();
        currentWorkoutSelected = text;
        var { exerciseList: exercises } = await pullWorkoutTableData(text)
        console.log(exercises.length);
        var workout = new workoutTemplate(text, user, exercises);
        workout.populateTable();

        //Populate the title of the workout based on if its already there or not.
        if($('h4#workoutTitle').length == 0){
            $("table.exerciseList").prepend('<h4 id="workoutTitle">'+ text+ '</h4>');
        }
        else{
            $('h4#workoutTitle').replaceWith('<h4 id="workoutTitle">'+ text+ '</h4>');
        };
    });
});
</code>```

Body:
I am making a call to the database and grabbing each of the map items from an array and storing them in an array that I am returning. The array shows the correct data if I log to the console but the array seems to be empty when I try to reference any of the data and the length of the array is also zero.

$(document).ready(function(){
    //This ('click','li') binds all dynamically added shit to respond to click.
    $('ul.hiddentext').on('click','li', function(e){
        $(this).siblings().css('font-weight','normal');
        $(this).css('font-weight','bolder');
        let text = $(this).text();
        currentWorkoutSelected = text;
        var exercises = pullWorkoutTableData(text)
        console.log(exercises.length);
        var workout = new workoutTemplate(text, user, exercises);
        workout.populateTable();

        //Populate the title of the workout based on if its already there or not.
        if($('h4#workoutTitle').length == 0){
            $("table.exerciseList").prepend('
'+ text+ '
');
        }
        else{
            $('h4#workoutTitle').replaceWith('
'+ text+ '
');
        };
    });
});

//Taking the data needed for the workout table from the database.
function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
    });
    console.log(exerciseList);
    this.setState({exerciseList});
    return exerciseList;
};

Expecting to be able to call the populateTable function but the object isnt created correctly because the array is empty.

Body:
Problem is db.collection returns a promise, and the data is not yet available when you log it.

you can try a couple of things here:

Move your set state into the listener, if you only care about the React state

function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
        this.setState({exerciseList}); // <---- HERE
    });

    return exerciseList;
};

Another thing you can do is to use an async/await function, but probably to update the state is enough for your case :)

If you browser support it.

function pullWorkoutTableData(workoutName){
    var exerciseList = [];
    return db.collection('workouts').get().then((snapshot)=>{
        snapshot.docs.forEach(doc => {
            if(doc.data().name === workoutName && doc.data().user.includes(user)){
                doc.data().exercises.forEach(element =>{
                    var exercise = [element.name, element.weight, element.reps];
                    exerciseList.push(exercise);
                });
            };
        });
        return Promise.resolve({ exerciseList })
    });
};
$(document).ready(async function(){
    //This ('click','li') binds all dynamically added shit to respond to click.
    $('ul.hiddentext').on('click','li', function(e){
        $(this).siblings().css('font-weight','normal');
        $(this).css('font-weight','bolder');
        let text = $(this).text();
        currentWorkoutSelected = text;
        var { exerciseList: exercises } = await pullWorkoutTableData(text)
        console.log(exercises.length);
        var workout = new workoutTemplate(text, user, exercises);
        workout.populateTable();

        //Populate the title of the workout based on if its already there or not.
        if($('h4#workoutTitle').length == 0){
            $("table.exerciseList").prepend('<h4 id="workoutTitle">'+ text+ '</h4>');
        }
        else{
            $('h4#workoutTitle').replaceWith('<h4 id="workoutTitle">'+ text+ '</h4>');
        };
    });
});


问:
How to Updating Existing Assets? - Hyperledger Composer
I am trying to update and Asset in hyperledger, in this case   I am trying to add a new provider to a provider array list in the Asset  but hthe composer dont let me.

I dont know what is wrong.  Belor are the model, the javascript and the error.

Model:

```<code>/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace org.acme.Bicycle

asset Bicycle identified by serial {
  o String serial
  --> Rider owner optional
  --> Rider [] ownerold optional
  --> Provider [] distribuold optional
  --> Store [] Storeold optional
  --> Manufacturing manufacturing
}

abstract participant User identified by email {
  o String email
  o String firstName
  o String lastName
}

participant Rider extends User {

}

participant Manufacturing extends User {

}

participant Provider extends User {

}

participant Store extends User {

}

participant Police extends User {

}

transaction check {
  o String date
  o String Description
  --> Rider owner
  --> Police police
  --> Bicycle bike
}

transaction fabrictodistri {
    o String Description
    --> Manufacturing manufacturing
    --> Bicycle bike
    --> Provider providerstore
}

transaction providertostore {
    o String Description
    --> Bicycle bike
    --> Provider providerstore
    --> Store Storeold
}

transaction storetobiker {
    o String Description
    --> Bicycle bike
    --> Store Storeold
    --> Rider owner
}
</code>```

Script file: here is all my functions

```<code>/**
   * @param {org.acme.Bicycle.check} check
   * @transaction
*/
async function check(check) {
  let owner = check.bike.owner.email;
  let  ciclista = check.owner.email;

  if(owner != ciclista){
    check.description= "This is not the owner";
    throw new Error('This is not the owner');
  }else{
    check.description= "This is the owner";
    throw new Error('This is not the owner');
  }

}

/**
   * @param {org.acme.Bicycle.fabrictodistri} ftod
   * @transaction
*/
async function fabrictodistri(ftod) {
      let bike = ftod.bike;
       bike.distribuold.push(ftod.providerstore);

}

/**
   * @param {org.acme.Bicycle.providertostore} ptosto
   * @transaction
*/
async function providertostore(ptosto) {

   let bike = ptosto.bike;
   bike.distribuold.push(ptosto.providerstore);
   bike.Storeold.push(ptosto.Storeold);

}

/**
   * @param {org.acme.Bicycle.storetobiker} stostobik
   * @transaction
*/
async function storetobiker(stostobik) {

   let bike = stostobik.bike;
    bike.ownerold.push(stostobik.owner);
    bike.owner = stostobik.owner;

}
</code>```

Error: "TypeError: Cannot read property 'push' of undefined"

Image

答:
I faced the same issue. Turns out you probably can't push to a array which is empty/undefined.

I used the following fix for that (Modify it according to your program) :

if (typeof roj.contributors == 'undefined') { // Check if the array is empty
        roj.contributors = new Array();
        roj.contributors[0] = createROData.creator;
    }
    else {
        roj.contributors.push(createROData.creator);
    }```

Body:
I am trying to update and Asset in hyperledger, in this case   I am trying to add a new provider to a provider array list in the Asset  but hthe composer dont let me.

I dont know what is wrong.  Belor are the model, the javascript and the error.

Model:

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace org.acme.Bicycle

asset Bicycle identified by serial {
  o String serial
  --> Rider owner optional
  --> Rider [] ownerold optional
  --> Provider [] distribuold optional
  --> Store [] Storeold optional
  --> Manufacturing manufacturing
}

abstract participant User identified by email {
  o String email
  o String firstName
  o String lastName
}

participant Rider extends User {

}

participant Manufacturing extends User {

}

participant Provider extends User {

}

participant Store extends User {

}

participant Police extends User {

}

transaction check {
  o String date
  o String Description
  --> Rider owner
  --> Police police
  --> Bicycle bike
}

transaction fabrictodistri {
    o String Description
    --> Manufacturing manufacturing
    --> Bicycle bike
    --> Provider providerstore
}

transaction providertostore {
    o String Description
    --> Bicycle bike
    --> Provider providerstore
    --> Store Storeold
}

transaction storetobiker {
    o String Description
    --> Bicycle bike
    --> Store Storeold
    --> Rider owner
}

Script file: here is all my functions

/**
   * @param {org.acme.Bicycle.check} check
   * @transaction
*/
async function check(check) {
  let owner = check.bike.owner.email;
  let  ciclista = check.owner.email;

  if(owner != ciclista){
    check.description= "This is not the owner";
    throw new Error('This is not the owner');
  }else{
    check.description= "This is the owner";
    throw new Error('This is not the owner');
  }

}

/**
   * @param {org.acme.Bicycle.fabrictodistri} ftod
   * @transaction
*/
async function fabrictodistri(ftod) {
      let bike = ftod.bike;
       bike.distribuold.push(ftod.providerstore);

}

/**
   * @param {org.acme.Bicycle.providertostore} ptosto
   * @transaction
*/
async function providertostore(ptosto) {

   let bike = ptosto.bike;
   bike.distribuold.push(ptosto.providerstore);
   bike.Storeold.push(ptosto.Storeold);

}

/**
   * @param {org.acme.Bicycle.storetobiker} stostobik
   * @transaction
*/
async function storetobiker(stostobik) {

   let bike = stostobik.bike;
    bike.ownerold.push(stostobik.owner);
    bike.owner = stostobik.owner;

}

Error: "TypeError: Cannot read property 'push' of undefined"

Image


问:
C# - skip generics
How I can pass parameters of a generic type in my methods?</p>

```<code>public Type<T, U, V> { ... }

public void Method(??? arg) // where ??? is Type<T, U, V>
{
  ...
}
</code>```

答:
You'll have to make the method itself generic:  </p>

```<code>public void Method<T, U, V>(Type<T, U, V> arg) {
  // ...
}
</code>```

Title: C# - skip generics

Body:
How I can pass parameters of a generic type in my methods?

public Type<T, U, V> { ... }

public void Method(??? arg) // where ??? is Type<T, U, V>
{
  ...
}

Body:
You'll have to make the method itself generic:

public void Method<T, U, V>(Type<T, U, V> arg) {
  // ...
}


问:
Check if the browser tab is in focus in ReactJS
I have a website in ReactJS. I want to get a callback whenever my tab comes in focus or is hidden. I came across the Page Visibility API for this but I'm not able to figure out how to use it in ReactJS.

In which lifecycle method do I register the callback for this?

答:
There is no reliable method to check it, so you need to combine few methods together. Here is Context for react-hooks</p>
```<code>import React, { useState, useEffect } from 'react'

export const WindowContext = React.createContext(null)

export const WindowContextProvider = props => {
  const [windowIsActive, setWindowIsActive] = useState(true)

  function handleActivity(forcedFlag) {
    if (typeof forcedFlag === 'boolean') {
      return forcedFlag ? setWindowIsActive(true) : setWindowIsActive(false)
    }

    return document.hidden ? setWindowIsActive(false) : setWindowIsActive(true)
  }

  useEffect(() => {
    const handleActivityFalse = () => handleActivity(false)
    const handleActivityTrue = () => handleActivity(true)

    document.addEventListener('visibilitychange', handleActivity)
    document.addEventListener('blur', handleActivityFalse)
    window.addEventListener('blur', handleActivityFalse)
    window.addEventListener('focus', handleActivityTrue )
    document.addEventListener('focus', handleActivityTrue)

    return () => {
      window.removeEventListener('blur', handleActivity)
      document.removeEventListener('blur', handleActivityFalse)
      window.removeEventListener('focus', handleActivityFalse)
      document.removeEventListener('focus', handleActivityTrue )
      document.removeEventListener('visibilitychange', handleActivityTrue )
    }
  }, [])

  return <WindowContext.Provider value={{ windowIsActive }}>{props.children}</WindowContext.Provider>
}
</code>```

Body:
There is no reliable method to check it, so you need to combine few methods together. Here is Context for react-hooks

import React, { useState, useEffect } from 'react'

export const WindowContext = React.createContext(null)

export const WindowContextProvider = props => {
  const [windowIsActive, setWindowIsActive] = useState(true)

  function handleActivity(forcedFlag) {
    if (typeof forcedFlag === 'boolean') {
      return forcedFlag ? setWindowIsActive(true) : setWindowIsActive(false)
    }

    return document.hidden ? setWindowIsActive(false) : setWindowIsActive(true)
  }

  useEffect(() => {
    const handleActivityFalse = () => handleActivity(false)
    const handleActivityTrue = () => handleActivity(true)

    document.addEventListener('visibilitychange', handleActivity)
    document.addEventListener('blur', handleActivityFalse)
    window.addEventListener('blur', handleActivityFalse)
    window.addEventListener('focus', handleActivityTrue )
    document.addEventListener('focus', handleActivityTrue)

    return () => {
      window.removeEventListener('blur', handleActivity)
      document.removeEventListener('blur', handleActivityFalse)
      window.removeEventListener('focus', handleActivityFalse)
      document.removeEventListener('focus', handleActivityTrue )
      document.removeEventListener('visibilitychange', handleActivityTrue )
    }
  }, [])

  return <WindowContext.Provider value={{ windowIsActive }}>{props.children}</WindowContext.Provider>
}


问:
How to parse JSON array to a spinner
I want to parse a JSON file with nested arrays and objects, and use the parsed info to populate a spinner.
Now I'm stuck in the progress window, only showing "loading"...I only want to extract the name tag (navn) to the spinner, and nsrID stored in a variable, for later use.

JSON format:

```<code>[
  {
    "nsrId": "1018038",
    "koordinatLatLng": [
      59.6908,
      9.04228
    ],
    "navn": "Gransherad barnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Kommunal",
    "antallBarn": 26
  },
  {
    "nsrId": "1012983",
    "koordinatLatLng": [
      59.5763,
      9.19806
    ],
    "navn": "Trolldalen Gårdsbarnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Privat",
    "antallBarn": 24
  },
</code>```

etc...

My code:

```<code>    spinner = findViewById(R.id.barneHage_Spinner);

    hentJSON();
}

private void hentJSON() {
    showSimplProgressDialog(this, "loading...", "Henter Json", false);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, barnehager_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("strrrrr", ">>" + response);

                    try {
                        JSONObject obj = new JSONObject(response);

                        barnehageArrayList = new ArrayList<>();
                        JSONArray dataArray = obj.getJSONArray("navn");

                        for (int i = 0; i < dataArray.length(); i++) {
                            Barnehage model = new Barnehage();
                            JSONObject dataobj = dataArray.getJSONObject(i);

                            model.setNavn(dataobj.getString("navn"));
                           // model.setNsrId(dataArray.getNsrId(Integer.parseInt("nsrId")));

                            barnehageArrayList.add(model);
                        }

                        for (int i = 0; i < barnehageArrayList.size(); i++) {
                            names.add(barnehageArrayList.get(i).getNavn());
                        }
                        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(BarneHager.this, simple_spinner_item, names);
                        spinner.setAdapter(spinnerArrayAdapter);
                        removeSimpleProgressDialog();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
</code>```

I expect the output to be a spinner with the only values showing

```<code>1: Gransherad barnehage
2: Trolldalen Gårdsbarnehage
3: ..
4: ..
</code>```

etc

答:
You have to add an item at zero position of your list

```<code>barnehageArrayList.add(0,new MODELCLASS("Select option"))
</code>```

And add below code to populate your Spinner

```<code>SPINNER_NAME.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            if (position != 0) {

            } else {

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

Title: How to parse JSON array to a spinner

Body:
I want to parse a JSON file with nested arrays and objects, and use the parsed info to populate a spinner.
Now I'm stuck in the progress window, only showing "loading"...I only want to extract the name tag (navn) to the spinner, and nsrID stored in a variable, for later use.

JSON format:

[
  {
    "nsrId": "1018038",
    "koordinatLatLng": [
      59.6908,
      9.04228
    ],
    "navn": "Gransherad barnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Kommunal",
    "antallBarn": 26
  },
  {
    "nsrId": "1012983",
    "koordinatLatLng": [
      59.5763,
      9.19806
    ],
    "navn": "Trolldalen Gårdsbarnehage",
    "fylkesnummer": "08",
    "kommunenummer": "0807",
    "alder": "1 - 5",
    "eierform": "Privat",
    "antallBarn": 24
  },

etc...

My code:

    spinner = findViewById(R.id.barneHage_Spinner);

    hentJSON();
}

private void hentJSON() {
    showSimplProgressDialog(this, "loading...", "Henter Json", false);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, barnehager_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("strrrrr", ">>" + response);

                    try {
                        JSONObject obj = new JSONObject(response);

                        barnehageArrayList = new ArrayList<>();
                        JSONArray dataArray = obj.getJSONArray("navn");

                        for (int i = 0; i < dataArray.length(); i++) {
                            Barnehage model = new Barnehage();
                            JSONObject dataobj = dataArray.getJSONObject(i);

                            model.setNavn(dataobj.getString("navn"));
                           // model.setNsrId(dataArray.getNsrId(Integer.parseInt("nsrId")));

                            barnehageArrayList.add(model);
                        }

                        for (int i = 0; i < barnehageArrayList.size(); i++) {
                            names.add(barnehageArrayList.get(i).getNavn());
                        }
                        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(BarneHager.this, simple_spinner_item, names);
                        spinner.setAdapter(spinnerArrayAdapter);
                        removeSimpleProgressDialog();

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

I expect the output to be a spinner with the only values showing

1: Gransherad barnehage
2: Trolldalen Gårdsbarnehage
3: ..
4: ..

etc

Body:
You have to add an item at zero position of your list

barnehageArrayList.add(0,new MODELCLASS("Select option"))

And add below code to populate your Spinner

SPINNER_NAME.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            if (position != 0) {

            } else {

            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


问:
How to install tensorflow with Conda
I have been trying to install tensorflow via Conda for a couple days now with no luck.

I made a fresh install of anaconda3/miniconda3 followed the steps to fix the .bash_profile issue. Then

$ conda create -n tensorflow pip python=3.6

seems to work. However

$ source activate tensorflow

does nothing. I tried conda activate tensorflow and nothing. If I type conda info I can see that the tensorflow env is running. But I have no ability to type within it?

答:
You should first give a name to your environment then give package names that you want to install ie.
        conda create -n tensorflow_env tensorflow

Easiest way for me at least.

Title: How to install tensorflow with Conda


问:
How do you add two Class Member Functions together with another function inside the same class?

I have two functions in my class, we'll say:

```<code>double MyClass::FunctionOne() {
    double Number = 1.5;
    return Number;
}
</code>```

and

```<code>double MyClass::FunctionTwo(double x, double y, double z, double w) {
    total = x+y+z+w;
    return total;
}
</code>```

assume that "total" is a double declared in the class header

How exactly do I add the returned values of both of these functions after my object has been instantiated in main?

In main, we'll assume it looks like this:

```<code>MyClass Object();
std::cout << "Function One: " << Object.FunctionOne()
          << "Function Two: " << Object.FunctionTwo(1.1, 2.2, 3.3, 4.4);
</code>```

Is there a way to sum these two functions in a separate function inside the class? And then call it using an accessor or something? Or must I do it like this:

```<code>double CombineFunctions(double x, double y) {
    double total2 = (x + y);
    return total2;
}

std::cout << "Sum of both functions: "
<< CombineFunctions(Object.FunctionOne(), Object.FunctionTwo(1.1, 2.2, 3.3, 4.4));
</code>```

I'm fairly new at C++, so I don't actually know how to do this. I tried researching for a few hours but couldn't really find anything or wrap my head around it.

What I've tried: The closest I've got was declaring two variables in the class, then using them inside the class functions, and attempting to return them as:

```<code>double MyClass::SumOfReturns() {
    return total1 + total2;
}
</code>```

but the number I received was what I think was a memory location? 163423e19 or something.

答:
You can store the results in class's members, and you can store the results in variables inside your main function:</p>

```<code>MyClass Object();
double res1, res2;
res1 = Object.FunctionOne();
res2 = Object.FunctionTwo(1.1, 2.2, 3.3, 4.4);
std::cout << "Function One: " << res1 << "Function Two: " << res2 << std::endl;
std::cout << "Sum of both functions: " << res1 + res2 << std::endl;
</code>```

Body:
I have two functions in my class, we'll say:

double MyClass::FunctionOne() {
    double Number = 1.5;
    return Number;
}

and

double MyClass::FunctionTwo(double x, double y, double z, double w) {
    total = x+y+z+w;
    return total;
}

assume that "total" is a double declared in the class header

How exactly do I add the returned values of both of these functions after my object has been instantiated in main?

In main, we'll assume it looks like this:

MyClass Object();
std::cout << "Function One: " << Object.FunctionOne()
          << "Function Two: " << Object.FunctionTwo(1.1, 2.2, 3.3, 4.4);

Is there a way to sum these two functions in a separate function inside the class? And then call it using an accessor or something? Or must I do it like this:

double CombineFunctions(double x, double y) {
    double total2 = (x + y);
    return total2;
}

std::cout << "Sum of both functions: "
<< CombineFunctions(Object.FunctionOne(), Object.FunctionTwo(1.1, 2.2, 3.3, 4.4));

I'm fairly new at C++, so I don't actually know how to do this. I tried researching for a few hours but couldn't really find anything or wrap my head around it.

What I've tried: The closest I've got was declaring two variables in the class, then using them inside the class functions, and attempting to return them as:

double MyClass::SumOfReturns() {
    return total1 + total2;
}

but the number I received was what I think was a memory location? 163423e19 or something.

Body:
You can store the results in class's members, and you can store the results in variables inside your main function:

MyClass Object();
double res1, res2;
res1 = Object.FunctionOne();
res2 = Object.FunctionTwo(1.1, 2.2, 3.3, 4.4);
std::cout << "Function One: " << res1 << "Function Two: " << res2 << std::endl;
std::cout << "Sum of both functions: " << res1 + res2 << std::endl;